Esempio n. 1
0
        public void MergePDFs(string outPutFilePath, params string[] filesPath)
        {
            try
            {
                List <PdfReader> readerList = new List <PdfReader>();
                foreach (string filePath in filesPath)
                {
                    PdfReader pdfReader = new PdfReader(filePath);
                    readerList.Add(pdfReader);
                }

                iTextSharp.text.Document    document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0f, 0f, 0f, 20f);
                iTextSharp.text.pdf.PdfCopy writer   = new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(outPutFilePath, System.IO.FileMode.Create));

                document.Open();
                foreach (PdfReader reader in readerList)
                {
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        document.Add(iTextSharp.text.Image.GetInstance(page));
                    }

                    writer.AddDocument(reader);
                    reader.Close();
                }
                document.Close();
                writer.Close();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
Esempio n. 2
0
        public static void MergePdf()
        {
            using (var fs = new FileStream(@"C:\Projects\31g\trunk\Notes\misc\OccidentalMaps.pdf", FileMode.Create))
            {
                var doc = new iTextSharp.text.Document();
                var pdf = new iTextSharp.text.pdf.PdfCopy(doc, fs);
                doc.Open();

                foreach (var file in Directory.GetFiles(@"C:\Projects\31g\trunk\Notes\misc\WestMaps"))
                {
                    pdf.AddDocument(new iTextSharp.text.pdf.PdfReader(file));
                }

                doc.Close();
            }
        }
Esempio n. 3
0
 //Code found on net
 /// <summary>
 /// Gets the 2 file names in the array and adds in that specific order
 /// </summary>
 /// <param name="fileNames"></param>
 /// <param name="targetPdfName"></param>
 /// <returns></returns>
 private static bool MergePDFs(string[] fileNames, string targetPdfName)
 {
     bool merged = true;
     using (FileStream stream = new FileStream(targetPdfName, FileMode.Create))
     {
         Document document = new Document();
         PdfCopy pdf = new PdfCopy(document, stream);
         PdfReader reader = null;
         try
         {
             document.Open();
             foreach (string file in fileNames)
             {
                 reader = new PdfReader(file);
                 pdf.AddDocument(reader);
                 reader.Close();
             }
         }
         catch (Exception)
         {
             merged = false;
             if (reader != null)
             {
                 reader.Close();
             }
         }
         finally
         {
             if (document != null)
             {
                 document.Close();
             }
         }
     }
     return merged;
 }
        public bool PdfMerger(string[] fileNames, string targetPdf)
        {
           
            try
            {

                bool merged = true;
                using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
                {
                    Document document = new Document();
                    PdfCopy pdf = new PdfCopy(document, stream);
                    PdfReader reader = null;
                    try
                    {
                        document.Open();
                        foreach (string file in fileNames)
                        {
                            reader = new PdfReader(file);
                            pdf.AddDocument(reader);
                            reader.Close();
                        }
                    }
                    catch (Exception)
                    {
                        merged = false;
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    finally
                    {
                        if (document != null)
                        {
                            document.Close();
                        }
                    }
                }
                return merged;
               
            }
            catch (Exception e)
            {
                LogHelper.Logger(commandType + e.Message, _logPath);
                return false;
            }
            
 
        }
Esempio n. 5
0
        public static Blob.Blob MergePdfBlobsToC(List<Blob.Blob> blobsParam, ref Dictionary<string, int> pages)
        {
            blobsParam = blobsParam
                .Where(el => el != null && el.Data != null)
                .ToList();

            //Dictionary of file names (for display purposes) and their page numbers
            //var pages = new Dictionary<string, int>();

            //PDFs start at page 1
            var lastPageNumber = 1;

            //Will hold the final merged PDF bytes
            byte[] mergedBytes;

            //Most everything else below is standard
            using (var ms = new MemoryStream())
            {
                using (var document = new Document())
                {
                    using (var writer = new PdfCopy(document, ms))
                    {
                        document.Open();

                        foreach (var blob in blobsParam)
                        {

                            //Add the current page at the previous page number
                            pages.Add(blob.Name, lastPageNumber);

                            using (var reader = new PdfReader(blob.Data))
                            {
                                writer.AddDocument(reader);

                                //Increment our current page index
                                lastPageNumber += reader.NumberOfPages;
                            }
                        }
                        document.Close();
                    }
                }
                mergedBytes = ms.ToArray();
            }

            //Will hold the final PDF
            //            byte[] finalBytes;
            //            using (var ms = new MemoryStream())
            //            {
            //                using (var reader = new PdfReader(mergedBytes))
            //                {
            //                    using (var stamper = new PdfStamper(reader, ms))
            //                    {
            //
            //                        //The page number to insert our TOC into
            //                        var tocPageNum = reader.NumberOfPages + 1;
            //
            //                        //Arbitrarily pick one page to use as the size of the PDF
            //                        //Additional logic could be added or this could just be set to something like PageSize.LETTER
            //                        var tocPageSize = reader.GetPageSize(1);
            //
            //                        //Arbitrary margin for the page
            //                        var tocMargin = 20;
            //
            //                        //Create our new page
            //                        stamper.InsertPage(tocPageNum, tocPageSize);
            //
            //                        //Create a ColumnText object so that we can use abstractions like Paragraph
            //                        var ct = new ColumnText(stamper.GetOverContent(tocPageNum));
            //
            //                        //Set the working area
            //                        ct.SetSimpleColumn(tocPageSize.GetLeft(tocMargin), tocPageSize.GetBottom(tocMargin),
            //                            tocPageSize.GetRight(tocMargin), tocPageSize.GetTop(tocMargin));
            //
            //                        //Loop through each page
            //                        foreach (var page in pages)
            //                        {
            //                            var link = new Chunk(page.Key);
            //                            var action = PdfAction.GotoLocalPage(page.Value, new PdfDestination(PdfDestination.FIT),
            //                                stamper.Writer);
            //                            link.SetAction(action);
            //                            ct.AddElement(new Paragraph(link));
            //                        }
            //
            //                        ct.Go();
            //                    }
            //                }
            //                finalBytes = ms.ToArray();
            //            }

            var toReturn = new Blob.Blob { Data = mergedBytes/*finalBytes*/ };
            return toReturn;
        }
Esempio n. 6
0
        public static byte[] Merge(List<byte[]> filesContents)
        {
            using (var memoryStream = new MemoryStream())
            {
                var document = new Document();
                var pdf = new PdfCopy(document, memoryStream);
                PdfReader reader = null;

                try
                {
                    document.Open();

                    foreach (byte[] fileContent in filesContents)
                    {
                        reader = new PdfReader(fileContent);
                        pdf.AddDocument(reader);
                        reader.Close();
                    }
                }
                catch (Exception)
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    if (document != null)
                    {
                        document.Close();
                    }
                }

                return memoryStream.ToArray();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetPDF"></param>
        /// <param name="selectedFiles"></param>
        public void CreateMergedPDF(string targetPDF, List<string> selectedFiles )
        {
            using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.LETTER);
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();

                logger.Debug("Merging files count: " + selectedFiles.Count);
                int i = 1;
                foreach (string file in selectedFiles)
                {
                    logger.Debug(i + ". Adding: " + file);
                    pdf. AddDocument(new PdfReader(file));
                    i++;
                }

                if (pdfDoc != null)
                    pdfDoc.Close();

                logger.Debug(" PDF merge complete.");
            }
        }
Esempio n. 8
0
        static void CreateMergedPDF(string targetPDF, string sourceDir)
        {
            using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4);
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();
                var files = Directory.GetFiles(sourceDir);

                int i = 1;
                foreach (string file in files)
                {
                    int cnt = file.Length;
                    pdf.AddDocument(new PdfReader(file));
                    i++;
                }

                if (pdfDoc != null)
                    pdfDoc.Close();

            }
        }
Esempio n. 9
0
        public HttpResponseMessage Merge(string urls)
        {
            var urlArray = urls.Split(',');

            var wc = new WebClient();
            var pdfContents = urlArray.Select(u => Download(wc, u)).ToList();
            byte[] mergedPdf = null;
            using (var ms = new MemoryStream())
            {
                using (var document = new Document())
                {
                    using (var copy = new PdfCopy(document, ms))
                    {
                        document.Open();                 
                        pdfContents.ForEach(c => {
                            if (c != null) copy.AddDocument(new PdfReader(c));
                        });
                    }
                }
                mergedPdf = ms.ToArray();
            }
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(mergedPdf);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return response;
        }
Esempio n. 10
0
        public bool MergePDFs(IEnumerable<string> fileNames, string targetPdf)
        {
            bool merged = true;

            preProcess();

            using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
            {
                Document document = new Document();
                PdfCopy pdf = new PdfCopy(document, stream);
                PdfReader reader = null;
                try
                {
                    document.Open();
                    foreach (string file in fileNames)
                    {
                        reader = new PdfReader(file);
                        pdf.AddDocument(reader);

                        // 아래 함수 호출로 중간중간 Form의 이벤트를 처리해주어 
                        // "현재 Form이 "응답없음"에 빠지지 않게 함. 
                        Application.DoEvents();

                        mParent.Invoke(new MethodInvoker(delegate()
                            {
                                ///실행할 내용
                                mMergeProgressBar.Value++;
                                mMergeProgressBar.Text = mMergeProgressBar.Value.ToString();
                            }
                        ));

                        reader.Close();
                    }

#if false
                    //progressbar 닫기
                    mParent.Invoke(new MethodInvoker(
                        delegate()
                        {
                            ///실행할 내용
                            mMergeProgressBar.close();
                        }
                    )
               );

                    
#endif
                }
                catch (Exception)
                {
                    merged = false;
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    if (document != null)
                    {
                        document.Close();
                    }
                }
            }
            return merged;
        }
Esempio n. 11
0
        public virtual void TestNeedAppearancesMixed() {
            String f1 = RESOURCES + "appearances1.pdf";
            String f2 = RESOURCES + "appearances2(needAppearancesFalse).pdf";
            String f3 = RESOURCES + "appearances3(needAppearancesFalseWithStreams).pdf";
            String f4 = RESOURCES + "appearances4.pdf";

            Directory.CreateDirectory("PdfCopyTest/");
            FileStream outputPdfStream =
                new FileStream("PdfCopyTest/appearances(mixed).pdf", FileMode.Create);
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, outputPdfStream);
            copy.SetMergeFields();
            document.Open();
            foreach (String f in new String[] {f1, f2, f3, f4}) {
                PdfReader r = new PdfReader(f);
                copy.AddDocument(r);
            }
            copy.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/appearances(mixed).pdf", RESOURCES + "cmp_appearances(mixed).pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Esempio n. 12
0
        private Boolean unlockPDF(String r_password, String w_password)
        {
            Boolean NOPASS = true;

            ////////////////////////////////////////////////////
            // PDF解錠
            ////////////////////////////////////////////////////
            if (avaPDF)
            {
                // 一時ファイル取得
                String  tmpFilePath = Path.GetTempFileName();
                Boolean isRP        = false;
                Boolean isWP        = false;

                // パスワードなしで読み込めるかチェック
                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString());
                    isRP      = false; // ユーザーパスワードなし
                                       // オーナーパスワードが掛っているかチェック
                    isWP   = (pdfReader.IsEncrypted()) ? true : false;
                    NOPASS = !(isRP || isWP);
                    pdfReader.Close();
                    pdfReader.Dispose();
                } catch {
                    isRP   = true;
                    NOPASS = false;
                }
                if (NOPASS)
                {
                    // パスワードがかかっていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2;
                    //"This document is not applied password.";
                    pdfReader.Close();
                    pdfReader.Dispose();
                    return(false);
                }
                if (isRP && (r_password.Length == 0))
                {
                    // ユーザーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf3;
                    // "This document has been user password-protected.";
                    return(false);
                }
                if (isWP && (w_password.Length == 0))
                {
                    // オーナーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf4;
                    //"This document has been owner password-protected.";
                    return(false);
                }

                String rp = (r_password.Length == 0) ? null : r_password;
                String wp = (w_password.Length == 0) ? r_password : w_password;

                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString(), (byte[])System.Text.Encoding.ASCII.GetBytes(wp));
                } catch {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.message2;
                    // "Password is incorrect.";
                    return(false);
                }


                try {
                    pdfDoc  = new iTextSharp.text.Document(pdfReader.GetPageSize(1));
                    os      = new FileStream(tmpFilePath, FileMode.OpenOrCreate);
                    pdfCopy = new PdfCopy(pdfDoc, os);
                    pdfCopy.Open();

                    pdfDoc.Open();
                    pdfCopy.AddDocument(pdfReader);

                    pdfDoc.Close();
                    pdfCopy.Close();
                    pdfReader.Close();
                    pdfReader.Dispose();
                    // オリジナルファイルと一時ファイルを置き換える
                    System.IO.File.Copy(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString(), true);
                    System.IO.File.Delete(tmpFilePath);
                } catch (Exception eX) {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message;
                    // "Saving failed." + eX.Message;
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 13
0
        private Boolean lockPDF(String r_password, String w_password)
        {
            string rp = null, wp = null;

            ////////////////////////////////////////////////////
            // PDF施錠
            ////////////////////////////////////////////////////
            if (avaPDF)
            {
                // 一時ファイル取得
                String tmpFilePath = Path.GetTempFileName();

                // パスワードなしで読み込み可能かチェック
                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString());
                } catch {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf1;
                    // "This document has been password-protected.";
                    return(false);
                }
                // オーナーパスワードが掛っているかチェック
                if (pdfReader.IsEncrypted())
                {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2;
                    // "This document has been password-protected.";
                    return(false);
                }
                pdfDoc  = new iTextSharp.text.Document(pdfReader.GetPageSize(1));
                os      = new FileStream(tmpFilePath, FileMode.OpenOrCreate);
                pdfCopy = new PdfCopy(pdfDoc, os);
                // 出力ファイルにパスワード設定
                // rp:ユーザーパスワード
                // wp:オーナーパスワード(空の場合はユーザーパスワードと同じ値を設定)

                pdfCopy.Open();
                if (r_password.Length == 0)
                {
                    rp = null;
                }
                else
                {
                    rp = r_password;
                }
                if (w_password.Length == 0)
                {
                    wp = r_password;
                    pdfCopy.SetEncryption(
                        PdfCopy.STRENGTH128BITS, rp, wp,
                        PdfCopy.markAll);
                }
                else
                {
                    wp = w_password;
                    // AllowPrinting    印刷
                    // AllowCopy    内容のコピーと抽出
                    // AllowModifyContents  文書の変更
                    // AllowModifyAnnotations   注釈の入力
                    // AllowFillIn  フォーム・フィールドの入力と署名
                    // AllowScreenReaders   アクセシビリティのための内容抽出
                    // AllowAssembly    文書アセンブリ
                    pdfCopy.SetEncryption(
                        PdfCopy.STRENGTH128BITS, rp, wp,
                        PdfCopy.AllowScreenReaders | PdfCopy.AllowPrinting);
                }

                try {
                    // 出力ファイルDocumentを開く
                    pdfDoc.Open();
                    // アップロードPDFファイルの内容を出力ファイルに書き込む
                    pdfCopy.AddDocument(pdfReader);
                    // 出力ファイルDocumentを閉じる
                    pdfDoc.Close();
                    pdfCopy.Close();
                    os.Close();
                    pdfReader.Close();
                    // オリジナルファイルと一時ファイルを置き換える
                    File.Delete(dataGridView1.Rows[0].Cells[3].Value.ToString());
                    File.Move(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString());
                } catch (Exception eX) {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message;
                    // "Saving failed." + eX.Message;
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 14
0
        public virtual void LargeFilePerformanceTest() {
            const string target = "PdfCopyTest/";
            const string output = "copyLargeFile.pdf";
            const string cmp = "cmp_copyLargeFile.pdf";
            
            Directory.CreateDirectory(target);

            Stopwatch timer = new Stopwatch();
            timer.Start();

            PdfReader firstSourceReader = new PdfReader(RESOURCES + "frontpage.pdf");
            PdfReader secondSourceReader = new PdfReader(RESOURCES + "large_pdf.pdf");

            Document document = new Document();

            PdfCopy copy = new PdfCopy(document, File.Create(target + output));
            copy.SetMergeFields();

            document.Open();
            copy.AddDocument(firstSourceReader);
            copy.AddDocument(secondSourceReader);

            copy.Close();
            document.Close();

            timer.Stop();
            Console.WriteLine(timer.ElapsedMilliseconds);

            CompareTool cmpTool = new CompareTool();
            String errorMessage = cmpTool.CompareByContent(target + output, RESOURCES + cmp, target, "diff");

            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Esempio n. 15
0
        // PDF 파일 Merge하는 핵심 메소드
        private void MergePDFs(/*IEnumerable<string> fileNames, string targetPdf*/)
        {
            List<string> fileNames = mFileListToMerge;
            string targetPdf = mDestFilePath;
            int count = 0;
            Document document;
            PdfCopy pdfCopy;
            bool merged = true;

            using (FileStream destStream = new FileStream(targetPdf, FileMode.Create))
            {
                document = new Document();
                pdfCopy = new PdfCopy(document, destStream);  // 항상 PdfCopy는 Documnet.Open() 보다 먼저 생성되어야 한다.
                document.Open();
                PdfReader reader = null;

                try
                {
                    foreach (string file in fileNames)
                    {
                        reader = new PdfReader(file);

                        // 파일 합침.
                        pdfCopy.AddDocument(reader);

                        // 스레드 내부에서 Control 접근
                        this.setProgressBar(++count);
                        this.setMessage(string.Format("병합중입니다({0}/{1})", count, fileNames.Count));
                        reader.Close();
                    }

                }
                catch (Exception e)
                {
                    MessageBox.Show("error:" + e.Message);

                    merged = false;
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    if (document != null)
                    {
                        document.Close();
                        destStream.Close();
                    }

            #if false
                    // DialogResult에 값을 넣고 나서 이 함수를 빠져나가면 자동으로 Form이
                    // 종료되는 현상이 있음. 굳이 exitForm()을 호출하지 않아도 됨.
                    if (merged == true)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                    else
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                    }
            #endif

                    // Form 종료
                    if( merged == true)
                        this.exitForm(System.Windows.Forms.DialogResult.OK);
                    else
                        this.exitForm(System.Windows.Forms.DialogResult.Abort);
                }
            }
        }
Esempio n. 16
0
        public virtual void CopyFields3Test() {
            Document pdfDocument = new Document();
            Directory.CreateDirectory("PdfCopyTest/");
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream("PdfCopyTest/copyFields3.pdf", FileMode.Create));
            copier.SetMergeFields();
            pdfDocument.Open();

            PdfReader reader = new PdfReader(RESOURCES + "hello2_with_comments.pdf");
            copier.AddDocument(reader);
            copier.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/copyFields3.pdf", RESOURCES + "cmp_copyFields3.pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Esempio n. 17
0
        public virtual void CopyFields4Test() {
            string target = "PdfCopyTest/";
            Directory.CreateDirectory(target);
            const string outfile = "copyFields4.pdf";
            const string inputFile = "link.pdf";

            Document document = new Document();
            MemoryStream stream = new MemoryStream();
            PdfWriter.GetInstance(document, stream);
            Font font = new Font(BaseFont.CreateFont(RESOURCES + "fonts/georgia.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9);
            document.Open();
            document.Add(new Phrase("text", font));
            document.Close();

            Document pdfDocument = new Document();
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream(target + outfile, FileMode.Create));
            copier.SetMergeFields();
            pdfDocument.Open();

            PdfReader reader1 = new PdfReader(RESOURCES + inputFile);
            PdfReader reader2 = new PdfReader(stream.ToArray());

            copier.AddDocument(reader1);
            copier.AddDocument(reader2);
            copier.Close();
            CompareTool cmpTool = new CompareTool();
            string errorMessage = cmpTool.CompareByContent(target + outfile, RESOURCES + "cmp_" + outfile, target, "diff");
            if (errorMessage != null)
                Assert.Fail(errorMessage);
        }
Esempio n. 18
0
        public virtual void CopyFields1Test() {
            Document pdfDocument = new Document();
            Directory.CreateDirectory("PdfCopyTest/");
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream("PdfCopyTest/copyFields.pdf", FileMode.Create));
            copier.SetMergeFields();

            pdfDocument.Open();

            PdfReader readerMain = new PdfReader(RESOURCES + "fieldsOn3-sPage.pdf");
            PdfReader secondSourceReader = new PdfReader(RESOURCES + "fieldsOn2-sPage.pdf");
            PdfReader thirdReader = new PdfReader(RESOURCES + "appearances1.pdf");

            copier.AddDocument(readerMain);
            copier.CopyDocumentFields(secondSourceReader);
            copier.AddDocument(thirdReader);

            copier.Close();
            readerMain.Close();
            secondSourceReader.Close();
            thirdReader.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/copyFields.pdf", RESOURCES + "cmp_copyFields.pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Esempio n. 19
0
        public virtual void TestFullCompression2() {
            Directory.CreateDirectory("PdfCopyTest/");
            String outfile = "PdfCopyTest/out-forms.pdf";
            String first = RESOURCES + "subscribe.pdf";
            String second = RESOURCES + "filled_form_1.pdf";
            FileStream out_ = new FileStream(outfile, FileMode.Create);
            PdfReader reader = new PdfReader(first);
            PdfReader reader2 = new PdfReader(second);
            Document pdfDocument = new Document();
            PdfCopy pdfCopy = new PdfCopy(pdfDocument, out_);
            pdfCopy.SetMergeFields();
            pdfCopy.SetFullCompression();
            pdfCopy.CompressionLevel = PdfStream.BEST_COMPRESSION;
            pdfDocument.Open();
            pdfCopy.AddDocument(reader);
            pdfCopy.AddDocument(reader2);
            pdfCopy.Close();
            reader.Close();
            reader2.Close();

            reader = new PdfReader("PdfCopyTest/out-forms.pdf");
            Assert.NotNull(reader.GetPageN(1));
            reader.Close();
        }
Esempio n. 20
0
        public string MergePDFs(string[] transids)
        {
            string targetPDF = "PaymentReceipts" + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString() + ".pdf";
                targetPDF = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\" + targetPDF;
                using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
                {
                    Document pdfDoc = new Document();

                    PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                    pdfDoc.Open();
                    var files = Directory.GetFiles(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\");
                    Console.WriteLine("Merging files count: " + files.Length);
                    int i = 1;
                    foreach (string file in transids)
                    {
                        Console.WriteLine(i + ". Adding: " + file);
                        pdf.AddDocument(new PdfReader(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + file + ".pdf"));
                        i++;
                    }

                    if (pdfDoc != null)
                    {
                        pdfDoc.Close();
                        pdfDoc.Dispose();
                    }

                    return targetPDF;
                }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileNames"></param>
 /// <param name="outFile"></param>
 public static void CombineMultiplePDFs(string[] fileNames, string outFile)
 {
     using (FileStream stream = new FileStream(outFile, FileMode.Create))
     {
         Document pdfDoc = new Document(PageSize.A4);
         PdfCopy pdf = new PdfCopy(pdfDoc, stream);
         pdfDoc.Open();
         foreach (string file in fileNames) pdf.AddDocument(new PdfReader(file));
         if (pdfDoc != null) pdfDoc.Close();
     }
 }
Esempio n. 22
-9
        static void CreateMergedPDF(string targetPDF, string sourceDir)
        {
            using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4);
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();
                var files = Directory.GetFiles(sourceDir);
                Console.WriteLine("Merging files count: " + files.Length);
                int i = 1;
                foreach (string file in files)
                {
                    Console.WriteLine(i + ". Adding: " + file);
                    pdf.AddDocument(new PdfReader(file));
                    i++;
                }

                if (pdfDoc != null)
                    pdfDoc.Close();

                Console.WriteLine("SpeedPASS PDF merge complete.");
            }
        }