Exemplo n.º 1
0
        public void SmartCopySignedDocuments()
        {
            string file = RESOURCES + "hello_signed1.pdf";

            Directory.CreateDirectory("PdfCopyTest/");
            Document     pdfDocument = new Document();
            PdfSmartCopy copier      = new PdfSmartCopy(pdfDocument, new FileStream("PdfCopyTest/SmartCopySignedDocuments.pdf", FileMode.Create));

            pdfDocument.Open();

            PdfReader reader1 = new PdfReader(file);

            copier.AddPage(copier.GetImportedPage(reader1, 1));
            copier.FreeReader(reader1);

            reader1 = new PdfReader(file);
            copier.AddPage(copier.GetImportedPage(reader1, 1));
            copier.FreeReader(reader1);

            pdfDocument.Close();

            PdfReader     reader = new PdfReader("PdfCopyTest/SmartCopySignedDocuments.pdf");
            PdfDictionary sig    = (PdfDictionary)reader.GetPdfObject(8);
            PdfDictionary sigRef = sig.GetAsArray(PdfName.REFERENCE).GetAsDict(0);

            Assert.True(PdfName.SIGREF.Equals(sigRef.GetAsName(PdfName.TYPE)));
            Assert.False(sigRef.Contains(PdfName.DATA));
        }
Exemplo n.º 2
0
        private void addFilePages(Stream fileStream)
        {
            PdfReader reader = null;

            try
            {
                _fileNumber++;
                _attachmentsCount += copyAttachments(fileStream);
                fileStream         = fileStream.ReopenForReading();
                reader             = new PdfReader(fileStream);
                reader.ConsolidateNamedDestinations();

                addBookmark(reader);

                int numberOfPages = reader.NumberOfPages;
                for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++)
                {
                    var size = reader.GetPageSizeWithRotation(pageNumber);
                    _document.SetPageSize(size);
                    _document.NewPage();
                    _overallPageNumber++;

                    var page = _writer.GetImportedPage(reader, pageNumber);
                    addContentToPage(reader, size, page);
                    _writer.AddPage(page);
                }
            }
            finally
            {
                if (reader != null)
                {
                    _writer.FreeReader(reader);
                }
            }
        }
Exemplo n.º 3
0
 public 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 PdfSmartCopy(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++)
             {
                 ((PdfSmartCopy)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);
 }
Exemplo n.º 4
0
        public MemoryStream MergePdfForms(List <byte[]> files)
        {
            if (files.Count > 1)
            {
                string[]     names;
                PdfStamper   stamper;
                MemoryStream msTemp      = null;
                PdfReader    pdfTemplate = null;
                PdfReader    pdfFile;
                Document     doc;
                PdfWriter    pCopy;
                var          msOutput = new MemoryStream();

                pdfFile = new PdfReader(files[0]);

                doc   = new Document();
                pCopy = new PdfSmartCopy(doc, msOutput)
                {
                    PdfVersion = PdfWriter.VERSION_1_7
                };

                doc.Open();

                for (var k = 0; k < files.Count; k++)
                {
                    for (var i = 1; i < pdfFile.NumberOfPages + 1; i++)
                    {
                        msTemp      = new MemoryStream();
                        pdfTemplate = new PdfReader(files[k]);

                        stamper = new PdfStamper(pdfTemplate, msTemp);

                        names = new string[stamper.AcroFields.Fields.Keys.Count];
                        stamper.AcroFields.Fields.Keys.CopyTo(names, 0);
                        foreach (var name in names)
                        {
                            stamper.AcroFields.RenameField(name, name + "_file" + k.ToString());
                        }

                        stamper.Close();
                        pdfFile = new PdfReader(msTemp.ToArray());
                        ((PdfSmartCopy)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);
        }
        /// <summary>
        /// <para>(ESP) Este metodo es recursivo, se encarga de asignar los bookmarks y asignarles su parent</para>
        /// <para>(ENG) this method is recursive, assign the parent for each file</para>
        /// </summary>
        /// <param name="doc">
        /// <para>(ESP) Este es el documento actual</para>
        /// <para>(ENG) this is the current document</para>
        /// </param>
        /// <param name="pdfCopy">
        /// <para>(ESP)es el documento que hará el smart copy</para>
        /// <para>(ENG) this is the pdfsmartcopy for the append another pdf</para>
        /// </param>
        /// <param name="marcadorNombreLibro">
        /// <para>(ESP) este es el parent</para>
        /// <para>(ENG) this is the parent</para>
        /// </param>
        /// <param name="enlace">
        /// <para>(ESP) Esta es la estructura del documento, donde contiene nombre y url del documento</para>
        /// <para>(ENG) This is the structure's document, this contains the name and url's file </para>
        /// </param>
        /// <param name="rutaPDFs">
        /// <para>(ESP)Es donde se generan los documentos</para>
        /// <para>(ENG)Its the path for create the files</para>
        /// </param>
        public static void GenerarHijosEstructura(Document doc, PdfSmartCopy pdfCopy, PdfOutline marcadorNombreLibro, Modelo.POCOs.EstructuraPDF enlace, string rutaPDFs)
        {
            try
            {
                PdfContentByte pb = pdfCopy.DirectContent;

                //Crea el link para la sección
                Anchor section1 = new Anchor(enlace.Nombre)
                {
                    Name = enlace.Nombre
                };

                Paragraph psecton1 = new Paragraph();
                psecton1.Add(section1);

                //mostrar la sección 1 en una ubicación específica del documento
                ColumnText.ShowTextAligned(pb, Element.ALIGN_LEFT, psecton1, 36, PageSize.A4.Height - 100, 0);


                //(ESP) Se crea el marcador para este documento, se hace referencia al documento padre (parent)
                //(ENG) create the bookmark for this document, and create the reference with the parent
                var mbot = new PdfOutline(marcadorNombreLibro, PdfAction.GotoLocalPage(enlace.Nombre, false), enlace.Nombre);

                //(ESP) Se lee el documento
                //(ENG) read the file
                PdfReader reader = new PdfReader(enlace.UrlDocumento);
                //(ESP) Se adjuntan las paginas al documento
                //(ENG) Copy each page in the current pdfcopy
                for (int I = 1; I <= reader.NumberOfPages; I++)
                {
                    doc.SetPageSize(reader.GetPageSizeWithRotation(1));
                    PdfImportedPage page = pdfCopy.GetImportedPage(reader, I);
                    pdfCopy.AddPage(page);
                }
                //Clean up
                pdfCopy.FreeReader(reader);
                reader.Close();

                if (enlace.Hijos.Any())
                {
                    foreach (var cadaHijo in enlace.Hijos)
                    {
                        //(ESP) aquí está la clave, esto es recurisvo
                        //(ENG) this is the magic, its recursive
                        GenerarHijosEstructura(doc, pdfCopy, mbot, cadaHijo, rutaPDFs);
                    }
                }
            }
            catch (Exception error)
            {
            }
        }
Exemplo n.º 6
0
        public static bool Execute(String[] sourcePaths, String targetPath)
        {
            try
            {
                Console.WriteLine("Begin merging {0} pdf documents . . . ", sourcePaths.Length);
                byte[] mergedPdf = null;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (Document document = new Document(PageSize.A4, 4, 3, 3, 3))
                    {
                        using (PdfCopy copy = new PdfSmartCopy(document, ms))
                        {
                            document.Open();

                            for (int i = 0; i < sourcePaths.Length; ++i)
                            {
                                Console.WriteLine("Extracting {0} . . . ", sourcePaths[i]);
                                PdfReader reader = new PdfReader(sourcePaths[i]);
                                // loop over the pages in that document
                                int n = reader.NumberOfPages;
                                for (int page = 0; page < n;)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader, ++page));
                                }
                                copy.FreeReader(reader);
                                reader.Close();
                            }
                        }
                    }
                    mergedPdf = ms.ToArray();
                    Console.WriteLine(String.Format("Merging {0} bytes of pdf documents", mergedPdf.Length));
                    using (Stream os = new FileStream(targetPath, FileMode.Create))
                    {
                        os.Write(mergedPdf, 0, mergedPdf.Length);
                        os.Flush();
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 7
0
        private static void CombineAndSavePdf(string savePath, List <string> lstPdfFiles)
        {
            using (Stream outputPdfStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                Document     document = new Document();
                PdfSmartCopy copy     = new PdfSmartCopy(document, outputPdfStream);
                document.Open();
                PdfReader  reader;
                int        totalPageCnt;
                PdfStamper stamper;
                string[]   fieldNames;
                foreach (string file in lstPdfFiles)
                {
                    reader       = new PdfReader(file);
                    totalPageCnt = reader.NumberOfPages;
                    for (int pageCnt = 0; pageCnt < totalPageCnt;)
                    {
                        //have to create a new reader for each page or PdfStamper will throw error
                        reader     = new PdfReader(file);
                        stamper    = new PdfStamper(reader, outputPdfStream);
                        fieldNames = new string[stamper.AcroFields.Fields.Keys.Count];
                        stamper.AcroFields.Fields.Keys.CopyTo(fieldNames, 0);
                        foreach (string name in fieldNames)
                        {
                            stamper.AcroFields.RenameField(name, name + "_file" + pageCnt.ToString());
                        }

                        copy.AddPage(copy.GetImportedPage(reader, ++pageCnt));
                    }

                    copy.FreeReader(reader);
                }

                document.Close();
            }
        }
Exemplo n.º 8
0
        public static byte[] zCombinePdfs(List <byte[]> files)
        {
            if (files.Count > 1)
            {
                MemoryStream msOutput = new MemoryStream();

                PdfReader reader = new PdfReader(files[0]);

                Document doc = new Document();

                PdfSmartCopy copy = new PdfSmartCopy(doc, msOutput);

                doc.Open();

                for (int k = 0; k < files.Count; k++)
                {
                    for (int i = 1; i < reader.NumberOfPages + 1; i++)
                    {
                        copy.AddPage(copy.GetImportedPage(reader, i));
                        copy.FreeReader(reader);
                    }
                }

                reader.Close();
                copy.Close();
                doc.Close();

                return(msOutput.ToArray());
            }
            else if (files.Count == 1)
            {
                return(files[0]);
            }

            return(null);
        }
        public static bool MergePdfs(string folderInput, string mergePdfName, ref List <ColumbusIndex> documentsToMerge)
        {
            using (FileStream stream = new FileStream(mergePdfName, FileMode.Create))
            {
                var                  totalDocs = 0;
                PdfReader            reader    = null;
                Document             document  = new Document();
                PdfSmartCopy         pdf       = new PdfSmartCopy(document, stream);
                List <ColumbusIndex> tempList  = new List <ColumbusIndex>();
                try
                {
                    document.Open();
                    foreach (var doc in documentsToMerge)
                    {
                        tempList.Add(doc);
                        if (totalDocs > 0)
                        {
                            if (documentsToMerge[totalDocs - 1].PdfTempData != null)
                            {
                                documentsToMerge[totalDocs - 1].PdfTempData = null; //Release from memory
                            }
                        }
                        totalDocs++;

                        try
                        {
                            if (doc.PdfTempData == null)
                            {
                                doc.PdfTempData = File.ReadAllBytes(Path.Combine(folderInput, doc.FileName));
                            }

                            reader    = new PdfReader(doc.PdfTempData);
                            doc.Pages = reader.NumberOfPages;

                            if (doc.Pages == 0)
                            {
                                throw new Exception("Do not allow documents with zero pages");
                            }

                            for (int i = 1; i <= doc.Pages; i++)
                            {
                                //import the page from source pdf
                                var copiedPage = pdf.GetImportedPage(reader, i);
                                // add the page to the new document
                                if (pdf != null)
                                {
                                    pdf.AddPage(copiedPage);
                                }
                            }

                            if (pdf != null && reader != null)
                            {
                                pdf.FreeReader(reader);
                                pdf.Flush();
                            }

                            if (reader != null)
                            {
                                reader.Close();
                            }

                            long fileSize           = new FileInfo(mergePdfName).Length;
                            long columbusPDFMaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["ColumbusPDFMaxSize"]);
                            if (fileSize > columbusPDFMaxSize) //If file size is bigger than 200mb, start a new file
                            {
                                GenerateControlFile(mergePdfName, tempList);
                                documentsToMerge = documentsToMerge.Except(tempList).ToList();
                                return(true);
                            }
                        }
                        catch (Exception ex1)
                        {
                            doc.FileMissing = true;
                            throw new ProcessingException("COMBINE PDF: [" + Path.Combine(folderInput, doc.FileName) + "] " + ex1.Message + " : " + ex1.StackTrace);
                        }
                    }

                    //Generate control file for last merged PDF
                    GenerateControlFile(mergePdfName, tempList);
                    documentsToMerge = documentsToMerge.Except(tempList).ToList();

                    return(true);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("Failed to merge files in {0} to {1}. ex: {2}", folderInput, mergePdfName, ex));
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    return(false);
                }
                finally
                {
                    if (document != null)
                    {
                        document.Close();
                    }
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Merges pdf files from a byte list
        /// </summary>
        /// <param name="files">list of files to merge</param>
        /// <returns>memory stream containing combined pdf</returns>
        public static string MergePdfForms(List <string> file_names, string output)
        {
            if (file_names.Count > 1)
            {
                List <byte[]> files = new List <byte[]>();
                foreach (string file_name in file_names)
                {
                    var file = File.ReadAllBytes(file_name);
                    files.Add(file);
                }

                string[]     names;
                PdfStamper   stamper;
                MemoryStream msTemp      = null;
                PdfReader    pdfTemplate = null;
                PdfReader    pdfFile;
                Document     doc;
                PdfWriter    pCopy;
                MemoryStream msOutput = new MemoryStream();

                pdfFile = new PdfReader(files[0]);

                doc              = new Document();
                pCopy            = new PdfSmartCopy(doc, msOutput);
                pCopy.PdfVersion = PdfWriter.VERSION_1_7;

                doc.Open();

                for (int k = 0; k < files.Count; k++)
                {
                    for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
                    {
                        msTemp      = new MemoryStream();
                        pdfTemplate = new PdfReader(files[k]);

                        stamper = new PdfStamper(pdfTemplate, msTemp);

                        names = new string[stamper.AcroFields.Fields.Keys.Count];
                        stamper.AcroFields.Fields.Keys.CopyTo(names, 0);
                        foreach (string name in names)
                        {
                            stamper.AcroFields.RenameField(name, name + "_file" + k.ToString());
                        }

                        stamper.Close();
                        pdfFile = new PdfReader(msTemp.ToArray());
                        ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
                        pCopy.FreeReader(pdfFile);
                    }
                }

                FileStream f = new FileStream(output, FileMode.Create);
                msOutput.WriteTo(f);
                msOutput.Flush();
                f.Flush();


                pdfFile.Close();
                pCopy.Close();
                doc.Close();
                msOutput.Close();
                f.Close();

                return(output);
            }
            else if (file_names.Count == 1)
            {
                File.Copy(file_names.First(), output);
                return(output);
            }

            return(null);
        }