Exemple #1
0
        //========================================
        //
        //
        //========================================
        private void ExtractAndSaveFile(string sourcePdfFilePath, string outpuPdfFileName, int startPage, int numberOfPages)
        {
            using (PdfReader reader = new PdfReader(sourcePdfFilePath))
            {
                Document     document = new Document();
                PdfSmartCopy partial  = new PdfSmartCopy(document, new FileStream(outpuPdfFileName, FileMode.Create));

                partial.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
                partial.CompressionLevel = PdfStream.BEST_COMPRESSION;
                partial.SetFullCompression();

                document.Open();

                for (int pagenumber = startPage; pagenumber < (startPage + numberOfPages); pagenumber++)
                {
                    if (reader.NumberOfPages >= pagenumber)
                    {
                        partial.AddPage(partial.GetImportedPage(reader, pagenumber));
                    }
                    else
                    {
                        break;
                    }
                }

                document.Close();
            }
        }
Exemple #2
0
 public static void ConcatPages(List <PdfActionResult> docs, string outputFilePath, Rectangle pageSize)
 {
     try
     {
         // Capture the correct size and orientation for the page:
         using (var resultDoc = new Document(pageSize))
             using (var fs = new FileStream(outputFilePath, FileMode.Create))
                 using (var pdfCopy = new PdfSmartCopy(resultDoc, fs))
                 {
                     resultDoc.Open();
                     foreach (var doc in docs)
                     {
                         using (PdfReader reader = new PdfReader(doc.ResultPdfPath))
                         {
                             PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, doc.Action.ModelPageIndex);
                             pdfCopy.AddPage(importedPage);
                         }
                     }
                 }
     }
     catch (Exception ex)
     {
         throw new Exception("Impossible to concatenate Pages", ex);
     }
 }
Exemple #3
0
        /// <summary>
        /// Creates a single PDF from multiple at a specified location
        /// </summary>
        private static void MergePdf()
        {
            String result = @"d:\PDF\Output\mergefile.pdf";

            Document document = new Document();
            //create PdfSmartCopy object
            PdfSmartCopy copy = new PdfSmartCopy(document, new FileStream(result, FileMode.Create));

            copy.SetFullCompression();
            //open the document
            document.Open();

            PdfReader reader = null;

            foreach (var file in new DirectoryInfo(@"D:\PDF\Output").GetFiles("*.pdf").OrderBy(x => x.Name))
            {
                if (file.Name == "mergefile.pdf")
                {
                    continue;
                }
                //create PdfReader object
                reader = new PdfReader(file.FullName);
                //merge combine pages
                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    copy.AddPage(copy.GetImportedPage(reader, page));
                }
            }
            //close the document object
            document.Close();
        }
Exemple #4
0
        /**
         * Test to make sure that the following issue is fixed: http://sourceforge.net/mailarchive/message.php?msg_id=30891213
         */
        virtual public void TestDecodeParmsArrayWithNullItems()
        {
            Document     document     = new Document();
            MemoryStream byteStream   = new MemoryStream();
            PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, byteStream);

            document.Open();

            PdfReader reader = TestResourceUtils.GetResourceAsPdfReader(RESOURCES, "imgWithDecodeParms.pdf");

            pdfSmartCopy.AddPage(pdfSmartCopy.GetImportedPage(reader, 1));

            document.Close();
            reader.Close();

            reader = new PdfReader(byteStream.ToArray());
            PdfDictionary page        = reader.GetPageN(1);
            PdfDictionary resources   = page.GetAsDict(PdfName.RESOURCES);
            PdfDictionary xObject     = resources.GetAsDict(PdfName.XOBJECT);
            PdfStream     img         = xObject.GetAsStream(new PdfName("Im0"));
            PdfArray      decodeParms = img.GetAsArray(PdfName.DECODEPARMS);

            Assert.AreEqual(2, decodeParms.Size);
            Assert.IsTrue(decodeParms[0] is PdfNull);

            reader.Close();
        }
        public static byte[] Merge(string[] documentPaths)
        {
            byte[] mergedDocument;

            using (MemoryStream memoryStream = new MemoryStream())
                using (Document document = new Document())
                {
                    PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream);
                    document.Open();

                    foreach (string docPath in documentPaths)
                    {
                        PdfReader reader = new PdfReader(docPath);
                        try
                        {
                            reader.ConsolidateNamedDestinations();
                            int numberOfPages = reader.NumberOfPages;
                            for (int page = 0; page < numberOfPages;)
                            {
                                PdfImportedPage pdfImportedPage = pdfSmartCopy.GetImportedPage(reader, ++page);
                                pdfSmartCopy.AddPage(pdfImportedPage);
                            }
                        }
                        finally
                        {
                            reader.Close();
                        }
                    }

                    document.Close();
                    mergedDocument = memoryStream.ToArray();
                }

            return(mergedDocument);
        }
        /// <summary>
        /// 合并生成的pdf文件流
        /// </summary>
        /// <param name="pdfStreams">多个pdf文件字节</param>
        /// <returns>返回合并之后的pdf文件流</returns>
        public static MemoryStream MergePdfs(List <byte[]> pdfStreams)
        {
            try
            {
                Document     document       = new Document();
                MemoryStream mergePdfStream = new MemoryStream();
                //这里用的是smartCopy,整篇文档只会导入一份字体。属于可接受范围内
                PdfSmartCopy copy = new PdfSmartCopy(document, mergePdfStream);

                document.Open();
                for (int i = 0; i < pdfStreams.Count; i++)
                {
                    byte[] stream = pdfStreams[i];

                    PdfReader reader = new PdfReader(stream);
                    //for循环新增文档页数,并copy pdf数据
                    document.NewPage();
                    PdfImportedPage imported = copy.GetImportedPage(reader, 1);
                    copy.AddPage(imported);

                    reader.Close();
                }
                copy.Close();
                document.Close();

                return(mergePdfStream);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return(null);
            }
        }
        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);
                }
            }
        }
        public bool Split(Stream os, long sizeInBytes)
        {
            if (!HasMorePages())
            {
                os.Close();
                return(false);
            }
            overSized = false;
            Document document = new Document();
            PdfCopy  copy     = new PdfSmartCopy(document, os);

            document.Open();
            bool hasPage = false;
            PdfResourceCounter counter = new PdfResourceCounter(reader.Trailer);
            long trailer = counter.GetLength(null);
            IDictionary <int, PdfObject> resources = counter.Resources;
            long length = 0;
            long page;

            while (HasMorePages())
            {
                counter   = new PdfResourceCounter(reader.GetPageN(currentPage));
                page      = counter.GetLength(resources);
                resources = counter.Resources;
                length   += page + trailer + XrefLength(resources.Count);
                if (LOGGER.IsLogging(Level.INFO))
                {
                    LOGGER.Info(String.Format("Page {0}: Comparing {1} with {2}", currentPage, length, sizeInBytes));
                    LOGGER.Info(String.Format("   page {0} trailer {1} xref {2}", page, trailer, XrefLength(resources.Count)));
                }
                if (!hasPage || length < sizeInBytes)
                {
                    hasPage = true;
                    copy.AddPage(copy.GetImportedPage(reader, currentPage));
                    length = copy.Os.Counter;
                    if (LOGGER.IsLogging(Level.INFO))
                    {
                        LOGGER.Info(String.Format("Size after adding page: {0}", length));
                    }
                    if (length > sizeInBytes)
                    {
                        overSized = true;
                    }
                    currentPage++;
                }
                else
                {
                    LOGGER.Info("Page doesn't fit");
                    break;
                }
            }
            document.Close();
            return(true);
        }
        /// <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)
            {
            }
        }
        public void fillPDF(string templatePath, IEnumerable <IPdfMergeData> mergeDataItems,
                            System.IO.MemoryStream outputstream)
        {
            var pagesAll = new List <byte[]>();

            byte[] pageBytes = null;

            foreach (var mergeItem in mergeDataItems)
            {
                var templateReader = new iTextSharp.text.pdf.PdfReader(templatePath);
                using (var tempStream = new System.IO.MemoryStream())
                {
                    PdfStamper stamper = new PdfStamper(templateReader, tempStream);
                    stamper.FormFlattening = true;
                    AcroFields fields = stamper.AcroFields;
                    stamper.Writer.CloseStream = false;

                    var fieldVals = mergeItem.MergeFieldValues;

                    foreach (string name in fieldVals.Keys)
                    {
                        fields.SetField(name, fieldVals[name]);
                    }

                    stamper.Close();

                    tempStream.Position = 0;

                    pageBytes = tempStream.ToArray();

                    pagesAll.Add(pageBytes);
                }
            }

            Document mainDocument = new Document(PageSize.A4);

            var pdfCopier = new PdfSmartCopy(mainDocument, outputstream);

            pdfCopier.CloseStream = false;

            mainDocument.Open();
            foreach (var pageByteArray in pagesAll)
            {
                mainDocument.NewPage();
                pdfCopier.AddPage(pdfCopier.GetImportedPage(new PdfReader(pageByteArray), 1));
            }
            pdfCopier.Close();

            outputstream.Position = 0;
        }
 //Burst-- Make each page of an existing multi-page PDF document 
 //as another brand new PDF document
 private void PDFBurst()
 {
     string pdfTemplatePath = Server.MapPath(P_InputStream3);
     PdfReader reader = new PdfReader(pdfTemplatePath);
     //PdfCopy copy;
     PdfSmartCopy copy;
     for (int i = 1; i < reader.NumberOfPages; i++)
     {
         Document d1 = new Document();
         copy = new PdfSmartCopy(d1, new FileStream(Server.MapPath(P_OutputStream).Replace(".pdf", i.ToString() + ".pdf"), FileMode.Create));
         d1.Open();
         copy.AddPage(copy.GetImportedPage(reader, i));
         d1.Close();
     }
 }
Exemple #12
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;
            }
        }
Exemple #13
0
 public static void WriteInTemplate(List<Models.Statement> statementList)
     {
         try
         {
             string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim();
                  
             using (Document document = new Document())
             {
                 FileStream fileStream = new FileStream(HostingEnvironment.MapPath("~/Content/reports/" + invoiceNumber + ".pdf"), FileMode.Create);
                 using (PdfSmartCopy smartCopy = new PdfSmartCopy(document, fileStream))
                 {
                     document.Open();
                     PdfReader pdfReader = new PdfReader(HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf"));
                             using (var memoryStream = new MemoryStream())
                             {
                                 using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
                                 {
                                     string month = null;
                                     string day = null;
                                     string year = null;
                                     AcroFields pdfFields = pdfStamper.AcroFields;
                                     {//billing address
                                         pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper());
                                         pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper());
                                         pdfFields.SetField("ShipToCompany", statementList.FirstOrDefault().ShipToCompany.ToString().Trim().ToUpper());
                                         pdfFields.SetField("ShipToContact", statementList.FirstOrDefault().ShipToContact.ToString().Trim().ToUpper());
                                         pdfFields.SetField("PONumber", statementList.FirstOrDefault().PurchaseOrderNo.ToString().Trim());
                                         pdfFields.SetField("OrderNumber", statementList.FirstOrDefault().Order_Number.ToString().Trim());
                                         pdfFields.SetField("ShippingMethod", statementList.FirstOrDefault().Shipping_Method.ToString().Trim());
                                         pdfFields.SetField("PaymentTerms", statementList.FirstOrDefault().Payment_Terms.ToString().Trim());
                                    }
                                    pdfStamper.FormFlattening = true; // generate a flat PDF 
                                 }
                                 pdfReader = new PdfReader(memoryStream.ToArray());
                                 smartCopy.AddPage(smartCopy.GetImportedPage(pdfReader, 1));
                             }
                 }
             }
                 
             emailController.CreateMessageWithAttachment(invoiceNumber);
         }
         catch (Exception e)
         {
         }
     }
        public static byte[] DeletePages(byte[] fileContents, int[] pages)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4))
                {
                    using (var pdfReader = new PdfReader(fileContents))
                    {
                        pages = pages
                                .Where(o => o >= 1 && o <= pdfReader.NumberOfPages)
                                .Distinct()
                                .ToArray();

                        if (pages.Length < pdfReader.NumberOfPages)
                        {
                            using (var copyWriter = new PdfSmartCopy(document, memoryStream))
                            {
                                document.Open();
                                copyWriter.RegisterFonts();

                                var contents = copyWriter.DirectContent;

                                for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                                {
                                    if (!pages.Contains(i))
                                    {
                                        var importedPage = copyWriter.GetImportedPage(pdfReader, i);

                                        copyWriter.AddPage(importedPage);
                                    }
                                }

                                document.Close();
                                copyWriter.RegisterProperties();

                                fileContents = memoryStream.ToArray();
                            }
                        }
                    }
                }
            }

            return(fileContents);
        }
Exemple #15
0
        public void TrimLeftandRightFoall(string sourceFilePath, string outputFilePath, float cropwidth)
        {
            PdfReader pdfReader = new PdfReader(sourceFilePath);

            float widthTo_Trim = Utilities.MillimetersToPoints(cropwidth);



            using (var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
            {
                // Create a new document
                Document doc = new Document();

                // Make a copy of the document
                PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);

                // Open the newly created document
                doc.Open();

                // Loop through all pages of the source document
                for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                {
                    // Get a page
                    var page = pdfReader.GetPageN(i);
                    iTextSharp.text.Rectangle cropbox = pdfReader.GetCropBox(i);

                    float        width        = cropbox.Width;
                    float        height       = cropbox.Height;
                    PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, widthTo_Trim, width - widthTo_Trim, height - widthTo_Trim);

                    page.Put(PdfName.MEDIABOX, rectLeftside);



                    var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
                    smartCopy.AddPage(copiedPage);
                }

                doc.Close();
            }
        }
        virtual public void XmpEncodingTest()
        {
            String       fileName = "xmp_UTF-16BE-encoding";
            Document     document = new Document();
            PdfSmartCopy copy     = new PdfSmartCopy(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create));

            document.Open();

            PdfReader reader    = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf");
            int       pageCount = reader.NumberOfPages;

            for (int currentPage = 1; currentPage <= pageCount; currentPage++)
            {
                PdfImportedPage page = copy.GetImportedPage(reader, currentPage);
                copy.AddPage(page);
            }


            MemoryStream os  = new MemoryStream();
            XmpWriter    xmp = new XmpWriter(os, XmpWriter.UTF16, 2000);

            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata");
            xmp.Close();

            copy.XmpMetadata = os.ToArray();

            string metadataXml = System.Text.Encoding.GetEncoding("UTF-16BE").GetString(copy.XmpMetadata);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(metadataXml);  //<-- This is where the exception is thrown


            document.Close();
            copy.Close();
            reader.Close();
        }
Exemple #17
0
        public static Byte[] MultiplePDF(string[] mySelectIDArray, string reportName, string schoolyear, string schoolcode, string sessionID)
        {
            Document     doc      = new Document();
            MemoryStream msOutput = new MemoryStream();
            //           PdfCopy pCopy;
            PdfCopy pCopy = new PdfSmartCopy(doc, msOutput);

            doc.Open();

            for (int j = 0; j < mySelectIDArray.Length; j++)
            {
                string userID     = HttpContext.Current.User.Identity.Name;
                string employeeID = mySelectIDArray[j].ToString();
                if (employeeID != "")
                {
                    try
                    {
                        Byte[] myPDF;
                        myPDF = GetOneReport(reportName, userID, schoolyear, schoolcode, sessionID);
                        MemoryStream stream1  = new MemoryStream(myPDF);
                        PdfReader    pdfFile1 = new PdfReader(stream1.ToArray());
                        for (int i = 1; i <= pdfFile1.NumberOfPages; i++)
                        {
                            pCopy.AddPage(pCopy.GetImportedPage(pdfFile1, i));
                        }
                        pdfFile1.Close();
                    }
                    catch { }
                }
            }
            try
            {
                pCopy.Close();
                doc.Close();
            }
            catch { }

            return(msOutput.ToArray());
        }
Exemple #18
0
        public static byte[] SavePDF(IList <byte[]> Lbyte)
        {
            Document     document = new Document();
            MemoryStream memory   = new MemoryStream();
            //这里用的是smartCopy,整篇文档只会导入一份字体。属于可接受范围内
            PdfSmartCopy copy = new PdfSmartCopy(document, memory);

            document.Open();
            PdfReader reader = new PdfReader(Lbyte.FirstOrDefault());

            document.NewPage();
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                //for循环新增文档页数,并copy pdf数据
                PdfImportedPage imported = copy.GetImportedPage(reader, i);
                copy.AddPage(imported);
            }
            reader.Close();
            copy.Close();
            document.Close();
            return(memory.ToArray());
        }
Exemple #19
0
        virtual public void XmpEncodingTest()
        {
            String       fileName = "xmp_utf-8_encoding";
            Document     document = new Document();
            PdfSmartCopy copy     = new PdfSmartCopy(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create));

            document.Open();

            PdfReader reader    = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf");
            int       pageCount = reader.NumberOfPages;

            for (int currentPage = 1; currentPage <= pageCount; currentPage++)
            {
                PdfImportedPage page = copy.GetImportedPage(reader, currentPage);
                copy.AddPage(page);
            }


            PdfAConformanceLevel pdfaLevel = PdfAConformanceLevel.PDF_A_1B;
            MemoryStream         os        = new MemoryStream();
            PdfAXmpWriter        xmp       = new PdfAXmpWriter(os, copy.Info, pdfaLevel, copy);

            xmp.Close();

            copy.XmpMetadata = os.ToArray();

            string metadataXml = System.Text.Encoding.GetEncoding("UTF-8").GetString(copy.XmpMetadata);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(metadataXml);  //<-- This is where the exception is thrown


            document.Close();
            copy.Close();
            reader.Close();
        }
Exemple #20
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();
            }
        }
Exemple #21
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();
                    }
                }
            }
        }
        public void MergeAndStampPdf(bool resetStampEachPage, String[] input, String output, String stamp)
        {
            PdfReader        stampReader    = new PdfReader(pdfContent[stamp]);
            List <PdfReader> readersToClose = new List <PdfReader>();

            readersToClose.Add(stampReader);

            MemoryStream baos = new MemoryStream();

            try
            {
                Document document = new Document();

                PdfCopy writer = new PdfSmartCopy(document, baos);
                try
                {
                    document.Open();

                    int stampPageNum = 1;

                    foreach (string element in input)
                    {
                        // create a reader for the input document
                        PdfReader documentReader = new PdfReader(
                            new RandomAccessFileOrArray(
                                new RandomAccessSourceFactory().CreateSource(pdfContent[element])
                                )
                            , null);

                        for (int pageNum = 1; pageNum <= documentReader.NumberOfPages; pageNum++)
                        {
                            // import a page from the main file
                            PdfImportedPage mainPage = writer.GetImportedPage(documentReader, pageNum);

                            // make a stamp from the page and get under content...
                            PdfCopy.PageStamp pageStamp = writer.CreatePageStamp(mainPage);

                            // import a page from a file with the stamp...
                            if (resetStampEachPage)
                            {
                                stampReader = new PdfReader(pdfContent[stamp]);
                                readersToClose.Add(stampReader);
                            }
                            PdfImportedPage stampPage = writer.GetImportedPage(stampReader, stampPageNum++);

                            // add the stamp template, update stamp, and add the page
                            pageStamp.GetOverContent().AddTemplate(stampPage, 0, 0);
                            pageStamp.AlterContents();
                            writer.AddPage(mainPage);

                            if (stampPageNum > stampReader.NumberOfPages)
                            {
                                stampPageNum = 1;
                            }
                        }
                    }
                }
                finally
                {
                    writer.Close();
                    document.Close();
                }
            }
            finally
            {
                foreach (PdfReader stampReaderToClose in readersToClose)
                {
                    stampReaderToClose.Close();
                }
            }
            pdfContent[output] = baos.ToArray();
        }
Exemple #24
0
        private void merge_btn_Click(object sender, EventArgs e)
        {
            //gets the size of linked list...
            int list_len = 0;

            list_len = path_link.len();

            //If user tries to merge without choosing two files atleast...
            while (list_len == 0)
            {
                MessageBox.Show("Please Choose Files First !");
                choose_btn_Click(sender, e);
                return;
            }

            //path of our merged file...
            string outputPdfPath = @"C:\Users\umair\source\repos\basic\basic\mergedDoc\getMerged.pdf";

            //Creates a new Document...
            Document doc = new Document();

            //Creates an outputStream file for the doc...
            FileStream out_file = new FileStream(outputPdfPath, FileMode.Create);

            //Creates a copy of document...
            PdfSmartCopy copy_doc = new PdfSmartCopy(doc, out_file);

            //open document
            doc.Open();

            Node curr = path_link.head;

            //Merge all files in a link list
            for (int f = 0; f < list_len; f++)
            {
                //Reads pdf...
                PdfReader read_pdf = new PdfReader(curr.path);

                //gets total number of pages in read_pdf;
                int TotalPages = read_pdf.NumberOfPages;

                //Adding each page in doc...
                for (int i = 1; i <= TotalPages; i++)
                {
                    //get each page of file and adding it to doc...
                    PdfImportedPage get_page = copy_doc.GetImportedPage(read_pdf, i);
                    copy_doc.AddPage(get_page);
                }
                curr = curr.next;
                read_pdf.Close();
            }

            //save the output file
            doc.Close();

            DialogResult show_dialog = MessageBox.Show("Download your Merged File !", "Success!", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            if (show_dialog == DialogResult.OK)
            {
                System.Diagnostics.Process.Start(outputPdfPath);
            }
            if (show_dialog == DialogResult.Cancel)
            {
                this.Hide();
                merge_page h = new merge_page();
                h.Show();
            }
        }
        public void convertoonepdf(String Idproofimage, String resiproofimage, string documentproof, String VC, string PDFName, String Ecafno)
        {
            try
            {
                var creatfpdf = Server.MapPath("~/MyExcelFile/");

                var finalPDF = System.IO.Path.Combine(creatfpdf, PDFName);

                var Header_text = getheader_text();

                //This variable will eventually hold our combined PDF as a byte array
                Byte[] finalFileBytes;

                //Write everything to a MemoryStream
                using (var finalFile = new System.IO.MemoryStream())
                {
                    //Create a generic Document
                    Document doc = new Document();


                    //Use PdfSmartCopy to intelligently merge files
                    PdfSmartCopy copy = new PdfSmartCopy(doc, finalFile);


                    //Open our document for writing
                    doc.Open();

                    //#1 - Import the SSRS report

                    //Bind a reader to our SSRS report
                    PdfReader.unethicalreading = true;
                    if (Idproofimage != "http://localhost/yesbank/MobImages/")
                    {
                        if (Idproofimage.ToUpper().Contains(".PDF"))
                        {
                            try
                            {
                                PdfReader reader1 = new PdfReader(Idproofimage);

                                for (var i = 1; i <= reader1.NumberOfPages; i++)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader1, i));
                                }
                                reader1.Close();
                            }
                            catch
                            { }
                        }
                        else
                        {
                            try
                            {
                                iTextSharp.text.Rectangle pageSize = null;
                                WebClient    wc    = new WebClient();
                                byte[]       bytes = wc.DownloadData(Idproofimage);
                                MemoryStream ms    = new MemoryStream(bytes);
                                using (var srcImage = new Bitmap(ms))
                                {
                                    if (srcImage.Width < 580)
                                    {
                                        pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100);
                                    }
                                    else
                                    {
                                        pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100);
                                    }
                                }

                                //Will eventually hold the PDF with the image as a byte array
                                Byte[] imageBytes;

                                //Simple image to PDF
                                using (var m = new MemoryStream())
                                {
                                    Document d = new Document(pageSize, 0, 0, 0, 0);

                                    PdfWriter w = PdfWriter.GetInstance(d, m);

                                    d.Open();
                                    d.Add(iTextSharp.text.Image.GetInstance(Idproofimage));
                                    d.Close();
                                    //Grab the bytes before closing out the stream
                                    imageBytes = m.ToArray();
                                }

                                //Now merge using the same merge code as #1
                                PdfReader reader1 = new PdfReader(imageBytes);

                                for (var i = 1; i <= reader1.NumberOfPages; i++)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader1, i));
                                }
                                reader1.Close();
                                ms.Close();
                            }
                            catch
                            { }
                        }
                    }
                    //#3 - Merge additional PDF
                    if (resiproofimage != "http://localhost/yesbank/MobImages/")
                    {
                        if (resiproofimage.ToUpper().Contains(".PDF"))
                        {
                            try
                            {
                                PdfReader reader1 = new PdfReader(resiproofimage);

                                for (var i = 1; i <= reader1.NumberOfPages; i++)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader1, i));
                                }
                                reader1.Close();
                            }
                            catch
                            { }
                        }
                        else
                        {
                            try
                            {
                                iTextSharp.text.Rectangle pageSize = null;
                                WebClient    wc    = new WebClient();
                                byte[]       bytes = wc.DownloadData(resiproofimage);
                                MemoryStream ms    = new MemoryStream(bytes);
                                using (var srcImage = new Bitmap(ms))
                                {
                                    if (srcImage.Width < 580)
                                    {
                                        pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100);
                                    }
                                    else
                                    {
                                        pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100);
                                    }
                                }

                                //Will eventually hold the PDF with the image as a byte array
                                Byte[] imageBytes;

                                //Simple image to PDF
                                using (var m = new MemoryStream())
                                {
                                    Document d = new Document(pageSize, 0, 0, 0, 0);

                                    PdfWriter w = PdfWriter.GetInstance(d, m);

                                    d.Open();
                                    d.Add(iTextSharp.text.Image.GetInstance(resiproofimage));
                                    d.Close();



                                    //Grab the bytes before closing out the stream
                                    imageBytes = m.ToArray();
                                }

                                //Now merge using the same merge code as #1
                                PdfReader reader1 = new PdfReader(imageBytes);

                                for (var i = 1; i <= reader1.NumberOfPages; i++)
                                {
                                    copy.AddPage(copy.GetImportedPage(reader1, i));
                                }
                                reader1.Close();
                                ms.Close();
                            }
                            catch
                            { }
                        }
                    }

                    if (documentproof != "http://localhost/yesbank/MobImages/")
                    {
                        try
                        {
                            PdfReader reader1 = new PdfReader(documentproof);

                            for (var i = 1; i <= reader1.NumberOfPages; i++)
                            {
                                copy.AddPage(copy.GetImportedPage(reader1, i));
                            }
                            reader1.Close();
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    doc.Close();
                    copy.Close();

                    //Grab the bytes before closing the stream
                    finalFileBytes = finalFile.ToArray();

                    System.IO.File.WriteAllBytes(finalPDF, finalFileBytes);

                    byte[] bytesaa = File.ReadAllBytes(finalPDF);
                    iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.RED);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        PdfReader reader = new PdfReader(bytesaa);
                        using (PdfStamper stamper = new PdfStamper(reader, stream))
                        {
                            int pages = reader.NumberOfPages;
                            for (int i = 1; i <= pages; i++)
                            {
                                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase("E-CAF No. : " + Ecafno, blackFont), 568f, 15f, 0);
                            }
                        }
                        bytesaa = stream.ToArray();
                    }
                    File.WriteAllBytes(finalPDF, bytesaa);
                }
            }
            catch
            { }
        }
        /// <summary>
        /// Returns a memory stream for a combined document, comprising all the supplied pdf documents
        /// </summary>
        /// <param name="documents">The documents to combine</param>
        /// <returns>The memory stream for the combined document</returns>
        public MemoryStream PdfDocumentCombinedStream(IList <Document> documents)
        {
            // If we have no documents at all, do not proceed
            if (documents.Count == 0)
            {
                return(null);
            }

            // Initialise the new PDF document object to create, the output stream to write its data to, and the PdfSmartCopy writer
            var combinedDocument        = new iTextSharp.text.Document();
            var oCombinedDocumentStream = new MemoryStream();
            var pdfWriter = new PdfSmartCopy(combinedDocument, oCombinedDocumentStream);

            // Set compression options
            pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
            pdfWriter.CompressionLevel = PdfStream.BEST_COMPRESSION;
            pdfWriter.SetFullCompression();

            // Open document object to write to - this is the actual object that gets created and modified in memoey
            // The pdf writer outputs this to the memory stream (if we wanted to, we could just as easily write to a file instead)
            combinedDocument.Open();

            // Iterate through all pdf documents in the collection
            foreach (var document in documents)
            {
                var oStream = new MemoryStream();

                // Read individual document content
                var reader = new PdfReader(document.LatestRevision.Content.Content);

                // Create a pdf stamper to modify the content and output it to a memory stream
                // We set it to flatten the form field data in the output, so it cannot be modified
                // Note that text fields are flattened explicitly later in the method
                // so the only form fields that actually get flattened are radio buttons, check boxes etc
                var stamper = new PdfStamper(reader, oStream)
                {
                    FormFlattening = true
                };
                var form = stamper.AcroFields;
                var keys = new ArrayList(form.Fields.Keys.ToList());

                // Create an arial base font
                // We use this during flattening of text fields
                var arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                var arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                foreach (var key in keys)
                {
                    if (form.GetFieldType(key.ToString()) == 4)
                    {
                        // Text field

                        // Render the form field content as a replacement text (Phrase) object
                        // We do this here as the built-in FormFlattening option causes a font error in the final pdf

                        const float fontSize      = 8.0f;
                        const float leading       = 8.0f;
                        const float minimumHeight = 12.5f;
                        const float adjustmentY   = 1.5f;

                        // Get field positioning information
                        var fieldPositions = form.GetFieldPositions(key.ToString());
                        if (fieldPositions.Count == 0)
                        {
                            break;
                        }
                        var fieldPosition    = fieldPositions[0];
                        var height           = fieldPosition.position.Top - fieldPosition.position.Bottom;
                        var width            = fieldPosition.position.Right - fieldPosition.position.Left;
                        var heightAdjustment = height < minimumHeight ? minimumHeight - height : 0.0f;

                        // Generate the Phrase object which holds the rendered text, and populate it using the contents of the form field
                        var phrase = new Phrase(leading, form.GetField(key.ToString()), new iTextSharp.text.Font(arialBaseFont, fontSize));

                        // Table object to hold the Phrase
                        // This allows us to set the vertical and horizontal alignment of each rendered Phrase
                        var table = new PdfPTable(1)
                        {
                            WidthPercentage = 100
                        };
                        table.SetWidths(new[] { width });

                        // Table cell object in which the Phrase will be positioned
                        var cell = new PdfPCell {
                            FixedHeight         = height + heightAdjustment,
                            Border              = iTextSharp.text.Rectangle.NO_BORDER,
                            VerticalAlignment   = Element.ALIGN_MIDDLE,
                            HorizontalAlignment = Element.ALIGN_LEFT
                        };
                        cell.AddElement(phrase);
                        table.AddCell(cell);

                        // We now create our ColumnText wrapper, which allows us to position the table in the same place as the original form field
                        var columnText = new ColumnText(stamper.GetOverContent(fieldPosition.page));
                        columnText.SetSimpleColumn(fieldPosition.position.Left, fieldPosition.position.Bottom + adjustmentY - heightAdjustment, fieldPosition.position.Right, fieldPosition.position.Top + adjustmentY);
                        columnText.AddElement(table);
                        columnText.Go();

                        // Finally, all that is left to do is to remove the original form field
                        form.RemoveField(key.ToString());
                    }
                    else
                    {
                        // Non-text field

                        // Append each form field name to have a unique suffix
                        // This is so that when we join all the documents together, all the form field names are unique and therefore still rendered correctly
                        form.RenameField(key.ToString(), string.Format("{0}{1}", key, documents.IndexOf(document)));
                    }
                }

                // We now compress all images in the pdf
                // http://cjhaas.com/blog/2012/01/06/how-to-recompress-images-in-a-pdf-using-itextsharp/

                const int physicalSizePercentage = 90;
                const int compressionPercentage  = 85;

                var numberOfPages = reader.NumberOfPages;
                for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    // Get the XObject structure
                    var resources = (PdfDictionary)PdfReader.GetPdfObject(reader.GetPageN(currentPageIndex).Get(PdfName.RESOURCES));
                    var xObjects  = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT));
                    if (xObjects != null)
                    {
                        // Loop through each XObject key
                        foreach (var key in xObjects.Keys)
                        {
                            var xObject = xObjects.Get(key);
                            if (xObject.IsIndirect())
                            {
                                // Get the current key as a pdf object
                                var imgObject = (PdfDictionary)PdfReader.GetPdfObject(xObject);

                                // Is the object an image?
                                if (imgObject != null && imgObject.Get(PdfName.SUBTYPE).Equals(PdfName.IMAGE))
                                {
                                    // Note: There are several different types of filters we're only handing the simplest one here which is basically raw jpeg
                                    if (imgObject.Get(PdfName.FILTER).Equals(PdfName.DCTDECODE))
                                    {
                                        // Get the raw bytes of the image
                                        var    oldBytes = PdfReader.GetStreamBytesRaw((PRStream)imgObject);
                                        byte[] newBytes;

                                        // Wrap a stream around our original image
                                        using (var memoryStream = new MemoryStream(oldBytes))
                                        {
                                            // Convert the bytes into a .NET image
                                            using (var oldImage = System.Drawing.Image.FromStream(memoryStream))
                                            {
                                                // Shrink the source image to a percentage of its original size
                                                using (var newImage = ShrinkImage(oldImage, physicalSizePercentage / 100.0f))
                                                {
                                                    // Convert the image to bytes using jpeg
                                                    newBytes = ConvertImageToBytes(newImage, compressionPercentage);
                                                }
                                            }
                                        }

                                        // Create a new iTextSharp image from our bytes
                                        var compressedImage = Image.GetInstance(newBytes);

                                        // Kill off the old image
                                        PdfReader.KillIndirect(xObject);

                                        // Add our image in its place
                                        stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)xObject);
                                    }
                                }
                            }
                        }
                    }
                }

                stamper.Writer.CloseStream = false;
                stamper.Close();

                // Read modified document content from the pdf stamper's output stream
                reader        = new PdfReader(oStream.ToArray());
                numberOfPages = reader.NumberOfPages;

                // Add each modified page to our combined document object
                for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    var page = pdfWriter.GetImportedPage(reader, currentPageIndex);
                    pdfWriter.AddPage(page);
                }
            }

            // Close the pdf writer and the combined document object
            // This will flush the output memory stream, and give us our completed document data
            pdfWriter.CloseStream = false;
            pdfWriter.Close();
            combinedDocument.Close();

            // Move the stream position to the beginning then return it
            oCombinedDocumentStream.Seek(0, SeekOrigin.Begin);

            return(oCombinedDocumentStream);
        }
Exemple #27
0
        //2.4.1
        //fill text to each PDF withgroup E letters_____________________________________________________________________ E.2
        private void FillTextToPDF_E(string inputPDFFile, PdfSmartCopy copy, FPL1LTR pageInfo, string LtrSubGrp, string PtnCNY)
        {
            using (var baos = new MemoryStream())
            {
                using (PdfReader templateReader = new PdfReader(GlobalVar.wPATH() + inputPDFFile))  //source template PDF (group E only)  d:\L1Letters\E_Letters_template.pdf
                {
                    using (PdfStamper stamper = new PdfStamper(templateReader, baos))
                    {
                        //create a font family (細明體HKSCS + EUDC)
                        string   fontPath   = @"d:\MINGLIU.TTC,2"; //path + @"\MINGLIU.TTC,2";
                        BaseFont bfChinese  = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                        string   fontPath2  = @"d:\EUDC.TTF";
                        BaseFont bfChinese2 = BaseFont.CreateFont(fontPath2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                        List <BaseFont> FontFamily = new List <BaseFont>();
                        FontFamily.Add(bfChinese);
                        FontFamily.Add(bfChinese2);

                        AcroFields fields = stamper.AcroFields;
                        fields.SubstitutionFonts   = FontFamily;
                        fields.GenerateAppearances = true;

                        fields.SetField("cname", pageInfo.PTNCNA);
                        stamper.AcroFields.SetFieldProperty("pname", "textsize", 0f, null);  //font auto resize (0f)
                        fields.SetField("pname", pageInfo.PTNNAM);
                        fields.SetField("ltrno", pageInfo.LTRNO);
                        fields.SetField("idno", pageInfo.PTNIDN.Substring(0, 4) + "XXXX");
                        fields.SetField("ofcdate", DateTime.Now.ToString("dd/MM/yyyy"));
                        fields.SetField("ptnno", pageInfo.PTNNO);
                        fields.SetField("ptnnoidx", pageInfo.PTNNO.Trim() + "/" + pageInfo.IDX.ToString().Trim());
                        fields.SetField("barcode", pageInfo.PTNNO + "-" + pageInfo.LTRNO);

                        stamper.AcroFields.SetFieldProperty("addr1", "textsize", 0f, null);
                        fields.SetField("addr1", pageInfo.ADDR1);

                        if (pageInfo.ADDR2.Trim() == "")   //向前移 (如空白, 分段地址向上移)
                        {
                            if (pageInfo.ADDR3.Trim() == "")
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                            else
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR3;
                                pageInfo.ADDR3 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                        }

                        if (pageInfo.ADDR3.Trim() == "")  //向前移 (如空白, 分段地址向上移)
                        {
                            pageInfo.ADDR3 = pageInfo.ADDR4;
                            pageInfo.ADDR4 = "";
                        }

                        stamper.AcroFields.SetFieldProperty("addr2", "textsize", 0f, null);
                        fields.SetField("addr2", pageInfo.ADDR2.Trim());
                        stamper.AcroFields.SetFieldProperty("addr3", "textsize", 0f, null);
                        fields.SetField("addr3", pageInfo.ADDR3.Trim());
                        fields.SetField("addr4", pageInfo.ADDR4);

                        //_GenQRCode(stamper, "QRcode", pageInfo.PTNNO);     //E-Letters don't need QRcode! Requested by Elyse on 17/7/2019

                        stamper.FormFlattening = true;
                    }

                    using (var template_filled = new PdfReader(baos.ToArray()))
                    {
                        copy.AddPage(copy.GetImportedPage(template_filled, 1));
                    }
                }
            } // end : fill text in a PDF (group E only)
        }
Exemple #28
0
        //2.2.1
        //fill text to each PDF except group E letters__________________________________________________________________ 2.2.2
        private void FillTextToPDF_POR(string inputPDFFile, PdfSmartCopy copy, FPL1LTR pageInfo, string LtrSubGrp, string PtnCNY)
        {
            using (var baos = new MemoryStream())                                                                              //inputHead=p1_inPOR_xxxxxx.PDF
            {
                using (PdfReader templateReader = new PdfReader(GlobalVar.wPATH() + inputPDFFile.Replace("inXXX_", "inPOR_"))) //input= "d:\L1Letters\" + "inPOR_A1提款信_MO_1-18480_page18480_1.PDF"
                {
                    using (PdfStamper stamper = new PdfStamper(templateReader, baos))
                    {
                        //create a font family (細明體HKSCS + EUDC)
                        string   fontPath   = @"d:\MINGLIU.TTC,2"; //path + @"\MINGLIU.TTC,2";
                        BaseFont bfChinese  = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                        string   fontPath2  = @"d:\EUDC.TTF";
                        BaseFont bfChinese2 = BaseFont.CreateFont(fontPath2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                        List <BaseFont> FontFamily = new List <BaseFont>();
                        FontFamily.Add(bfChinese);
                        FontFamily.Add(bfChinese2);

                        AcroFields fields = stamper.AcroFields;
                        fields.SubstitutionFonts   = FontFamily;
                        fields.GenerateAppearances = true;

                        fields.SetField("cname", pageInfo.PTNCNA);
                        stamper.AcroFields.SetFieldProperty("pname", "textsize", 0f, null);  //font auto resize (0f)
                        fields.SetField("pname", pageInfo.PTNNAM);
                        fields.SetField("ltrno", pageInfo.LTRNO);
                        fields.SetField("idno", pageInfo.PTNIDN.Substring(0, 4) + "XXXX");
                        fields.SetField("ofcdate", DateTime.Now.ToString("dd/MM/yyyy"));
                        fields.SetField("ptnno", pageInfo.PTNNO);
                        fields.SetField("idx", pageInfo.IDX.ToString());
                        fields.SetField("ltrgrp", pageInfo.LTRGRP);

                        stamper.AcroFields.SetFieldProperty("addr1", "textsize", 0f, null);
                        fields.SetField("addr1", pageInfo.ADDR1);

                        if (pageInfo.ADDR2.Trim() == "")   //向前移 (如空白, 分段地址向上移)
                        {
                            if (pageInfo.ADDR3.Trim() == "")
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                            else
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR3;
                                pageInfo.ADDR3 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                        }

                        if (pageInfo.ADDR3.Trim() == "")  //向前移 (如空白, 分段地址向上移)
                        {
                            pageInfo.ADDR3 = pageInfo.ADDR4;
                            pageInfo.ADDR4 = "";
                        }

                        stamper.AcroFields.SetFieldProperty("addr2", "textsize", 0f, null);
                        fields.SetField("addr2", pageInfo.ADDR2.Trim());
                        stamper.AcroFields.SetFieldProperty("addr3", "textsize", 0f, null);
                        fields.SetField("addr3", pageInfo.ADDR3.Trim());
                        fields.SetField("addr4", pageInfo.ADDR4);


                        if (pageInfo.LTRGRP.Trim() == "D")         //3.3 政府管理子帳戶結餘, 3.4 提取款項原因   (未滿65歲)
                        {
                            if (pageInfo.UPLBAL < pageInfo.TXNBAL) //未滿65歲 (LA), 提款上限 (UPLBAL) < 結餘 (TXNBAL) then uplbal else txnbal
                            {
                                fields.SetField("p1balance", "O montante máximo a levantar é de MOP$" + String.Format("{0:#,#00.00}", pageInfo.UPLBAL) + " (incluindo a verba do ano " + DateTime.Now.Year.ToString() + ").");
                            }
                            else
                            {
                                fields.SetField("p1balance", "O montante máximo a levantar é de MOP$" + String.Format("{0:#,#00.00}", pageInfo.TXNBAL) + " (incluindo a verba do ano " + DateTime.Now.Year.ToString() + ").");
                            }
                            fields.SetField("p2age", "Não ter completado 65 anos de idade, e estar a receber a pensão de invalidez do Fundo de Segurança Social há mais de um ano ou o subsídio de invalidez especial do Instituto de Acção Social.");
                        }
                        else
                        {
                            fields.SetField("p1balance", "O saldo é de MOP$" + String.Format("{0:#,#00.00}", pageInfo.TXNBAL) + " (incluindo a verba do ano " + DateTime.Now.Year.ToString() + ").");
                            fields.SetField("p2age", "Ter completado 65 anos de idade.");
                        }


                        if (pageInfo.LTRGRP.Trim() == "C")  //3.5 款項發放
                        {
                            //fields.SetField("p4bank1", "Por depósito na minha conta bancária em MOP n.º_____Banco___"); //全型underline
                            fields.SetField("p4bank1", "Por depósito na conta bancária em MOP nº_________Banco___"); //全型underline
                            fields.SetField("p4bank2", "(Deve anexar fotocópias do BIRM e da conta bancária)");
                            fields.SetField("p4bank3", "");
                            fields.SetField("p4bank4", "");
                            fields.SetField("p4bank5", "");
                        }
                        else
                        {
                            fields.SetField("p4bank1", "A  verba  será   depositada   na  conta  bancária   do  requerente   pela  ordem");
                            fields.SetField("p4bank2", "seguinte: 1. Conta bancária na qual recebe a pensão para idosos ou pensão de");
                            fields.SetField("p4bank3", "invalidez do FSS. 2. Conta bancária na qual recebe o subsídio para idosos do");
                            fields.SetField("p4bank4", "Instituto de  Acção  Social.  3. Conta  bancária  na  qual recebe o subsídio de");
                            fields.SetField("p4bank5", "invalidez especial do Instituto de Acção Social.");
                        }

                        if (pageInfo.LTRGRP.Trim() == "A")
                        {
                            fields.SetField("p6point", "6.");
                            fields.SetField("p6label", "Inscrição    de     levantamento");
                            fields.SetField("p6label2", "automático de verbas:");

                            fields.SetField("p6auto1", "Se   concordar ,   pode    participar   na   “Inscrição   de    levantamento");
                            fields.SetField("p6auto2", "automático  de  verbas”  (vide  Guia para a  inscrição de  levantamento");
                            fields.SetField("p6auto3", "automático  de  verbas), tomando conhecimento  de que a partir do ano");
                            fields.SetField("p6auto4", "seguinte   ao   registo,  não   é   preciso   efectuar  o   requerimento   de");
                            fields.SetField("p6auto5", "levantamento  de  verba desde que sejam  preenchidos os requisitos  no");
                            fields.SetField("p6auto6", "ano  em  causa.  A  verba  do  ano  relevante  será  atribuída   na   conta");
                            fields.SetField("p6auto7", "bancária acima referida.");

                            string          fontPath3   = @"c:\windows\fonts\Webdings.TTF";
                            BaseFont        bfChinese3  = BaseFont.CreateFont(fontPath3, BaseFont.IDENTITY_V, BaseFont.EMBEDDED);
                            List <BaseFont> FontFamily3 = new List <BaseFont>();
                            FontFamily3.Add(bfChinese3);
                            AcroFields fields3 = stamper.AcroFields;
                            fields3.SubstitutionFonts = FontFamily3;
                            fields3.SetField("p6chkbox", "");

                            _GenQRCode(stamper, "QRcode", pageInfo.PTNNO);
                        }

                        stamper.FormFlattening = true;
                    }

                    using (var template_filled = new PdfReader(baos.ToArray()))
                    {
                        copy.AddPage(copy.GetImportedPage(template_filled, 1));
                    }
                }
            } // end : fill text in a PDF
        }
Exemple #29
0
        //2.2.1
        //fill text to each PDF except group E letters__________________________________________________________________ 2.2.1
        private void FillTextToPDF_CHN(string inputPDFFile, PdfSmartCopy copy, FPL1LTR pageInfo, string LtrSubGrp, string PtnCNY)
        {
            // Console.WriteLine("start chn  " + pageInfo.LTRNO + " === " + DateTime.Now.ToString());

            using (var baos = new MemoryStream())  //p1_inCHN_xxxxxx.PDF
            {
                //using (PdfReader templateReader = new PdfReader(outputPDFFile))  //source template PDF (chn version)  d:\L1Letters\L1_Letters_chn_template.pdf
                using (PdfReader templateReader = new PdfReader(GlobalVar.wPATH() + inputPDFFile.Replace("inXXX_", "inCHN_"))) //input= "d:\L1Letters\" + "p1_inCHN_A1提款信_MO_1-18480_page18480_1.PDF"
                {
                    using (PdfStamper stamper = new PdfStamper(templateReader, baos))                                          //convert inXXX_ to inCHN_
                    {
                        //create a font family (細明體HKSCS + EUDC)
                        string   fontPath   = @"d:\MINGLIU.TTC,2"; //path + @"\MINGLIU.TTC,2";
                        BaseFont bfChinese  = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                        string   fontPath2  = @"d:\EUDC.TTF";
                        BaseFont bfChinese2 = BaseFont.CreateFont(fontPath2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                        List <BaseFont> FontFamily = new List <BaseFont>();
                        FontFamily.Add(bfChinese);
                        FontFamily.Add(bfChinese2);

                        AcroFields fields = stamper.AcroFields;
                        fields.SubstitutionFonts   = FontFamily;
                        fields.GenerateAppearances = true;

                        fields.SetField("cname", pageInfo.PTNCNA);
                        stamper.AcroFields.SetFieldProperty("pname", "textsize", 0f, null);  //font auto resize (0f)
                        fields.SetField("pname", pageInfo.PTNNAM);
                        fields.SetField("ltrno", pageInfo.LTRNO);
                        fields.SetField("idno", pageInfo.PTNIDN.Substring(0, 4) + "XXXX");
                        fields.SetField("ofcdate", DateTime.Now.ToString("dd/MM/yyyy"));
                        fields.SetField("ptnno", pageInfo.PTNNO);
                        fields.SetField("idx", pageInfo.IDX.ToString());
                        fields.SetField("ltrgrp", pageInfo.LTRGRP);

                        stamper.AcroFields.SetFieldProperty("addr1", "textsize", 0f, null);
                        fields.SetField("addr1", pageInfo.ADDR1);

                        if (pageInfo.ADDR2.Trim() == "")   //向前移 (如空白, 分段地址向上移)
                        {
                            if (pageInfo.ADDR3.Trim() == "")
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                            else
                            {
                                pageInfo.ADDR2 = pageInfo.ADDR3;
                                pageInfo.ADDR3 = pageInfo.ADDR4;
                                pageInfo.ADDR4 = "";
                            }
                        }

                        if (pageInfo.ADDR3.Trim() == "")  //向前移 (如空白, 分段地址向上移)
                        {
                            pageInfo.ADDR3 = pageInfo.ADDR4;
                            pageInfo.ADDR4 = "";
                        }

                        stamper.AcroFields.SetFieldProperty("addr2", "textsize", 0f, null);
                        fields.SetField("addr2", pageInfo.ADDR2.Trim());
                        stamper.AcroFields.SetFieldProperty("addr3", "textsize", 0f, null);
                        fields.SetField("addr3", pageInfo.ADDR3.Trim());
                        fields.SetField("addr4", pageInfo.ADDR4);


                        if (pageInfo.LTRGRP.Trim() == "D")  //3.3 政府管理子帳戶結餘, 3.4 提取款項原因
                        {
                            fields.SetField("p1balance", "可提取的款項為澳門幣" + String.Format("{0:#,#00.00}", pageInfo.TXNBAL) + "(已包括" + DateTime.Now.Year.ToString() + "年度的款項)");
                            stamper.AcroFields.SetFieldProperty("p2age", "textsize", 0f, null);  //font auto resize (0f)
                            fields.SetField("p2age", "未滿65歲,正收取社會保障基金殘疾金超過一年或社會工作局特別殘疾津貼");
                        }
                        else
                        {
                            fields.SetField("p1balance", "結餘為澳門幣" + String.Format("{0:#,#00.00}", pageInfo.TXNBAL) + "(已包括" + DateTime.Now.Year.ToString() + "年度的款項)");
                            fields.SetField("p2age", "已年滿65歲");
                        }

                        if (pageInfo.LTRGRP.Trim() == "C")                                  //3.5 款項發放
                        {
                            fields.SetField("p4bank1", "存入本人澳門幣銀行帳號__________銀行名稱_______"); //全型underline
                            fields.SetField("p4bank2", "(須附同澳門居民身份證影印本及銀行帳號影印本)");
                            fields.SetField("p4bank3", "");
                        }
                        else
                        {
                            fields.SetField("p4bank1", "款項將按以下順序存入申請人的銀行帳戶:1.收取社會保障基金養老金或");
                            fields.SetField("p4bank2", "殘疾金的銀行帳戶、2.收取社會工作局敬老金的銀行帳戶、3.收取社會工");
                            fields.SetField("p4bank3", "作局特別殘疾津貼的銀行帳戶。");
                        }

                        if (pageInfo.LTRGRP.Trim() == "A")
                        {
                            fields.SetField("p6point", "6.");
                            fields.SetField("p6label", "自動提款登記:");

                            fields.SetField("p6auto1", "同意參與《自動提款登記》(詳見自動提款登記指南),並知悉自登");
                            fields.SetField("p6auto2", "記翌年起在符合條件的年度可無需辦理提款申請,相關年度的分配款");
                            fields.SetField("p6auto3", "項將發放至上述的銀行帳戶。");

                            string          fontPath3   = @"c:\windows\fonts\Webdings.TTF";
                            BaseFont        bfChinese3  = BaseFont.CreateFont(fontPath3, BaseFont.IDENTITY_V, BaseFont.EMBEDDED);
                            List <BaseFont> FontFamily3 = new List <BaseFont>();
                            FontFamily3.Add(bfChinese3);
                            AcroFields fields3 = stamper.AcroFields;
                            fields3.SubstitutionFonts = FontFamily3;
                            fields3.SetField("p6chkbox", "");

                            _GenQRCode(stamper, "QRcode", pageInfo.PTNNO);
                        }

                        stamper.FormFlattening = true;
                    }

                    using (var template_filled = new PdfReader(baos.ToArray()))
                    {
                        copy.AddPage(copy.GetImportedPage(template_filled, 1));
                    }
                }
            } // end : fill text in a PDF

            //Console.WriteLine("end chn  " + pageInfo.LTRNO + " === " + DateTime.Now.ToString());
        }
Exemple #30
0
        public static void GenerateDeck(Guid deckGuid, bool generateMissingCards, bool singleDoc = true)
        {
            var jsonFile = Repository.GetDeckJsonFile(deckGuid);

            if (!File.Exists(jsonFile))
            {
                return;
            }

            var deck = JsonConvert.DeserializeObject <Deck>(File.ReadAllText(jsonFile));

            using (FileStream zipToOpen = new FileStream(Repository.GetDeckZipFile(deckGuid), FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    var licfiles = Directory.GetFiles(Repository.LicPath);
                    foreach (var licfile in licfiles)
                    {
                        var licName = Path.GetFileName(licfile);
                        archive.CreateEntryFromFile(licfile, licName);
                    }

                    foreach (var deckCard in deck.DeckCards)
                    {
                        var cardPdf = Repository.GetPdfFile(deckCard.Card.Guid);
                        if (!File.Exists(cardPdf))
                        {
                            if (generateMissingCards)
                            {
                                CardGenerator.CreatePngJob(deckCard.Card.Guid, deckCard.Card.Faction.Name, deckCard.Card.Type.Name);
                            }
                            else
                            {
                                continue;
                            }
                        }

                        if (!singleDoc)
                        {
                            var entryName = SanitizeName(deckCard.Card.Name);

                            for (var i = 0; i < deckCard.Quantity; i++)
                            {
                                archive.CreateEntryFromFile(cardPdf, $"{entryName}_{i + 1}.pdf");
                            }
                        }
                    }

                    var cardBackPdfFile = Repository.GetBackPdfFile();
                    if (!File.Exists(cardBackPdfFile))
                    {
                        if (generateMissingCards)
                        {
                            CardGenerator.CreateBackPdfJob();
                        }
                    }

                    if (!singleDoc)
                    {
                        if (File.Exists(cardBackPdfFile))
                        {
                            archive.CreateEntryFromFile(cardBackPdfFile, $"back.pdf");
                        }
                    }
                    var deckFormatFile = Repository.GetDeckFormatFile(deckGuid);
                    if (File.Exists(deckFormatFile))
                    {
                        archive.CreateEntryFromFile(deckFormatFile, $"deck.txt");
                    }

                    if (singleDoc)
                    {
                        var deckpdf = Repository.GetDeckFile(deck.Guid);
                        using (FileStream stream = new FileStream(deckpdf, FileMode.Create))
                        {
                            using (Document pdfDoc = new Document())
                            {
                                pdfDoc.AddAuthor($"{deck.Creator.Name}");
                                pdfDoc.AddCreator($"{deck.Creator.Name} - wtactics.org");
                                pdfDoc.AddTitle($"{deck.Name} - wtactics.org");
                                PdfCopy pdf = new PdfSmartCopy(pdfDoc, stream);

                                pdfDoc.Open();
                                foreach (var deckCard in deck.DeckCards)
                                {
                                    var cardPdf = Repository.GetPdfFile(deckCard.Card.Guid);
                                    using (var reader = new PdfReader(cardPdf))
                                    {
                                        for (var i = 0; i < deckCard.Quantity; i++)
                                        {
                                            pdf.AddPage(pdf.GetImportedPage(reader, 1));
                                        }
                                    }
                                }

                                using (var reader = new PdfReader(cardBackPdfFile))
                                {
                                    pdf.AddPage(pdf.GetImportedPage(reader, 1));
                                }
                            }
                            archive.CreateEntryFromFile(deckpdf, $"deck.pdf");
                        }
                    }
                }
            }
        }
 public bool Split(Stream os, long sizeInBytes) {
     if (!HasMorePages()) {
         os.Close();
         return false;
     }
     overSized = false;
     Document document = new Document();
     PdfCopy copy = new PdfSmartCopy(document, os);
     document.Open();
     bool hasPage = false;
     PdfResourceCounter counter = new PdfResourceCounter(reader.Trailer);
     long trailer = counter.GetLength(null);
     IDictionary<int, PdfObject> resources = counter.Resources;
     long length = 0;
     long page;
     while (HasMorePages()) {
         counter = new PdfResourceCounter(reader.GetPageN(currentPage));
         page = counter.GetLength(resources);
         resources = counter.Resources;
         length += page + trailer + XrefLength(resources.Count);
         LOGGER.Info(String.Format("Page {0}: Comparing {1} with {2}", currentPage, length, sizeInBytes));
         LOGGER.Info(String.Format("   page {0} trailer {1} xref {2}", page, trailer, XrefLength(resources.Count)));
         if (!hasPage || length < sizeInBytes) {
             hasPage = true;
             copy.AddPage(copy.GetImportedPage(reader, currentPage));
             length = copy.Os.Counter;
             LOGGER.Info(String.Format("Size after adding page: {0}", length));
             if (length > sizeInBytes) overSized = true;
             currentPage++;
         } else {
             LOGGER.Info("Page doesn't fit");
             break;
         }
     }
     document.Close();
     return true;
 }