Esempio n. 1
0
        private void ManipulatePdf(PdfDocument pdfDocument, bool setTagged)
        {
            Document document = new Document(pdfDocument);

            if (setTagged)
            {
                pdfDocument.SetTagged();
            }
            pdfDocument.GetCatalog().SetLang(new PdfString("en-US"));
            pdfDocument.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            PdfDocumentInfo info = pdfDocument.GetDocumentInfo();

            info.SetTitle("iText7 PDF/UA test");
            PdfFont   font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true);
            Paragraph p    = new Paragraph();

            p.SetFont(font);
            p.Add(new Text("The quick brown "));
            iText.Layout.Element.Image foxImage = new Image(ImageDataFactory.Create(FOX));
            foxImage.GetAccessibilityProperties().SetAlternateDescription("Fox");
            p.Add(foxImage);
            p.Add(" jumps over the lazy ");
            iText.Layout.Element.Image dogImage = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG));
            dogImage.GetAccessibilityProperties().SetAlternateDescription("Dog");
            p.Add(dogImage);
            document.Add(p);
            document.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDFA document with output intent
            PdfADocument pdf = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent
                                                    ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", new FileStream(INTENT, FileMode.Open, FileAccess.Read
                                                                                                                               )));

            //Setting some required parameters
            pdf.SetTagged();
            pdf.GetCatalog().SetLang(new PdfString("en-US"));
            pdf.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("iText7 PDF/A-1a example");
            //Create PdfMerger instance
            PdfMerger merger = new PdfMerger(pdf);
            //Add pages from the first document
            PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));

            merger.Merge(firstSourcePdf, 1, firstSourcePdf.GetNumberOfPages());
            //Add pages from the second pdf document
            PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));

            merger.Merge(secondSourcePdf, 1, secondSourcePdf.GetNumberOfPages());
            //Close the documents
            firstSourcePdf.Close();
            secondSourcePdf.Close();
            pdf.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            PdfDocument pdf      = new PdfDocument(new PdfWriter(dest, new WriterProperties().AddXmpMetadata()));
            Document    document = new Document(pdf);

            //Setting some required parameters
            pdf.SetTagged();
            pdf.GetCatalog().SetLang(new PdfString("en-US"));
            pdf.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("iText7 PDF/UA example");
            //Fonts need to be embedded
            PdfFont   font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true);
            Paragraph p    = new Paragraph();

            p.SetFont(font);
            p.Add(new Text("The quick brown "));
            iText.Layout.Element.Image foxImage = new Image(ImageDataFactory.Create(FOX));
            //PDF/UA: Set alt text
            foxImage.GetAccessibilityProperties().SetAlternateDescription("Fox");
            p.Add(foxImage);
            p.Add(" jumps over the lazy ");
            iText.Layout.Element.Image dogImage = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG));
            //PDF/UA: Set alt text
            dogImage.GetAccessibilityProperties().SetAlternateDescription("Dog");
            p.Add(dogImage);
            document.Add(p);
            document.Close();
        }
Esempio n. 4
0
        private static void AddMetaInformationForDocument(PdfDocument document, string subject, string title)
        {
            PdfDocumentInfo info = document.GetDocumentInfo();

            info.SetAuthor("Vantage Driver Management");
            info.SetKeywords("Vantage Driver Management PDF Reports");
            info.SetCreator("Vantage Driver Management App");
            info.SetSubject(subject);
            info.SetTitle(title);
        }
Esempio n. 5
0
        protected internal virtual void ManipulatePdf()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC),
                                                 new PdfWriter(DEST, new WriterProperties().AddXmpMetadata()));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("New title");
            info.AddCreationDate();

            pdfDoc.Close();
        }
Esempio n. 6
0
        public void ReporteVentas1()
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            string      dest   = "c:/temp/reporte_ventas1.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.LETTER.Rotate());

            //TAGGED PDF
            //Make document tagged
            //pdfDoc.SetTagged();

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas de la Semana");

            Paragraph p = new Paragraph();

            PdfFont font = PdfFontFactory.CreateFont();

            p.SetFont(font);
            p.SetFontSize(26);
            p.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

            p.Add("Reporte de Ventas de la Semana");

            document.Add(p);

            Table tabla = new Table(2);

            tabla.SetWidth(200);

            //tabla.SetBorder(Border.NO_BORDER);

            for (int i = 0; i < 8; i++)
            {
                Cell celda = new Cell().Add(new Paragraph("Celda " + i));
                //celda.SetBorder(Border.NO_BORDER);
                tabla.AddCell(celda);
            }

            document.Add(tabla);
            document.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            PdfADocument pdf = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_3A, new PdfOutputIntent
                                                    ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", new FileStream(INTENT, FileMode.Open, FileAccess.Read
                                                                                                                               )));
            Document document = new Document(pdf, PageSize.A4.Rotate());

            document.SetMargins(20, 20, 20, 20);
            //Setting some required parameters
            pdf.SetTagged();
            pdf.GetCatalog().SetLang(new PdfString("en-US"));
            pdf.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("iText7 PDF/A-3 example");
            //Add attachment
            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.ModDate, new PdfDate().GetPdfObject());
            PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(pdf, File.ReadAllBytes(System.IO.Path.Combine(DATA
                                                                                                                    )), "united_states.csv", "united_states.csv", new PdfName("text/csv"), parameters, PdfName.Data);

            fileSpec.Put(new PdfName("AFRelationship"), new PdfName("Data"));
            pdf.AddFileAttachment("united_states.csv", fileSpec);
            PdfArray array = new PdfArray();

            array.Add(fileSpec.GetPdfObject().GetIndirectReference());
            pdf.GetCatalog().Put(new PdfName("AF"), array);
            //Embed fonts
            PdfFont font = PdfFontFactory.CreateFont(FONT, true);
            PdfFont bold = PdfFontFactory.CreateFont(BOLD_FONT, true);
            // Create content
            Table table = new Table(UnitValue.CreatePercentArray(new float[] { 4, 1, 3, 4, 3, 3, 3, 3, 1 }))
                          .UseAllAvailableWidth();

            using (StreamReader sr = File.OpenText(DATA))
            {
                String line = sr.ReadLine();
                Process(table, line, bold, true);
                while ((line = sr.ReadLine()) != null)
                {
                    Process(table, line, font, false);
                }
            }

            document.Add(table);
            //Close document
            document.Close();
        }
Esempio n. 8
0
        public virtual void CreatePdf(String dest)
        {
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().AddXmpMetadata().SetPdfVersion
                                                                (PdfVersion.PDF_1_6)));
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("The Strange Case of Dr. Jekyll and Mr. Hyde");
            info.SetAuthor("Robert Louis Stevenson");
            info.SetSubject("A novel");
            info.SetKeywords("Dr. Jekyll, Mr. Hyde");
            info.SetCreator("A simple tutorial example");
            Document document = new Document(pdf);

            document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
            document.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            PdfDocument          pdf         = new PdfDocument(new PdfWriter(dest));
            PdfViewerPreferences preferences = new PdfViewerPreferences();

            preferences.SetPrintScaling(PdfViewerPreferences.PdfViewerPreferencesConstants.NONE);
            preferences.SetNumCopies(5);
            pdf.GetCatalog().SetViewerPreferences(preferences);
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("A Strange Case");
            Document document = new Document(pdf, PageSize.A4.Rotate());

            document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
            document.Close();
        }
Esempio n. 10
0
        /// <summary>
        /// Creates a new PDF document using provided properties, adds images with
        /// recognized text.
        /// </summary>
        /// <param name="pdfWriter">
        /// the
        /// <see cref="iText.Kernel.Pdf.PdfWriter"/>
        /// object
        /// to write final PDF document to
        /// </param>
        /// <param name="pdfOutputIntent">
        ///
        /// <see cref="iText.Kernel.Pdf.PdfOutputIntent"/>
        /// for PDF/A-3u document
        /// </param>
        /// <param name="imagesTextData">
        /// map that contains input image files as keys,
        /// and as value: map pageNumber -&gt; text for the page
        /// </param>
        /// <returns>
        /// result
        /// <see cref="iText.Kernel.Pdf.PdfDocument"/>
        /// object
        /// </returns>
        private PdfDocument CreatePdfDocument(PdfWriter pdfWriter, PdfOutputIntent pdfOutputIntent, IDictionary <FileInfo
                                                                                                                 , IDictionary <int, IList <TextInfo> > > imagesTextData)
        {
            PdfDocument pdfDocument;
            bool        createPdfA3u = pdfOutputIntent != null;

            if (createPdfA3u)
            {
                pdfDocument = new PdfADocument(pdfWriter, PdfAConformanceLevel.PDF_A_3U, pdfOutputIntent, new DocumentProperties
                                                   ().SetEventCountingMetaInfo(new PdfOcrMetaInfo()));
            }
            else
            {
                pdfDocument = new PdfDocument(pdfWriter, new DocumentProperties().SetEventCountingMetaInfo(new PdfOcrMetaInfo
                                                                                                               ()));
            }
            // pdfLang should be set in PDF/A mode
            bool hasPdfLangProperty = ocrPdfCreatorProperties.GetPdfLang() != null && !ocrPdfCreatorProperties.GetPdfLang
                                          ().Equals("");

            if (createPdfA3u && !hasPdfLangProperty)
            {
                LOGGER.Error(MessageFormatUtil.Format(OcrException.CANNOT_CREATE_PDF_DOCUMENT, PdfOcrLogMessageConstant.PDF_LANGUAGE_PROPERTY_IS_NOT_SET
                                                      ));
                throw new OcrException(OcrException.CANNOT_CREATE_PDF_DOCUMENT).SetMessageParams(PdfOcrLogMessageConstant.
                                                                                                 PDF_LANGUAGE_PROPERTY_IS_NOT_SET);
            }
            // add metadata
            if (hasPdfLangProperty)
            {
                pdfDocument.GetCatalog().SetLang(new PdfString(ocrPdfCreatorProperties.GetPdfLang()));
            }
            // set title if it is not empty
            if (ocrPdfCreatorProperties.GetTitle() != null)
            {
                pdfDocument.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
                PdfDocumentInfo info = pdfDocument.GetDocumentInfo();
                info.SetTitle(ocrPdfCreatorProperties.GetTitle());
            }
            // reset passed font provider
            ocrPdfCreatorProperties.GetFontProvider().Reset();
            AddDataToPdfDocument(imagesTextData, pdfDocument, createPdfA3u);
            return(pdfDocument);
        }
        /// <summary>
        /// creates pdf
        /// </summary>
        /// <param name="dest"></param>
        private void CreatePdf(string dest)
        {
            //CountryResponse country = Countries[];

            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.A4.Rotate());


            pdfDoc.SetTagged();


            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle($"'s Details");

            Paragraph p = new Paragraph();



            p.Add($"'s Details").SetFontSize(30);

            document.Add(p);

            p = new Paragraph("\n\n\n\n").SetFontSize(20);
            document.Add(p);

            List list = new List().SetFontSize(20);

            list.Add(new ListItem($"Capital: "));
            list.Add(new ListItem($"Region: "));
            list.Add(new ListItem($"Subregion: "));
            list.Add(new ListItem($"Population: "));
            list.Add(new ListItem($"Area: "));
            list.Add(new ListItem($"NativeName: "));
            list.Add(new ListItem($"Cioc: "));
            list.Add(new ListItem($"NumericCode: "));
            document.Add(list);

            document.Close();
        }
Esempio n. 12
0
        private static string AddPage(string src, string sourceName, string documentLink, string documentName, string hash)
        {
            string dest = System.IO.Path.GetTempFileName();

            string temp = System.IO.Path.GetTempFileName();

            if (!string.IsNullOrEmpty(sourceName))
            {
                sourceName = Uri.UnescapeDataString(sourceName);
            }
            if (!string.IsNullOrEmpty(documentName))
            {
                documentName = Uri.UnescapeDataString(documentName);
            }

            PdfDocument pdfSignaturesPage = new PdfDocument(new PdfWriter(temp));
            Document    docSignatures     = new Document(pdfSignaturesPage);

            docSignatures.Add(new Paragraph("PROTOCOLO DE ASSINATURA(S)").SetFontSize(10).SetBold().SetUnderline());
            docSignatures.Add(new Paragraph("O documento acima foi proposto para assinatura digital na plataforma " + sourceName + ".").SetFontSize(10).SetMargin(0));
            docSignatures.Add(new Paragraph("Para verificar as assinaturas clique no link: " + documentLink).SetFontSize(10).SetMargin(0));
            docSignatures.Add(new Paragraph("Código do documento: " + documentName).SetFontSize(10).SetMargin(0));
            docSignatures.Add(new Paragraph("Hash do documento").SetFontSize(10).SetMargin(0));
            docSignatures.Add(new Paragraph(hash).SetFontSize(10).SetMargin(0));
            docSignatures.Add(new Paragraph("O(s) assinante(s) do documento é(são):").SetFontSize(10).SetMarginLeft(0).SetMarginTop(5));

            docSignatures.Close();
            pdfSignaturesPage.Close();

            PdfDocument     pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            PdfDocumentInfo info   = pdfDoc.GetDocumentInfo();

            info.SetTitle(documentName);

            pdfSignaturesPage = new PdfDocument(new PdfReader(temp));

            pdfSignaturesPage.CopyPagesTo(1, 1, pdfDoc);
            pdfSignaturesPage.Close();
            pdfDoc.Close();

            return(dest);
        }
        public virtual void CreatePdf(String dest)
        {
            PdfDocument          pdf         = new PdfDocument(new PdfWriter(dest));
            PdfViewerPreferences preferences = new PdfViewerPreferences();

            preferences.SetFitWindow(true);
            preferences.SetHideMenubar(true);
            preferences.SetHideToolbar(true);
            preferences.SetHideWindowUI(true);
            preferences.SetCenterWindow(true);
            preferences.SetDisplayDocTitle(true);
            pdf.GetCatalog().SetViewerPreferences(preferences);
            PdfDocumentInfo info = pdf.GetDocumentInfo();

            info.SetTitle("A Strange Case");
            Document document = new Document(pdf, PageSize.A4.Rotate());

            document.Add(new Paragraph("Mr. Jekyl and Mr. Hyde"));
            document.Close();
        }
        /// <summary>
        /// Start new pdf, create try create enviroment and objects
        /// </summary>
        /// <param name="pDirTarget">Directory where copy pdf at the end process</param>
        /// <param name="pFileNameSort">Short filenae of pdf like helloworld.pdf</param>
        /// <param name="pDocMetaTitle">Short filenae of pdf like helloworld.pdf</param>
        /// <param name="pDocMetaAuthor">Autor of file</param>
        /// <param name="pDocMetaCreator">Cretor of file</param>
        /// <param name="pDocMetaKeyWords">Separeted coma values</param>
        /// <param name="pDocMetaSubject">Litle description</param>
        public bool fnc_00_Start(String pDirTarget, String pFileNameSort, String pDocMetaTitle, String pDocMetaAuthor, String pDocMetaCreator, String pDocMetaKeyWords, String pDocMetaSubject)
        {
            fncToolClearLastError();
            m_DirTarget       = pDirTarget;
            m_FileNameSort    = pFileNameSort;
            m_DocMetaTitle    = pDocMetaTitle;
            m_DocMetaAuthor   = pDocMetaAuthor;
            m_DocMetaCreator  = pDocMetaCreator;
            m_DocMetaKeyWords = pDocMetaKeyWords;
            m_DocMetaSubject  = pDocMetaSubject;
            m_FileNameTemp    = fncToolPathCombine(m_DirTemp, pFileNameSort);
            m_FileNameTarget  = fncToolPathCombine(pDirTarget, pFileNameSort);
            // creation global objects, and directories ... and set metas
            try
            {
                System.IO.Directory.CreateDirectory(m_DirTemp);
                System.IO.Directory.CreateDirectory(pDirTarget);
                if (System.IO.File.Exists(m_FileNameTemp))
                {
                    System.IO.File.Delete(m_FileNameTemp);
                }
                m_PdfWriter = new PdfWriter(m_FileNameTemp);
                m_PdfDoc    = new PdfDocument(m_PdfWriter);
                m_info      = m_PdfDoc.GetDocumentInfo();
                m_info.SetTitle(m_DocMetaTitle);
                m_info.SetAuthor(pDocMetaAuthor);
                m_info.SetCreator(pDocMetaCreator);
                m_info.SetKeywords(pDocMetaKeyWords);
                m_info.SetSubject(pDocMetaSubject);


                m_Document = new Document(m_PdfDoc, PageSize.A4);
            }
            catch (Exception xcpt)
            {
                m_IsError  = true;
                m_ErrorMsg = xcpt.Message;
            }

            return(!m_IsError);
        }
Esempio n. 15
0
        private void ManipulatePdf(String dest)
        {
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

            Stream fileStream =
                new FileStream("../../../resources/data/sRGB_CS_profile.icm", FileMode.Open, FileAccess.Read);
            PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A,
                                                   new PdfOutputIntent("Custom", "",
                                                                       null, "sRGB IEC61966-2.1", fileStream));

            pdfDoc.GetCatalog().SetLang(new PdfString("nl-nl"));

            pdfDoc.SetTagged();

            Document doc = new Document(pdfDoc);

            doc.SetMargins(MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM);

            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info
            .SetTitle("title")
            .SetAuthor("Author")
            .SetSubject("Subject")
            .SetCreator("Creator")
            .SetKeywords("Metadata, iText, PDF")
            .SetCreator("My program using iText")
            .AddCreationDate();

            Paragraph element = new Paragraph("Hello World").SetFont(font).SetFontSize(10);

            doc.Add(element);

            Image logoImage = new Image(ImageDataFactory.Create(LOGO));

            logoImage.GetAccessibilityProperties().SetAlternateDescription("Logo");
            doc.Add(logoImage);

            doc.Close();
        }
Esempio n. 16
0
        /// <summary>
        /// Sets the title.
        /// </summary>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <param name="title">The title.</param>
        internal static void SetTitle(string pdfFilePath, string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                return;
            }

            string tempFilePath = Path.GetTempFileName();

            using (PdfReader pdfReader = new PdfReader(pdfFilePath))
            {
                using (PdfWriter pdfWriter = new PdfWriter(tempFilePath))
                {
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter))
                    {
                        PdfDocumentInfo pdfDocumentInfo = pdfDocument.GetDocumentInfo();
                        pdfDocumentInfo.SetTitle(title);
                    }
                }
            }

            File.Delete(pdfFilePath);
            File.Move(tempFilePath, pdfFilePath);
        }
Esempio n. 17
0
        private void ButtonStart_Click(object sender, EventArgs e)
        {
            string title    = IniFile.ReadIni("metadane", "Title");
            string author   = IniFile.ReadIni("metadane", "Author");
            string subject  = IniFile.ReadIni("metadane", "Subject");
            string keywords = IniFile.ReadIni("metadane", "Keywords");

            string podstawaPrawna = IniFile.ReadIni("metadane_dod", "podstawa_prawna");

            List <string> inputFolders = new List <string> {
                _inputDir
            };

            inputFolders.AddRange(Directory.GetDirectories(_inputDir, "*", SearchOption.AllDirectories).ToList());

            Dictionary <string, int>    validationErrors = new Dictionary <string, int>();
            Dictionary <string, int>    prefiksErrors    = new Dictionary <string, int>();
            Dictionary <string, string> otherErrors      = new Dictionary <string, string>();

            foreach (string inputFolder in inputFolders)
            {
                string outputFolder = inputFolder.Replace(_inputDir, _outputDir);

                Directory.CreateDirectory(outputFolder);

                string[] inputFiles = Directory.GetFiles(inputFolder, "*.pdf", SearchOption.TopDirectoryOnly);

                foreach (string inputFile in inputFiles)
                {
                    string outputFile = Path.Combine(outputFolder, Path.GetFileName(inputFile) ?? throw new InvalidOperationException());

                    PdfDocument srcPdf = new PdfDocument(new PdfReader(inputFile));

                    PdfOutputIntent rgbIntent = new PdfOutputIntent("Custom",
                                                                    "",
                                                                    "http://www.color.org",
                                                                    "sRGB IEC61966-2.1",
                                                                    new MemoryStream(Resources.sRGB_CS_profile));

                    PdfADocument outputPdf = new PdfADocument(new PdfWriter(outputFile), PdfAConformanceLevel.PDF_A_3B, rgbIntent);

                    try
                    {
                        srcPdf.CopyPagesTo(1, srcPdf.GetNumberOfPages(), outputPdf);
                    }
                    catch (Exception exception)
                    {
                        srcPdf.Close();

                        Document document = new Document(outputPdf);
                        document.Add(new Paragraph());
                        document.Close();
                        outputPdf.Close();

                        otherErrors.Add(inputFile, exception.Message);

                        continue;
                    }

                    srcPdf.Close();

                    PdfDocumentInfo info = outputPdf.GetDocumentInfo();

                    info.SetCreator("GN PDF_A Creator");

                    info.SetTitle(title);
                    info.SetAuthor(author);
                    info.SetSubject(subject);
                    info.SetKeywords(keywords);

                    info.SetMoreInfo(@"Podstawa prawna", podstawaPrawna);

                    string file = Path.GetFileName(outputFile);

                    Dictionary <string, string> rodzajDokumentu = _prefix.Where(p => file.ToUpper().Contains(p.Key.ToUpper())).ToDictionary(x => x.Key, x => x.Value);

                    if (rodzajDokumentu.Count != 1)
                    {
                        prefiksErrors.Add(inputFile, rodzajDokumentu.Count);
                        info.SetMoreInfo(@"Rodzaj Dokumentu", "");
                    }
                    else
                    {
                        info.SetMoreInfo(@"Rodzaj Dokumentu", rodzajDokumentu.Values.ElementAt(0));
                    }

                    info.SetMoreInfo("software", @"The file was created by the PDF_A program using iText 7 library");
                    info.SetMoreInfo("license", @"This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.");
                    info.SetMoreInfo("copyright", @"Copyright (C) 2019 GISNET");

                    for (int i = 0; i <= outputPdf.GetNumberOfPdfObjects(); i++)
                    {
                        PdfObject pdfObject = outputPdf.GetPdfObject(i);

                        if (pdfObject != null && pdfObject.IsStream())
                        {
                            PdfStream pdfStream = (PdfStream)pdfObject;

                            PdfObject subtype = pdfStream.Get(PdfName.Subtype);

                            if (Equals(subtype, PdfName.Image) && pdfStream.ContainsKey(PdfName.Interpolate))
                            {
                                pdfStream.Remove(PdfName.Interpolate);
                            }
                        }
                    }

                    try
                    {
                        outputPdf.Close();
                    }
                    catch (Exception exception)
                    {
                        otherErrors.Add(inputFile, exception.Message);

                        continue;
                    }

                    using (PDFACompliance pdfA = new PDFACompliance(false, outputFile, null, PDFACompliance.Conformance.e_Level3B, null, 10, false))
                    {
                        int errCnt = pdfA.GetErrorCount();

                        if (errCnt > 0)
                        {
                            validationErrors.Add(outputFile, errCnt);
                        }
                    }
                }
            }

            using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_validation.txt", FileMode.Create)))
            {
                foreach (var error in validationErrors)
                {
                    errorFile.WriteLine(error.Key + ": " + error.Value);
                }
            }

            using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_prefix.txt", FileMode.Create)))
            {
                foreach (var error in prefiksErrors)
                {
                    errorFile.WriteLine(error.Key + ": " + error.Value);
                }
            }

            using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_other.txt", FileMode.Create)))
            {
                foreach (var error in otherErrors)
                {
                    errorFile.WriteLine(error.Key + ": " + error.Value);
                }
            }

            MessageBox.Show(@"Przetwarzanie zakończono.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 18
0
        private void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.A4.Rotate());

            //TAGGED PDF
            //Make document tagged
            pdfDoc.SetTagged();

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("English pangram");

            Paragraph p = new Paragraph();

            //PDF/UA
            //Embed font
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true);

            p.SetFont(font);

            p.Add("The quick brown ");

            Image img = new Image(ImageDataFactory.Create(FOX));

            //PDF/UA
            //Set alt text
            img.GetAccessibilityProperties().SetAlternateDescription("Fox");
            p.Add(img);
            p.Add(" jumps over the lazy ");

            img = new Image(ImageDataFactory.Create(DOG));

            //PDF/UA
            //Set alt text
            img.GetAccessibilityProperties().SetAlternateDescription("Dog");
            p.Add(img);

            document.Add(p);

            p = new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n").SetFont(font).SetFontSize(20);
            document.Add(p);

            List list = new List().SetFont(font).SetFontSize(20);

            list.Add(new ListItem("quick"));
            list.Add(new ListItem("brown"));
            list.Add(new ListItem("fox"));
            list.Add(new ListItem("jumps"));
            list.Add(new ListItem("over"));
            list.Add(new ListItem("the"));
            list.Add(new ListItem("lazy"));
            list.Add(new ListItem("dog"));
            document.Add(list);

            document.Close();
        }
Esempio n. 19
0
        public IActionResult Create(string pdfHtmlString, string saveName = null)
        {
            #region Parameters
            // Global Config
            string fontFamily = Configuration["PdfConfig:GlobalConfig:FontFamily"];
            // Path Config
            string descPath = Configuration["PdfConfig:PathConfig:DescPath"];
            string logPath  = Configuration["PdfConfig:PathConfig:LogPath"];
            // MetaData Config
            string title    = Configuration["PdfConfig:MetaData:Title"];
            string author   = Configuration["PdfConfig:MetaData:Author"];
            string creator  = Configuration["PdfConfig:MetaData:Creator"];
            string keywords = Configuration["PdfConfig:MetaData:Keywords"];
            string subject  = Configuration["PdfConfig:MetaData:Subject"];
            // Header Config
            string headerText           = Configuration["PdfConfig:Header:Text"];
            float  headerFontSize       = Convert.ToSingle(Configuration["PdfConfig:Header:FontSize"]);
            string headerFontColor      = Configuration["PdfConfig:Header:FontColor"];
            string headerImageSource    = Configuration["PdfConfig:Header:Image:Source"];
            float  headerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Width"]);
            float  headerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Left"]);
            float  headerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Top"]);
            // Footer Config
            string footerText           = Configuration["PdfConfig:Footer:Text"];
            double footerFontSize       = Convert.ToDouble(Configuration["PdfConfig:Footer:FontSize"]);
            string footerFontColor      = Configuration["PdfConfig:Footer:FontColor"];
            string footerImageSource    = Configuration["PdfConfig:Footer:Image:Source"];
            float  footerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Width"]);
            float  footerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Left"]);
            float  footerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Top"]);
            #endregion

            #region Properties & Setting
            // Configure properties for converter | 配置转换器
            ConverterProperties properties = new ConverterProperties();
            // Resources path, store images/fonts for example | 资源路径, 存放如图片/字体等资源
            string resources = Host.WebRootPath + (osInfo.Platform == PlatformID.Unix ? "/src/font/" : "\\src\\font\\");
            // PDF saved path | 生成的PDF文件存放路径
            string desc = string.Empty;
            if (osInfo.Platform == PlatformID.Unix)
            {
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }
            else
            {
                descPath = "D:\\Pdf\\";
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }

            FontProvider fp = new FontProvider();
            // Add Standard fonts libs without chinese support | 添加标准字体库
            // fp.AddStandardPdfFonts();
            fp.AddDirectory(resources);
            properties.SetFontProvider(fp);
            // Set base uri to resource folder | 设置基础uri
            properties.SetBaseUri(resources);

            PdfWriter   writer = new PdfWriter(desc);
            PdfDocument pdfDoc = new PdfDocument(writer);
            // Set PageSize | 设置页面大小
            pdfDoc.SetDefaultPageSize(PageSize.A4);
            // Set Encoding | 设置文本编码方式
            pdfDoc.GetCatalog().SetLang(new PdfString("UTF-8"));

            //Set the document to be tagged | 展示文档标签树
            pdfDoc.SetTagged();
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));

            //https://developers.itextpdf.com/content/itext-7-examples/converting-html-pdf/pdfhtml-header-and-footer-example
            // create pdf font using custom resources | 自定义字体
            PdfFont sourcehansanscn = PdfFontFactory.CreateFont(resources + fontFamily, PdfEncodings.IDENTITY_H);

            Dictionary <string, object> header = new Dictionary <string, object>()
            {
                { "text", headerText },
                { "fontSize", headerFontSize },
                { "fontColor", headerFontColor },
                { "source", Host.WebRootPath + headerImageSource },
                { "width", headerImageWidth },
                { "left", headerImagePositionX },
                { "top", headerImagePositionY }
            };
            Dictionary <string, object> footer = new Dictionary <string, object>()
            {
                { "text", footerText },
                { "fontSize", footerFontSize },
                { "fontColor", footerFontColor },
                { "source", Host.WebRootPath + footerImageSource },
                { "width", footerImageWidth },
                { "left", footerImagePositionX },
                { "top", footerImagePositionY }
            };
            // Header handler | 页头处理
            PdfHeader headerHandler = new PdfHeader(header, sourcehansanscn);
            // Footer handler | 页脚处理
            PdfFooter footerHandler = new PdfFooter(footer, sourcehansanscn);

            // Assign event-handlers
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);

            // Setup custom tagworker factory for better tagging of headers | 设置标签处理器
            DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory();
            properties.SetTagWorkerFactory(tagWorkerFactory);

            // Setup default outline(bookmark) handler | 设置默认大纲(书签)处理器
            // We used the createStandardHandler() method to create a standard handler.
            // This means that pdfHTML will look for <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
            // The bookmarks will be created based on the hierarchy of those tags in the HTML file.
            // To enable other tags, read the folllowing article for more details.
            // https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml
            OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler();
            properties.SetOutlineHandler(outlineHandler);

            // Bookmark | 书签
            // https://developers.itextpdf.com/content/itext-7-examples/itext-7-bookmarks-tocs/toc-first-page
            // https://developers.itextpdf.com/content/best-itext-questions-stackoverview/actions-and-annotations/itext7-how-create-hierarchical-bookmarks
            // https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-6-creating-actions-destinations-and-bookmarks
            // https://developers.itextpdf.com/examples/actions-and-annotations/clone-named-destinations
            // PdfOutline outline = null;
            // outline = CreateOutline(outline, pdfDoc, "bookmark", "bookmark");

            // Meta tags | 文档属性标签
            PdfDocumentInfo pdfMetaData = pdfDoc.GetDocumentInfo();
            pdfMetaData.SetTitle(title);
            pdfMetaData.SetAuthor(author);
            pdfMetaData.AddCreationDate();
            pdfMetaData.GetProducer();
            pdfMetaData.SetCreator(creator);
            pdfMetaData.SetKeywords(keywords);
            pdfMetaData.SetSubject(subject);
            #endregion

            // Start convertion | 开始转化
            //Document document =
            //    HtmlConverter.ConvertToDocument(pdfHtmlString, pdfDoc, properties);

            IList <IElement>   elements        = HtmlConverter.ConvertToElements(pdfHtmlString, properties);
            Document           document        = new Document(pdfDoc);
            CJKSplitCharacters splitCharacters = new CJKSplitCharacters();
            document.SetFontProvider(fp);
            document.SetSplitCharacters(splitCharacters);
            document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters);
            foreach (IElement e in elements)
            {
                try
                {
                    document.Add((AreaBreak)e);
                }
                catch
                {
                    document.Add((IBlockElement)e);
                }
            }

            // Close and release document | 关闭并释放文档资源
            document.Close();

            return(Content("SUCCESS"));
        }
Esempio n. 20
0
        public void ReporteVentas2()
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            string      dest   = "c:/temp/reporte_ventas1.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.LETTER.Rotate());

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas de la Semana");

            float[] columnWidths = { 0.5f, 1, 5, 1 };
            Table   tabla        = new Table(UnitValue.CreatePercentArray(columnWidths));

            //tabla.SetWidth();
            tabla.UseAllAvailableWidth();
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            // celda de encabezado

            Text txt = new Text("Reporte de Ventas Semanal")
                       .SetFontSize(20)
                       .SetBold();

            Paragraph pTitulo = new Paragraph(txt)
                                .SetTextAlignment(TextAlignment.CENTER);

            document.Add(pTitulo);

            //Cell cell = new Cell(1, 4)
            //    .Add(new Paragraph("Reporte de Ventas Semanal"))
            //    .SetFont(font)
            //    .SetFontSize(13)
            //    .SetFontColor(DeviceGray.WHITE)
            //    .SetBackgroundColor(DeviceGray.BLACK)
            //    .SetTextAlignment(TextAlignment.CENTER);

            //tabla.AddHeaderCell(cell);

            for (int i = 0; i < 2; i++)
            {
                Cell[] headerFooter =
                {
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("No."))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Cant."))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Artículo"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Total"))
                    .SetBorder(Border.NO_BORDER)
                };

                foreach (Cell hfCell in headerFooter)
                {
                    if (i == 0)
                    {
                        tabla.AddHeaderCell(hfCell);
                    }
                    //    else
                    //    {
                    //        tabla.AddFooterCell(hfCell);
                    //    }
                }
            }

            for (int j = 0; j < 10; j++)
            {
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph((j + 1).ToString())));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph("cantidad " + (j + 1))));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph("lapiz adhesivo resistol no tóxico 100gr -- lapiz adhesivo resistol no tóxico 100gr " + (j + 1))));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.RIGHT)
                              .Add(new Paragraph("$100" + (j + 1))));
            }

            document.Add(tabla);
            Paragraph p = new Paragraph();

            p.SetTextAlignment(TextAlignment.RIGHT);
            p.Add("Total de la semana: $" + 10000);

            document.Add(p);

            document.Close();
        }
Esempio n. 21
0
        public void TotalVentasMesArticulo(DataTable dt)
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            string      dest   = "c:/temp/ReporteMesArticulo1.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.LETTER.Rotate());

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas de Artículo por Mes");

            float[] columnWidths = { 1, 5, 2 };
            Table   tabla        = new Table(UnitValue.CreatePercentArray(columnWidths));

            //tabla.SetWidth();
            tabla.UseAllAvailableWidth();
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            // celda de encabezado

            Text txt = new Text("Reporte de Ventas Semanal")
                       .SetFontSize(20)
                       .SetBold();

            Paragraph pTitulo = new Paragraph(txt)
                                .SetTextAlignment(TextAlignment.CENTER);

            document.Add(pTitulo);

            for (int i = 0; i < 2; i++)
            {
                Cell[] headerFooter =
                {
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Mes"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Artículo"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Total"))
                    .SetBorder(Border.NO_BORDER)
                };

                foreach (Cell hfCell in headerFooter)
                {
                    if (i == 0)
                    {
                        tabla.AddHeaderCell(hfCell);
                    }
                }
            }

            decimal totalMes = 0;

            Cell c_mes      = new Cell().SetTextAlignment(TextAlignment.CENTER);
            Cell c_articulo = new Cell().SetTextAlignment(TextAlignment.LEFT);
            Cell c_total    = new Cell().SetTextAlignment(TextAlignment.RIGHT);

            tabla.AddCell(c_articulo);
            tabla.AddCell(c_mes);
            tabla.AddCell(c_total);

            // ciclo para filas
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                c_mes.Add(new Paragraph(dt.Rows[j][0].ToString()));
                c_articulo.Add(new Paragraph(dt.Rows[j][1].ToString()));
                c_total.Add(new Paragraph(dt.Rows[j][2].ToString()));

                totalMes += (decimal)dt.Rows[j][2];
            }

            document.Add(tabla);
            Paragraph p = new Paragraph();

            p.SetTextAlignment(TextAlignment.RIGHT);
            p.Add("Total del mes: $" + totalMes);

            document.Add(p);

            document.Close();
        }
Esempio n. 22
0
        //---------------------------------------------------------------------
        //
        //---------------------------------------------------------------------
        public void ManipulatePdf()
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.A4.Rotate());

            //TAGGED PDF
            //Make document tagged
            pdfDoc.SetTagged();

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas del Mes");

            Paragraph p = new Paragraph();

            //PDF/UA
            //Embed font
            //PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true);
            //p.SetFont(font);

            PdfFont font = PdfFontFactory.CreateFont();

            p.SetFont(font);
            p.SetFontSize(26);

            p.Add("Papelería D'Loreto");

            //Image img = new Image(ImageDataFactory.Create(FOX));

            //PDF/UA
            //Set alt text
            //img.GetAccessibilityProperties().SetAlternateDescription("Fox");
            //p.Add(img);
            //p.Add(" jumps over the lazy ");

            //img = new Image(ImageDataFactory.Create(DOG));

            //PDF/UA
            //Set alt text
            //img.GetAccessibilityProperties().SetAlternateDescription("Dog");
            //p.Add(img);

            document.Add(p);

            p = new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n").SetFont(font).SetFontSize(20);
            document.Add(p);

            List list = new List().SetFont(font).SetFontSize(20);

            list.Add(new ListItem("quick"));
            list.Add(new ListItem("brown"));
            list.Add(new ListItem("fox"));
            list.Add(new ListItem("jumps"));
            list.Add(new ListItem("over"));
            list.Add(new ListItem("the"));
            list.Add(new ListItem("lazy"));
            list.Add(new ListItem("dog"));
            document.Add(list);

            document.Close();
        }