Beispiel #1
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();
        }
Beispiel #2
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);
            }
        }
        /// <summary>
        /// Is to use the library ITextSharp.
        /// The method creates a new file <paramref name="OutputFile"/> using
        /// the filestream by copying the files entered here <paramref name="PDFfileNames"/>.
        /// "https://www.c-sharpcorner.com/article/merge-multiple-pdf-files-into-single-pdf-using-itextsharp-in-c-sharp/"
        /// </summary>
        /// <param name="PDFfileNames"></param>
        /// <param name="OutputFile"></param>
        public static void CreatePdf(string[] PDFfileNames, string OutputFile)
        {
            // Create document object
            Document PDFdoc = new Document();

            // Create a object of FileStream which will be disposed at the end
            using FileStream MyFileStream = new FileStream(OutputFile, FileMode.Create);
            // Create a PDFwriter that is listens to the Pdf document
            PdfCopy PDFwriter = new PdfCopy(PDFdoc, MyFileStream);

            if (PDFwriter == null)
            {
                return;
            }
            // Open the PDFdocument
            PDFdoc.Open();
            foreach (string fileName in PDFfileNames)
            {
                // Create a PDFreader for a certain PDFdocument
                PdfReader PDFreader = new PdfReader(fileName);
                PDFreader.ConsolidateNamedDestinations();
                // Add content for page
                for (int i = 1; i <= PDFreader.NumberOfPages; i++)
                {
                    PDFwriter.AddPage(PDFwriter.GetImportedPage(PDFreader, i));
                }

                // Close PDFreader
                PDFreader.Close();
            }
            // Close the PDFdocument and PDFwriter
            PDFwriter.Close();
            PDFdoc.Close();
        }
Beispiel #4
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);
            }
        }
Beispiel #5
0
        private void merge_files(string[] files, string output_file)
        {
            Document document = new Document();
            PdfCopy  writer   = new PdfCopy(document, new FileStream(output_file, FileMode.Create));

            if (writer == null)
            {
                return;
            }

            document.Open();

            foreach (string fileName in files)
            {
                PdfReader reader = new PdfReader(fileName);
                reader.ConsolidateNamedDestinations();

                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                reader.Close();
            }

            writer.Close();
            document.Close();
        }
 public static MemoryStream MergePdfForms(List <byte[]> files)
 {
     if (files.Count > 1)
     {
         PdfReader    pdfFile;
         Document     doc;
         PdfWriter    pCopy;
         MemoryStream msOutput = new MemoryStream();
         pdfFile = new PdfReader(files[0]);
         doc     = new Document();
         pCopy   = new PdfCopy(doc, msOutput);
         doc.Open();
         for (int k = 0; k < files.Count; k++)
         {
             pdfFile = new PdfReader(files[k]);
             for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
             {
                 ((PdfCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
             }
             pCopy.FreeReader(pdfFile);
         }
         pdfFile.Close();
         pCopy.Close();
         doc.Close();
         return(msOutput);
     }
     else if (files.Count == 1)
     {
         return(new MemoryStream(files[0]));
     }
     return(null);
 }
Beispiel #7
0
        public void SplitPDF(string source_file, string result)
        {
            string tempPath = result + @"\tmp\";

            //Create Folder temporary
            // If directory does not exist, create it.
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            PdfCopy copy;

            PdfReader reader = new PdfReader(source_file);

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                Document document = new Document();
                copy = new PdfCopy(document, new FileStream(tempPath + i + ".pdf", FileMode.Create));
                copy.SetFullCompression();

                document.Open();

                copy.AddPage(copy.GetImportedPage(reader, i));

                document.Close();


                copy.Close();
            }
            //X

            reader.Close();
        }
Beispiel #8
0
        private void mergePdfs(string rutaDocumentoFinal, String[] archivos)
        {
            string[] source_files = archivos;
            string   result       = rutaDocumentoFinal;

            //create Document object
            using (Document document = new Document())
            {
                //create PdfCopy object
                using (PdfCopy copy = new PdfCopy(document, new FileStream(result, FileMode.Create)))
                {
                    //open the document
                    document.Open();
                    //PdfReader variable
                    //PdfReader reader;
                    for (int i = 0; i < source_files.Length; i++)
                    {
                        //create PdfReader object
                        using (PdfReader reader = new PdfReader(source_files[i]))
                        {
                            //merge combine pages
                            for (int page = 1; page <= reader.NumberOfPages; page++)
                            {
                                copy.AddPage(copy.GetImportedPage(reader, page));
                            }
                            reader.Close();
                        }
                    }

                    //close the document object
                    document.Close();
                    copy.Close();
                }
            }
        }
Beispiel #9
0
        public static bool CombineMultiplePDFs(string[] fileNames, string TargetFile)
        {
            try
            {
                string outFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SamplePDFFolder");
                if (!Directory.Exists(outFile))
                {
                    Directory.CreateDirectory(outFile);
                }
                outFile = Path.Combine(outFile, "MergedPdf.pdf");
                // step 1: creation of a document-object
                Document document = new Document();

                // step 2: we create a writer that listens to the document
                PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                if (writer == null)
                {
                    return(false);
                }

                // step 3: we open the document
                document.Open();

                foreach (string fileName in fileNames)
                {
                    // we create a reader for a certain document
                    PdfReader reader = new PdfReader(fileName);
                    reader.ConsolidateNamedDestinations();

                    // step 4: we add content
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }

                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                    {
                        writer.CopyAcroForm(reader);
                    }

                    reader.Close();
                }

                // step 5: we close the document and writer
                writer.Close();
                document.Close();

                File.Copy(outFile, TargetFile, true);
                File.Delete(outFile);
                return(true);
            }
            catch (Exception ex)
            {
                Log.This(ex);
                return(false);
            }
        }
Beispiel #10
0
        public void MergeArquivo(string pathRaizLote, string pathArquivo, string pathArquivoParaMerge, string cpfCnpj, LoteDTO lote)
        {
            var pathArquivoTemp = String.Format(@"{0}\{1}_TEMP{2}", pathRaizLote, cpfCnpj, ".pdf");

            //Arquivo formatado -> Ex..: 00081876000100.pdf
            //Arquivo para merger -> Ex..: 00081876000100_TASK1_1.pdf

            using (var readerArquivoFormatado = new PdfReader(pathArquivo))
                using (var readerArquivoParaMerge = new PdfReader(pathArquivoParaMerge))
                {
                    int totalArqFormatado = readerArquivoFormatado.NumberOfPages;
                    int totalArqMerge     = readerArquivoParaMerge.NumberOfPages;

                    var document = new Document(readerArquivoFormatado.GetPageSizeWithRotation(1));
                    var provider = new PdfCopy(document, new FileStream(pathArquivoTemp, FileMode.Create));

                    document.Open();

                    var    conteudoPaginas = new List <string>();
                    string textoPag;

                    //Adiciona paginas ao arquivo temporario.
                    for (int pagina = 1; pagina <= totalArqFormatado; pagina++)
                    {
                        textoPag = PdfTextExtractor.GetTextFromPage(readerArquivoFormatado, pagina, new SimpleTextExtractionStrategy());

                        var imported = provider.GetImportedPage(readerArquivoFormatado, pagina);

                        provider.AddPage(imported);

                        conteudoPaginas.Add(textoPag);
                    }

                    //Adiciona paginas ao arquivo temporario se não houver duplicacao.
                    for (int pagina = 1; pagina <= totalArqMerge; pagina++)
                    {
                        textoPag = PdfTextExtractor.GetTextFromPage(readerArquivoParaMerge, pagina, new SimpleTextExtractionStrategy());

                        if (!string.IsNullOrWhiteSpace(textoPag) && !conteudoPaginas.Contains(textoPag))
                        {
                            var imported = provider.GetImportedPage(readerArquivoParaMerge, pagina);

                            provider.AddPage(imported);
                        }
                    }

                    document.Close();

                    provider.Close();
                }

            File.Delete(pathArquivo);

            File.Delete(pathArquivoParaMerge);

            File.Move(pathArquivoTemp, pathArquivo);

            //throw new InvalidPdfException("Teste");
        }
Beispiel #11
0
        public void AddSheet(string pdfFile, string addSheetFile, int numberInSheetFile, int numberInPdfFile, string destFile)
        {
            var sheet  = new PdfReader(addSheetFile);
            var pdf    = new PdfReader(pdfFile);
            var doc    = new Document();
            var copier = new PdfCopy(doc, new FileStream(destFile, FileMode.Create));

            doc.Open();
            var pdfLabels = PdfPageLabels.GetPageLabels(pdf);

            if (pdfLabels?.Length != pdf.NumberOfPages)
            {
                pdfLabels = null;
            }
            var sheetLabel = PdfPageLabels.GetPageLabels(sheet);

            if (sheetLabel?.Length != sheet.NumberOfPages)
            {
                sheetLabel = null;
            }
            var labels = new PdfPageLabels();

            for (var i = 1; i < numberInPdfFile; i++)
            {
                var page = copier.GetImportedPage(pdf, i);
                copier.AddPage(page);
                if (pdfLabels != null)
                {
                    var label = pdfLabels[i - 1];
                    labels.AddPageLabel(i, PdfPageLabels.EMPTY, label);
                }
            }

            copier.AddPage(copier.GetImportedPage(sheet, numberInSheetFile));
            if (sheetLabel != null)
            {
                labels.AddPageLabel(numberInPdfFile, PdfPageLabels.EMPTY, sheetLabel[numberInSheetFile - 1]);
            }
            else
            {
                labels.AddPageLabel(numberInPdfFile, PdfPageLabels.EMPTY, "бланк");
            }
            for (var i = numberInPdfFile; i < pdf.NumberOfPages + 1; i++)
            {
                copier.AddPage(copier.GetImportedPage(pdf, i));
                if (pdfLabels != null)
                {
                    var label = pdfLabels[i - 1];
                    labels.AddPageLabel(i + 1, PdfPageLabels.EMPTY, label);
                }
            }

            copier.PageLabels = labels;
            doc.Close();
            copier.Close();
            pdf.Close();
            sheet.Close();
        }
        private void RenderPDF(ArrayList pages)
        {
            String coverName  = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.PP1_SUMMARY.pdf";
            String detailName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.PP1_DETAIL.pdf";

            if (File.Exists(pdfName))
            {
                File.Delete(pdfName);
            }

            Assembly   assembly     = Assembly.GetExecutingAssembly();
            FileStream outputStream = new FileStream(pdfName, FileMode.Create);

            Document pdfDoc = new Document(PageSize.A4);
            PdfCopy  pdf    = new PdfCopy(pdfDoc, outputStream);

            pdfDoc.Open();

            Stream       coverPageStream = assembly.GetManifestResourceStream(coverName);
            MemoryStream m             = new MemoryStream();
            PdfStamper   pdfStamper    = new PdfStamper(new PdfReader(coverPageStream), m);
            AcroFields   pdfFormFields = pdfStamper.AcroFields;

            populateCoverFormValue(pdfFormFields, 1);
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            pdf.AddDocument(new PdfReader(new MemoryStream(m.ToArray())));

            int max = pages.Count;
            int i   = 0;

            foreach (CTaxFormPageRv1 page in pages)
            {
                i++;

                Stream detailPageStream = assembly.GetManifestResourceStream(detailName);

                MemoryStream n = new MemoryStream();
                PdfStamper   pdfDetailStamper    = new PdfStamper(new PdfReader(detailPageStream), n);
                AcroFields   pdfDetailFormFields = pdfDetailStamper.AcroFields;

                populateDetailFormValue(pdfDetailFormFields, 2, i, pages.Count, page);

                pdfDetailStamper.FormFlattening = true;
                pdfDetailStamper.Close();

                PdfReader     reader = new PdfReader(new MemoryStream(n.ToArray()));
                PdfDictionary pd     = reader.GetPageN(1);
                pd.Put(PdfName.ROTATE, new PdfNumber(90));

                pdf.AddDocument(reader);

                UpdateProgress(i, max);
            }

            pdfDoc.Close();
            pdf.Close();
        }
Beispiel #13
0
        public static void FlatPDFonlyFistPage(List <string> files)
        {
            LogHelper.Log("Flatt all PDF comments", LogType.Successful);

            foreach (var file in files)
            {
                string OutFile = $"{Path.GetDirectoryName(file)}{Path.DirectorySeparatorChar}{Path.GetFileNameWithoutExtension(file)}_flat.pdf";

                LogHelper.Log($"Flattening file: { Path.GetFileNameWithoutExtension(file)}");

                using (FileStream stream = new FileStream(OutFile, FileMode.Create))
                {
                    PdfReader  reader  = null;
                    PdfStamper stamper = null;
                    try
                    {
                        var memStream1 = new MemoryStream();

                        reader = new PdfReader(file);
                        reader.SelectPages("1");

                        stamper = new PdfStamper(reader, memStream1)
                        {
                            FormFlattening       = true,
                            AnnotationFlattening = true,
                            FreeTextFlattening   = true,
                        };
                        stamper.Close();
                        PdfReader readerfirstPage = new PdfReader(memStream1.ToArray());

                        Document doc = new Document();
                        PdfCopy  pdf = new PdfCopy(doc, stream);
                        doc.Open();
                        pdf.AddDocument(readerfirstPage);

                        PdfReader readerOtherPages = new PdfReader(file);
                        if (readerOtherPages.NumberOfPages > 2)
                        {
                            readerOtherPages.SelectPages($"2-{readerOtherPages.NumberOfPages}");
                            pdf.AddDocument(readerOtherPages);
                        }
                        doc.Close();
                        pdf.Close();
                    }
                    catch (Exception e)
                    {
                        LogHelper.Log(e.ToString(), LogType.Error);

                        reader?.Close();
                    }
                    finally
                    {
                        reader?.Close();
                    }
                }
            }
        }
 /// <summary>
 /// Release our resources
 /// </summary>
 public void Dispose()
 {
     if (_pdfWriter != null)
     {
         _pdfWriter.Close();
         _pdfWriter.Dispose();
         _binaryWriter.Dispose();
     }
 }
        protected void btnMerge_Click(object sender, EventArgs e)
        {
            Stream         myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Title            = "Select PDFFile";
            saveFileDialog1.Filter           = "PDF(*.pdf)|*.pdf";
            saveFileDialog1.FilterIndex      = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    // Code to write the stream goes here.
                    myStream.Close();
                }
            }
            string pdfFile1 = Path.GetFullPath(textBoxPdfFile1Path.Text);

            string[] filenames      = { pdfFile1 };
            string   outputFileName = System.IO.Path.GetRandomFileName() + ".pdf";;
            string   outputPath     = saveFileDialog1.FileName;

            FileInfo fileInfo = new FileInfo(outputPath);

            Console.WriteLine(fileInfo.DirectoryName);


            Document doc    = new Document();
            PdfCopy  writer = new PdfCopy(doc, new FileStream(outputPath, FileMode.Create));

            if (writer == null)
            {
                return;
            }
            doc.Open();
            foreach (var filename in listBox1.Items)
            {
                PdfReader reader = new PdfReader(filename.ToString());
                reader.ConsolidateNamedDestinations();
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                reader.Close();
            }

            writer.Close();
            doc.Close();
            System.Diagnostics.Process.Start(outputPath);
        }
 public void Dispose()
 {
     if (document != null)
     {
         document.Close();
     }
     if (copy != null)
     {
         copy.CloseStream = false;
         copy.Close();
     }
 }
        //crea un PDF por separado para cada  uno de los documentos que huza el modulo de dactiloscopia
        public void crearPdfDocsDacti(int negid)
        {
            try
            {
                string          docPDFOrigen  = "";
                string          docPDFDestino = "";
                PdfImportedPage importedPage  = null;
                string          path          = consultaRutaNegocios();

                docPDFOrigen = path + negid + "\\" + negid + ".pdf";

                docPDFDestino = path + negid + "\\Pagina-";

                List <sp_ValDac2_DocumentosPaginas_Result> docuPaginas = db.sp_ValDac2_DocumentosPaginas(negid).ToList();

                foreach (sp_ValDac2_DocumentosPaginas_Result docPag in docuPaginas)
                {
                    if (docPag.Mascara == 20)
                    {
                        Session["Pagina20"] = docPag.Mascara;
                    }
                    else if (docPag.Mascara == 260)
                    {
                        Session["Pagina260"] = docPag.Mascara;
                    }
                    else
                    {
                        Session["Pagina280"] = docPag.Mascara;
                    }
                    if (!System.IO.File.Exists(docPDFDestino + docPag.Mascara + ".pdf"))
                    {
                        using (FileStream stream1 = new FileStream(docPDFDestino + docPag.Mascara + ".pdf", FileMode.Create))
                        {
                            Document pdfDoc    = new Document(PageSize.A4);
                            PdfCopy  pdfCreado = new PdfCopy(pdfDoc, stream1);
                            pdfDoc.Open();
                            importedPage = pdfCreado.GetImportedPage(new PdfReader((string)docPDFOrigen), (int)docPag.NumPagina);

                            pdfCreado.AddPage(importedPage);

                            pdfCreado.Close();
                            pdfDoc.Close();
                            stream1.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogRepository.registro("Error en CrearArchivos metodo crearPdfPorTypoDoc:  " + e.Message + "----stack trace----" + e.StackTrace);
                throw;
            }
        }
Beispiel #18
0
        public FileStreamResult PrintFormats(int idFormat, string RecordId)
        {
            if (!_tokenManager.GenerateToken())
            {
                return(null);
            }

            _IGeneratePDFApiConsumer.SetAuthHeader(_tokenManager.Token);
            _ISpartan_FormatRelatedApiConsumer.SetAuthHeader(_tokenManager.Token);

            MemoryStream ms = new MemoryStream();

            //Buscar los Formatos Relacionados
            var relacionados = _ISpartan_FormatRelatedApiConsumer.ListaSelAll(0, 5000, "Spartan_Format_Related.FormatId = " + idFormat, "").Resource.Spartan_Format_Relateds.OrderBy(r => r.Order).ToList();

            if (relacionados.Count > 0)
            {
                var outputDocument = new iTextSharp.text.Document();
                var writer         = new PdfCopy(outputDocument, ms);
                outputDocument.Open();
                foreach (var spartan_Format_Related in relacionados)
                {
                    var bytePdf = _IGeneratePDFApiConsumer.GeneratePDF(Convert.ToInt32(spartan_Format_Related.FormatId_Related), RecordId).Resource;
                    var reader  = new PdfReader(bytePdf);
                    for (var j = 1; j <= reader.NumberOfPages; j++)
                    {
                        writer.AddPage(writer.GetImportedPage(reader, j));
                    }
                    writer.FreeReader(reader);
                    reader.Close();
                }
                writer.Close();
                outputDocument.Close();
                var allPagesContent = ms.GetBuffer();
                ms.Flush();
            }
            else
            {
                var bytePdf = _IGeneratePDFApiConsumer.GeneratePDF(idFormat, RecordId);
                ms.Write(bytePdf.Resource, 0, bytePdf.Resource.Length);
            }

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Formatos.pdf");
            Response.Buffer = true;
            Response.Clear();
            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.End();

            return(new FileStreamResult(Response.OutputStream, "application/pdf"));
        }
Beispiel #19
0
        public static void CombineMultiplePdFs(string targetDirectory, string outFileLocation)
        {
            var filesPresent = CheckIfDirectoryIsEmpty(targetDirectory);

            //check if any files in the PDF merge source folder
            if (filesPresent)
            {
                // step 1: creation of a document-object
                Document document = new Document();

                //Get files in specific directory
                string[] fileEntries = Directory.GetFiles(targetDirectory);

                var mergedFileName = "\\Merged -" + Path.GetFileName(fileEntries[0]);
                //Create name for the outfile
                var outFile = outFileLocation + mergedFileName;
                //create newFileStream object which will be disposed at the end
                using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
                {
                    // step 2: we create a writer that listens to the document
                    PdfCopy writer = new PdfCopy(document, newFileStream);
                    // step 3: we open the document
                    document.Open();

                    foreach (string fileName in fileEntries)
                    {
                        ProcessFile(fileName);
                        // we create a reader for a certain document
                        PdfReader reader = new PdfReader(fileName);
                        reader.ConsolidateNamedDestinations();

                        // step 4: we add content
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            PdfImportedPage page = writer.GetImportedPage(reader, i);
                            writer.AddPage(page);
                        }

                        reader.Close();
                    }

                    // step 5: we close the document and writer
                    writer.Close();
                    document.Close();
                }
            }
            else
            {
                Printer.Print($"No files found in {targetDirectory}");
            }
        }
Beispiel #20
0
        public static byte[] CombineMultiplePDFs(List <byte[]> pdfS)
        {
            // step 1: creation of a document-object
            Document document = new Document();

            //create newFileStream object which will be disposed at the end
            using var ms = new MemoryStream();
            // step 2: we create a writer that listens to the document
            PdfCopy writer = new PdfCopy(document, ms);

            if (writer == null)
            {
                return(null);
            }

            // step 3: we open the document
            document.Open();

            foreach (var pdf in pdfS)
            {
                if (pdf != null && pdf.Length > 0)
                {
                    // we create a reader for a certain document
                    PdfReader reader = new PdfReader(pdf);
                    reader.ConsolidateNamedDestinations();

                    // step 4: we add content
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }

                    PrAcroForm form = reader.AcroForm;
                    if (form != null)
                    {
                        writer.CopyAcroForm(reader);
                    }

                    reader.Close();
                }
            }

            // step 5: we close the document and writer
            writer.Close();
            document.Close();
            return(ms.ToArray());
            //disposes the newFileStream object
        }
Beispiel #21
0
        private void Form1_Load(object sender, EventArgs e)
        {
            String SecondPage = AppDomain.CurrentDomain.BaseDirectory + "TranscriptRequest.pdf";
            String FirstPage  = AppDomain.CurrentDomain.BaseDirectory + "FirstPage.pdf";

            String Merged = AppDomain.CurrentDomain.BaseDirectory + "TranscriptMerged.pdf";


            Document document = new Document();

            using (FileStream newFileStream = new FileStream(Merged, FileMode.Create))
            {
                PdfCopy writer = new PdfCopy(document, newFileStream);
                if (writer == null)
                {
                    return;
                }


                document.Open();
                PdfReader reader = new PdfReader(FirstPage);

                reader.ConsolidateNamedDestinations();


                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                reader.Close();


                PdfReader readers = new PdfReader(SecondPage);
                PdfReader.unethicalreading = true;
                readers.ConsolidateNamedDestinations();

                // step 4: we add content
                for (int i = 1; i <= readers.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(readers, i);
                    writer.AddPage(page);
                }
                readers.Close();

                writer.Close();
                document.Close();
            }
        }
Beispiel #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileOne"></param>
        /// <param name="fileTwo"></param>
        /// <param name="newFile"></param>
        public static void ConcatPdf(string fileOne, string fileTwo, string newFile)
        {
            //si le premier fichier en entrée est aussi le fichier de sortie on concatène ce dernier
            var append = fileOne.Equals(newFile);

            if (append)
            {
                //on construit le fichier sortie dans un autre emplacement
                string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\");
                newFile = Path.Combine(cardFolder, Path.GetFileName(newFile));
            }
            //fusion des pdf
            using (FileStream stream = new FileStream(newFile, FileMode.Create))
            {
                Document  pdfDoc = new Document();
                PdfReader reader;
                PdfCopy   pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();

                if (File.Exists(fileOne))
                {
                    reader = new PdfReader(fileOne);
                    pdf.AddDocument(reader);
                    reader.Close();
                }

                if (File.Exists(fileTwo))
                {
                    reader = new PdfReader(fileTwo);
                    pdf.AddDocument(reader);
                    reader.Close();
                }

                if (pdfDoc != null)
                {
                    pdf.Close();
                    pdfDoc.Close();
                    if (append)
                    {
                        if (File.Exists(fileOne))
                        {
                            File.Delete(fileOne);
                        }
                        //on déplace le fichier sortie obtenu à l'emplacement d'origine
                        File.Move(newFile, fileOne);
                    }
                }
            }
        }
 public void Dispose()
 {
     if (copy != null)
     {
         copy.Close();
     }
     if (document != null)
     {
         document.Close();
     }
     if (fs != null)
     {
         fs.Close();
     }
 }
Beispiel #24
0
        /// <summary>
        /// リスト内のPDFを結合しPDFを作成する
        /// http://zero0nine.com/archives/2866
        /// </summary>
        /// <param name="outPdfPath">
        /// 結合後のPDFファイルパス(フルパス)
        /// </param>
        /// <param name="pdfList">
        /// 結合対象のPDFファイルパスを格納したリスト
        /// </param>
        /// <returns>
        /// true:正常
        /// false:異常
        /// </returns>
        private bool JoinPdf(string outPdfPath, List <string> pdfList)
        {
            bool ret = true;

            Document joinedDoc = null;
            PdfCopy  pdfCopy   = null;

            try
            {
                joinedDoc = new Document();
                pdfCopy   = new PdfCopy(joinedDoc, new FileStream(outPdfPath, FileMode.Create));

                joinedDoc.Open();

                /// 出力するPDFのプロパティを設定
                //objITextDoc.AddKeywords("キーワードです。");
                //objITextDoc.AddAuthor("zero0nine.com");
                //objITextDoc.AddTitle("結合したPDFファイルです。");
                //objITextDoc.AddCreator("PDFファイル結合くん");
                //objITextDoc.AddSubject("結合したPDFファイル");

                /// ソートが必要ない場合は、コメント
                //pdfList.Sort();

                /// 結合対象ファイル分ループ
                pdfList.ForEach(list =>
                {
                    Debug.WriteLine(list);
                    /// 結合元のPDFファイル読込
                    PdfReader pdfReader = new PdfReader(list);
                    /// 結合元のPDFファイルを追加(全ページ)
                    pdfCopy.AddDocument(pdfReader);
                    pdfReader.Close();
                });
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp.Message);
                ret = false;
            }
            finally
            {
                joinedDoc.Close();
                pdfCopy.Close();
            }

            return(ret);
        }
Beispiel #25
0
        private void SetPdfPathList()
        {
            PdfReader reader   = new PdfReader(txtInputPdfFilePath.Text);
            Document  document = new Document();
            PdfCopy   copy     = null;

            PdfFilePathList = new List <string>();

            OriginalDirectoryPath = Path.GetDirectoryName(txtInputPdfFilePath.Text);

            TempDirectoryPath = Path.Combine(OriginalDirectoryPath, "PDF_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            _directoryPathList.Add(TempDirectoryPath);

            OriginalFileNmae = Path.GetFileNameWithoutExtension(txtInputPdfFilePath.Text);

            Directory.CreateDirectory(TempDirectoryPath);

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                PdfFilePathList.Add(Path.Combine(TempDirectoryPath, OriginalFileNmae) + "_" + i.ToString() + ".pdf");
                using (var fs = new FileStream(PdfFilePathList.Last(), FileMode.Create, FileAccess.Write))
                {
                    try
                    {
                        document = new Document(reader.GetPageSizeWithRotation(1));
                        copy     = new PdfCopy(document, fs);
                        document.Open();
                        copy.AddPage(copy.GetImportedPage(reader, i));
                    }
                    finally
                    {
                        document.Close();
                        copy.Close();
                    }
                }
            }

            reader.Close();

            SetNumberOfPages();
            txtPageMain.Text = "1";
            DisplayPdf();

            document.Dispose();
            copy.Dispose();
            reader.Dispose();
        }
Beispiel #26
0
        public void MergeFiles()
        {
            if (FileList == null || FileList.Count == 0)
            {
                MessageBox.Show("No PDF files found on folder.");
            }
            else
            {
                OutputFileName = System.IO.Path.Combine(Path, $"{OutputFileName}.pdf");

                Document document = new Document();

                using (FileStream newFileStream = new FileStream(OutputFileName, FileMode.Create))
                {
                    PdfCopy writer = new PdfCopy(document, newFileStream);
                    if (writer == null)
                    {
                        return;
                    }

                    document.Open();

                    foreach (var file in FileList)
                    {
                        PdfReader reader = new PdfReader(file.FullPath);
                        reader.ConsolidateNamedDestinations();

                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            PdfImportedPage page = writer.GetImportedPage(reader, i);
                            writer.AddPage(page);
                        }

                        PRAcroForm form = reader.AcroForm;
                        if (form != null)
                        {
                            writer.CopyAcroForm(reader);
                        }

                        reader.Close();
                    }

                    writer.Close();
                    document.Close();
                }
            }
        }
Beispiel #27
0
        public List <PayStub> GenerateIndividualStubs(string filename)
        {
            List <PayStub> stubs = new List <PayStub>();

            using (var reader = new PdfReader(filename))
            {
                for (var page = 1; page <= reader.NumberOfPages; page++)
                {
                    //extract page text
                    var strategy    = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    var currentText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, page, strategy);


                    var paystub = FindPayStubMatch(currentText);
                    if (paystub == null)
                    {
                        continue;
                    }

                    //write this individual page into a temp file
                    var outFileName = System.IO.Path.GetTempPath() + Guid.NewGuid() + ".pdf";

                    var pdfDoc = new Document(reader.GetPageSizeWithRotation(page));
                    var stream = new MemoryStream();
                    var pdf    = new PdfCopy(pdfDoc, stream);
                    pdf.CloseStream = false;
                    pdfDoc.Open();
                    pdf.AddPage(pdf.GetImportedPage(reader, page));
                    pdf.Close();
                    pdfDoc.Close();
                    stream.Position = 0;

                    var stamper = new PdfStamper(new PdfReader(stream), new FileStream(outFileName, FileMode.Create));
                    if ((paystub.Password + "").Length > 0)
                    {
                        stamper.SetEncryption(Encoding.ASCII.GetBytes(paystub.Password), Encoding.ASCII.GetBytes(paystub.Password), PdfWriter.ALLOW_PRINTING,
                                              PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
                    }
                    stamper.Close();
                    stream.Close();

                    paystub.Filename = outFileName;
                    stubs.Add(paystub);
                }
            }
            return(stubs);
        }
Beispiel #28
0
        private void MergeArquivo(PdfReader reader, string pathRaiz, string pathArquivo, string cpfCnpj, int pagina)
        {
            var pathArquivoTemp = String.Format(@"{0}\{1}_TEMP{2}", pathRaiz, cpfCnpj, ".pdf");

            using (var readerArquivoExistente = new PdfReader(pathArquivo))
            {
                var document = new Document(reader.GetPageSizeWithRotation(pagina));
                var provider = new PdfCopy(document, new FileStream(pathArquivoTemp, FileMode.Create));

                document.Open();

                var    conteudoPaginas = new List <string>();
                string textoPag;

                //Adiciona páginas do arquivo existente
                for (int i = 1; i <= readerArquivoExistente.NumberOfPages; i++)
                {
                    textoPag = PdfTextExtractor.GetTextFromPage(readerArquivoExistente, i, new SimpleTextExtractionStrategy());
                    var imported = provider.GetImportedPage(readerArquivoExistente, i);

                    if (!string.IsNullOrWhiteSpace(textoPag))
                    {
                        conteudoPaginas.Add(textoPag);

                        provider.AddPage(imported);
                    }
                }

                textoPag = PdfTextExtractor.GetTextFromPage(reader, pagina, new SimpleTextExtractionStrategy());

                if (!conteudoPaginas.Contains(textoPag))
                {
                    var importedPage = provider.GetImportedPage(reader, pagina);

                    provider.AddPage(importedPage);
                }

                document.Close();

                provider.Close();
            }

            File.Delete(pathArquivo);

            File.Move(pathArquivoTemp, pathArquivo);
        }
        public static void splitSpellPage(this PDF pdf, int page)
        {
            PdfReader reader          = new PdfReader(pdf.File);
            PdfReader sreader         = new PdfReader(pdf.SpellFile);
            Document  sourceDocument  = new Document(sreader.GetPageSizeWithRotation(1));
            PdfCopy   pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream("Alternate-Sheet.pdf", System.IO.FileMode.Create));

            sourceDocument.Open();
            PdfImportedPage importedPage = pdfCopyProvider.GetImportedPage(sreader, 1);

            pdfCopyProvider.AddPage(importedPage);
            pdfCopyProvider.AddPage(pdfCopyProvider.GetImportedPage(reader, 2));
            sourceDocument.Close();
            reader.Close();
            sreader.Close();
            pdfCopyProvider.Close();
        }
Beispiel #30
0
        private void CombineMultiplePDFs()
        {
            // step 1: creation of a document-object
            Document document = new Document();

            // step 2: we create a writer that listens to the document
            PdfCopy writer = new PdfCopy(document, new FileStream(destinationFile, FileMode.Create));

            if (writer == null)
            {
                return;
            }

            // step 3: we open the document
            document.Open();

            foreach (string fileName in FilesName)
            {
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(fileName);
                reader.ConsolidateNamedDestinations();

                // step 4: we add content
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                //PRAcroForm form = reader.AcroForm;
                //if (form != null)
                //{
                //    writer.CopyAcroForm(reader);
                //}

                reader.Close();
            }

            // step 5: we close the document and writer
            writer.Close();
            document.Close();

            // Eliminar PDFs temp
            //foreach (string filePath in FilesName)
            //    File.Delete(filePath);
        }