Example #1
0
        public void AddOrReplaceTitle(string title)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                return;
            }

            _pdfa.GetDocumentInfo().SetMoreInfo(PdfName.Title.GetValue(), title);
        }
        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();
        }
Example #3
0
        public async Task ShouldAddCustomProperties()
        {
            var path    = $"/pdfa";
            var prop1   = Guid.NewGuid().ToString("N");
            var prop2   = Guid.NewGuid().ToString("N");
            var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf";
            var pdfFile = await File.ReadAllBytesAsync(fixture);

            var formData = new PdfFormData().WithConformanceLevel("PDF_A_2B")
                           .AddCustomProperty(nameof(prop1), prop1)
                           .AddCustomProperty(nameof(prop2), prop2)
                           .Upload(pdfFile);

            var response = await _client.PostAsync(path, formData);

            var stream = await response.Content.ReadAsStreamAsync();

            var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream()));

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(prop1, pdfa.GetDocumentInfo().GetMoreInfo(nameof(prop1)));
            Assert.Equal(prop2, pdfa.GetDocumentInfo().GetMoreInfo(nameof(prop2)));
        }
        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();
        }
Example #5
0
        public async Task ShouldReplaceAuthor()
        {
            var path    = $"/pdfa";
            var author  = Guid.NewGuid().ToString("N");
            var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf";
            var pdfFile = await File.ReadAllBytesAsync(fixture);

            var formData = new PdfFormData()
                           .WithConformanceLevel("PDF_A_2B")
                           .WithAuthor(author)
                           .Upload(pdfFile);

            var response = await _client.PostAsync(path, formData);

            var stream = await response.Content.ReadAsStreamAsync();

            var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream()));

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(author, pdfa.GetDocumentInfo().GetAuthor());
        }
Example #6
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();
        }
Example #7
0
        public async Task ShouldReplaceCreationDate()
        {
            var path         = $"/pdfa";
            var creationDate = new DateTime(1980, 10, 10);
            var fixture      = $"{Program.TestProjectPath}/Fixtures/dummy.pdf";
            var pdfFile      = await File.ReadAllBytesAsync(fixture);

            var formData = new PdfFormData()
                           .WithConformanceLevel("PDF_A_2B")
                           .WithCreationDate(creationDate)
                           .Upload(pdfFile);

            var response = await _client.PostAsync(path, formData);

            var stream = await response.Content.ReadAsStreamAsync();

            var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream()));
            var creationDateProperty = PdfName.CreationDate.GetValue();
            var pdfaCreationDate     = pdfa.GetDocumentInfo().GetMoreInfo(creationDateProperty);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(creationDate, Convert.ToDateTime(pdfaCreationDate));
        }
Example #8
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);
        }