protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

            Rectangle rect             = new Rectangle(36, 700, 100, 100);
            String    embeddedFileName = "test.docx";

            // the 3rd argument is the file description.
            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the AFRelationship key value.
            PdfFileSpec   fileSpec   = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, PATH, null, embeddedFileName, null, null);
            PdfAnnotation attachment = new PdfFileAttachmentAnnotation(rect, fileSpec);

            // This method sets the text that will be displayed for the annotation or the alternate description,
            // if this type of annotation does not display text.
            attachment.SetContents("Click me");

            // Create XObject and draw it with the imported image on the canvas
            // to add XObject as normal appearance.
            PdfFormXObject xObject   = new PdfFormXObject(rect);
            ImageData      imageData = ImageDataFactory.Create(IMG);
            PdfCanvas      canvas    = new PdfCanvas(xObject, pdfDoc);

            canvas.AddImageFittedIntoRectangle(imageData, rect, true);
            attachment.SetNormalAppearance(xObject.GetPdfObject());

            pdfDoc.AddNewPage().AddAnnotation(attachment);

            pdfDoc.Close();
        }
示例#2
0
        public virtual void AddAssociatedFilesTest02()
        {
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + "add_associated_files02.pdf",
                                                                    new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)));

            pdfDocument.SetTagged();
            PdfCanvas       pageCanvas   = new PdfCanvas(pdfDocument.AddNewPage());
            PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.Create(sourceFolder + "berlin2013.jpg"
                                                                                       ));

            imageXObject.AddAssociatedFile(PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 1".GetBytes
                                                                                  (), "af_1.txt", PdfName.Data));
            pageCanvas.AddXObject(imageXObject, 40, 400);
            PdfFormXObject formXObject = new PdfFormXObject(new Rectangle(200, 200));
            PdfCanvas      formCanvas  = new PdfCanvas(formXObject, pdfDocument);

            formCanvas.SaveState().Circle(100, 100, 50).SetColor(ColorConstants.BLACK, true).Fill().RestoreState();
            formCanvas.Release();
            formXObject.AddAssociatedFile(PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 2".GetBytes
                                                                                 (), "af_2.txt", PdfName.Data));
            pageCanvas.AddXObject(formXObject, 40, 100);
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "add_associated_files02.pdf"
                                                                             , sourceFolder + "cmp_add_associated_files02.pdf", "d:/", "diff_"));
        }
示例#3
0
        public virtual void AddAssociatedFilesTest01()
        {
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(destinationFolder + "add_associated_files01.pdf",
                                                                    new WriterProperties().SetPdfVersion(PdfVersion.PDF_2_0)));

            pdfDocument.SetTagged();
            pdfDocument.AddAssociatedFile("af_1", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 1".
                                                                                     GetBytes(), "af_1.txt", PdfName.Data));
            pdfDocument.AddNewPage();
            pdfDocument.GetFirstPage().AddAssociatedFile("af_2", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 2"
                                                                                                    .GetBytes(), "af_2.txt", PdfName.Data));
            PdfStructTreeRoot root = pdfDocument.GetStructTreeRoot();

            root.AddAssociatedFile("af_3", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 3".GetBytes
                                                                                  (), "af_3.txt", PdfName.Data));
            PdfFileSpec af5 = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, "Associated File 5".GetBytes(), "af_5",
                                                                 "af_5.txt", PdfName.Data);
            PdfTextAnnotation textannot = new PdfTextAnnotation(new Rectangle(100, 600, 50, 40));

            textannot.SetText(new PdfString("Text Annotation 01")).SetContents(new PdfString("Some contents..."));
            textannot.AddAssociatedFile(af5);
            pdfDocument.GetFirstPage().AddAnnotation(textannot);
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "add_associated_files01.pdf"
                                                                             , sourceFolder + "cmp_add_associated_files01.pdf", "d:/", "diff_"));
        }
        public virtual void FileSpecCheckTest02()
        {
            String          outPdf       = destinationFolder + "pdfA2b_fileSpecCheckTest02.pdf";
            String          cmpPdf       = cmpFolder + "cmp_pdfA2b_fileSpecCheckTest02.pdf";
            PdfWriter       writer       = new PdfWriter(outPdf);
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            FileStream   fis = new FileStream(sourceFolder + "pdfa.pdf", FileMode.Open, FileAccess.Read);
            MemoryStream os  = new MemoryStream();

            byte[] buffer = new byte[1024];
            int    length;

            while ((length = fis.JRead(buffer, 0, buffer.Length)) > 0)
            {
                os.Write(buffer, 0, length);
            }
            pdfDocument.AddFileAttachment("some pdf file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, os.ToArray(
                                                                                                  ), "some pdf file", "foo.pdf", PdfName.ApplicationPdf, null, null));
            pdfDocument.Close();
            CompareResult(outPdf, cmpPdf);
        }
示例#5
0
        public virtual void FileSpecCheckTest02()
        {
            String          outPdf       = destinationFolder + "pdfA3b_fileSpecCheckTest02.pdf";
            String          cmpPdf       = cmpFolder + "cmp_pdfA3b_fileSpecCheckTest02.pdf";
            PdfWriter       writer       = new PdfWriter(outPdf);
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            MemoryStream           txt  = new MemoryStream();
            FormattingStreamWriter @out = new FormattingStreamWriter(txt);

            @out.Write("<foo><foo2>Hello world</foo2></foo>");
            @out.Dispose();
            pdfDocument.AddAssociatedFile("foo file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, txt.ToArray(), "foo file"
                                                                                         , "foo.xml", null, PdfName.Unspecified));
            pdfDocument.Close();
            CompareResult(outPdf, cmpPdf);
        }
示例#6
0
 public virtual void EncryptWithPasswordAes128EmbeddedFilesOnly()
 {
     String filename = "encryptWithPasswordAes128EmbeddedFilesOnly.pdf";
     int encryptionType = EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.EMBEDDED_FILES_ONLY;
     String outFileName = destinationFolder + filename;
     int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
     PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption(USER, OWNER, permissions
         , encryptionType).AddXmpMetadata());
     PdfDocument document = new PdfDocument(writer);
     document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
     PdfPage page = document.AddNewPage();
     String textContent = "Hello world!";
     WriteTextBytesOnPageContent(page, textContent);
     String descripton = "encryptedFile";
     String path = sourceFolder + "pageWithContent.pdf";
     document.AddFileAttachment(descripton, PdfFileSpec.CreateEmbeddedFileSpec(document, path, descripton, path
         , null, null));
     page.Flush();
     document.Close();
     //NOTE: Specific crypto filters for EFF StmF and StrF are not supported at the moment. iText don't distinguish objects based on their semantic role
     //      because of this we can't read streams correctly and corrupt such documents on stamping.
     bool ERROR_IS_EXPECTED = true;
     CheckDecryptedWithPasswordContent(destinationFolder + filename, OWNER, textContent, ERROR_IS_EXPECTED);
     CheckDecryptedWithPasswordContent(destinationFolder + filename, USER, textContent, ERROR_IS_EXPECTED);
 }
示例#7
0
        public void AttachFileiText()
        {
            string inPdf         = "noattach.pdf";
            string sourcePdfFile = Path.Combine(this.pdfRessources, inPdf);
            // Set source and target folders
            string targetFolder = outDir;
            var    method       = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string targetFile   = Path.Combine(targetFolder, string.Concat(DateTime.Now.ToString("yyyyMMdd"), "_" + method + ".pdf"));

            Assert.IsTrue(File.Exists(sourcePdfFile), "Source file doesn't exist");

            if (File.Exists(targetFile))
            {
                File.Delete(targetFile);
            }
            Assert.IsFalse(File.Exists(targetFile));

            WriterProperties propComp = new WriterProperties();

            propComp.SetFullCompressionMode(false);
            propComp.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfWriter   theCompWriter = new PdfWriter(targetFile, propComp);
            PdfDocument origPdf       = new PdfDocument(new PdfReader(sourcePdfFile), theCompWriter);

            Assert.IsNotNull(origPdf);

            PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(origPdf, Encoding.ASCII.GetBytes("Some text in the attached document"), "description of attachment here", "test.txt", null, null, null);

            origPdf.AddFileAttachment("attadescr", spec);
            origPdf.Close();
            Assert.IsTrue(new FileInfo(sourcePdfFile).Length < new FileInfo(targetFile).Length, "target file is not bigger than the source file");
        }
示例#8
0
        private bool createiText7Pdf(string password = null)
        {
            bool success = false;

            log.Info($"Using iText7 library to create a package with format [{this.packerType}]");
            if (this.overwrite)
            {
                deleteIfExist(this.dstFileName);
            }

            try
            {
                Stream stream = getTemplatePdfStream();
                if (stream == null)
                {
                    log.Error("Could not read the PDF Template from stream");
                    throw new FileNotFoundException("Could not read the PDF template");
                }

                WriterProperties propComp = new WriterProperties();
                propComp.SetFullCompressionMode(true);
                propComp.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
                if (String.IsNullOrEmpty(password))
                {
                    log.Warn($"No password was supplied, so the output file will be unencrypted [{this.dstFileName}]");
                }
                else
                {
                    byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
                    propComp.SetStandardEncryption(passwordBytes, passwordBytes, 0, EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
                    log.Info("Enabled PDF AES_256 encryption");
                }
                PdfWriter   theCompWriter = new PdfWriter(this.dstFileName, propComp);
                PdfDocument newPdf        = new PdfDocument(new PdfReader(stream), theCompWriter);
                foreach (string file in this.srcFileList)
                {
                    string      filename = Path.GetFileName(file);
                    PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(
                        newPdf, File.ReadAllBytes(file), filename, filename, null, null, null);
                    newPdf.AddFileAttachment(filename, fileSpec);
                    log.Debug($"Added file '{filename}' as attachment to pdf");
                }
                newPdf.Close();
            }
            catch (Exception e)
            {
                log.Error($"Exception while trying to pack with iText7", e);
                return(false);
            }
            log.Info($"Successfully packed the files into [{this.dstFileName}]");
            return(success);
        }
        // This method adds file attachment to the pdf document
        private void AddFileAttachment(PdfDocument document, String attachmentPath, String fileName)
        {
            String embeddedFileName        = fileName;
            String embeddedFileDescription = fileName;
            String fileAttachmentKey       = fileName;

            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the AFRelationship key value.
            PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(document, attachmentPath, embeddedFileDescription,
                                                                      embeddedFileName, null, null);

            document.AddFileAttachment(fileAttachmentKey, fileSpec);
        }
        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();
        }
示例#11
0
        /// <summary>
        /// Creates the PDF file.
        /// </summary>
        /// <param name="xml">a byte array with XML data</param>
        /// <param name="html">the HTML file as a byte array</param>
        /// <param name="baseUri">the base URI</param>
        /// <param name="dest">the path to the resulting PDF</param>
        /// <param name="intent">a path to the output intent</param>
        public void CreatePdf(byte[] xml, byte[] html, String baseUri, String dest, String intent)
        {
            PdfWriter    writer = new PdfWriter(dest);
            PdfADocument pdf    = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3A,
                                                   new PdfOutputIntent("Custom", "", "http://www.color.org",
                                                                       "sRGB IEC61966-2.1", new FileStream(intent, FileMode.Open, FileAccess.Read)));

            pdf.SetTagged();
            pdf.AddFileAttachment("Movie info",
                                  PdfFileSpec.CreateEmbeddedFileSpec(pdf, xml, "Movie info", "movies.xml",
                                                                     PdfName.ApplicationXml, new PdfDictionary(), PdfName.Data));
            ConverterProperties properties = new ConverterProperties();

            properties.SetBaseUri(baseUri);
            HtmlConverter.ConvertToPdf(new MemoryStream(html), pdf, properties);
        }
示例#12
0
        private void ManipulatePdf(String dest)
        {
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);
            PdfFont bold = PdfFontFactory.CreateFont(BOLD, 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_3B,
                                                   new PdfOutputIntent("Custom", "",
                                                                       null, "sRGB IEC61966-2.1", fileStream));

            Document document = new Document(pdfDoc, PageSize.A4.Rotate());

            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.ModDate, new PdfDate().GetPdfObject());

            // Embeds file to the document
            PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc,
                                                                      File.ReadAllBytes(DATA),
                                                                      "united_states.csv", "united_states.csv",
                                                                      new PdfName("text/csv"), parameters, PdfName.Data);

            pdfDoc.AddAssociatedFile("united_states.csv", fileSpec);

            Table table = new Table(UnitValue.CreatePercentArray(
                                        new float[] { 4, 1, 3, 4, 3, 3, 3, 3, 1 })).UseAllAvailableWidth();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Reads content of csv file
                String line = streamReader.ReadLine();

                Process(table, line, bold, 10, true);
                while ((line = streamReader.ReadLine()) != null)
                {
                    Process(table, line, font, 10, false);
                }

                streamReader.Close();
            }

            document.Add(table);
            document.Close();
        }
示例#13
0
 public virtual void FileSpecCheckTest03()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent);
         PdfStream stream         = new PdfStream();
         pdfDocument.GetCatalog().Put(new PdfName("testStream"), stream);
         PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, sourceFolder + "sample.wav", "sample.wav"
                                                               , "sample", null, null, true);
         stream.Put(new PdfName("fileData"), spec.GetPdfObject());
         pdfDocument.AddNewPage();
         pdfDocument.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.FileSpecificationDictionaryShallNotContainTheEFKey));
     ;
 }
示例#14
0
 public virtual void FileSpecCheckTest02()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent);
         PdfStream stream         = new PdfStream();
         pdfDocument.GetCatalog().Put(new PdfName("testStream"), stream);
         PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, sourceFolder + "sample.wav", "sample.wav"
                                                               , "sample", null, null);
         stream.Put(PdfName.F, spec.GetPdfObject());
         pdfDocument.AddNewPage();
         pdfDocument.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.STREAM_OBJECT_DICTIONARY_SHALL_NOT_CONTAIN_THE_F_FFILTER_OR_FDECODEPARAMS_KEYS))
     ;
 }
示例#15
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            String embeddedFileName        = "test.txt";
            String embeddedFileDescription = "some_test";

            byte[] embeddedFileContentBytes = Encoding.UTF8.GetBytes("Some test");

            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the PdfDictionary containing embedded file's parameters;
            // the 7th argument is the AFRelationship key value.
            PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, embeddedFileContentBytes,
                                                                  embeddedFileDescription, embeddedFileName, null, null, null);

            // This method adds file attachment at document level.
            pdfDoc.AddFileAttachment("embedded_file", spec);

            pdfDoc.Close();
        }
示例#16
0
        public virtual void FileSpecCheckTest03()
        {
            String          outPdf       = destinationFolder + "pdfA3b_fileSpecCheckTest03.pdf";
            String          cmpPdf       = cmpFolder + "cmp_pdfA3b_fileSpecCheckTest03.pdf";
            PdfWriter       writer       = new PdfWriter(outPdf);
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            byte[] somePdf = new byte[25];
            pdfDocument.AddAssociatedFile("some pdf file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, somePdf, "some pdf file"
                                                                                              , "foo.pdf", PdfName.ApplicationPdf, null, PdfName.Data));
            pdfDocument.Close();
            CompareResult(outPdf, cmpPdf);
        }
        public virtual void FileSpecCheckTest03()
        {
            PdfWriter       writer       = new PdfWriter(new MemoryStream());
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            MemoryStream txt  = new MemoryStream();
            StreamWriter @out = new StreamWriter(txt);

            @out.Write("<foo><foo2>Hello world</foo2></foo>");
            @out.Dispose();
            pdfDocument.AddFileAttachment("foo file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, txt.ToArray(), "foo file"
                                                                                         , "foo.xml", PdfName.ApplicationXml, null, PdfName.Source));
            pdfDocument.Close();
        }
示例#18
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            foreach (String text in ATTACHMENTS)
            {
                String embeddedFileName         = String.Format("{0}.txt", text);
                String embeddedFileDescription  = String.Format("Some test: {0}", text);
                byte[] embeddedFileContentBytes = Encoding.UTF8.GetBytes(embeddedFileDescription);

                // the 5th argument is the mime-type of the embedded file;
                // the 6th argument is the PdfDictionary containing embedded file's parameters;
                // the 7th argument is the AFRelationship key value.
                PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, embeddedFileContentBytes,
                                                                      embeddedFileDescription, embeddedFileName, null, null, null);

                // This method adds file attachment at document level.
                pdfDoc.AddFileAttachment(String.Format("embedded_file{0}", text), spec);
            }

            pdfDoc.Close();
        }
示例#19
0
        public virtual void EmbeddedFileAddedInAppendModeTest()
        {
            //Create input document
            MemoryStream boasEmpty      = new MemoryStream();
            PdfWriter    emptyDocWriter = new PdfWriter(boasEmpty);
            PdfDocument  emptyDoc       = new PdfDocument(emptyDocWriter);

            emptyDoc.AddNewPage();
            PdfDictionary emptyNamesDic = new PdfDictionary();

            emptyNamesDic.MakeIndirect(emptyDoc);
            emptyDoc.GetCatalog().GetPdfObject().Put(PdfName.Names, emptyNamesDic);
            emptyDoc.Close();
            //Create input document
            MemoryStream boasAttached    = new MemoryStream();
            PdfWriter    attachDocWriter = new PdfWriter(boasAttached);
            PdfDocument  attachDoc       = new PdfDocument(attachDocWriter);

            attachDoc.AddNewPage();
            attachDoc.Close();
            //Attach file in append mode
            PdfReader    appendReader = new PdfReader(new MemoryStream(boasEmpty.ToArray()));
            MemoryStream boasAppend   = new MemoryStream();
            PdfWriter    appendWriter = new PdfWriter(boasAppend);
            PdfDocument  appendDoc    = new PdfDocument(appendReader, appendWriter, new StampingProperties().UseAppendMode
                                                            ());

            appendDoc.AddFileAttachment("Test File", PdfFileSpec.CreateEmbeddedFileSpec(appendDoc, boasAttached.ToArray
                                                                                            (), "Append Embedded File test", "Test file", null));
            appendDoc.Close();
            //Check final result
            PdfReader   finalReader           = new PdfReader(new MemoryStream(boasAppend.ToArray()));
            PdfDocument finalDoc              = new PdfDocument(finalReader);
            PdfNameTree embeddedFilesNameTree = finalDoc.GetCatalog().GetNameTree(PdfName.EmbeddedFiles);
            IDictionary <String, PdfObject> embeddedFilesMap = embeddedFilesNameTree.GetNames();

            NUnit.Framework.Assert.IsTrue(embeddedFilesMap.Count > 0);
            NUnit.Framework.Assert.IsTrue(embeddedFilesMap.ContainsKey("Test File"));
        }
        public virtual void FileSpecNonConformingTest01()
        {
            // According to spec, only pdfa-1 or pdfa-2 compliant pdf document are allowed to be added to the
            // conforming pdfa-2 document. We only check they mime type, to define embedded file type, but we don't check
            // the bytes of the file. That's why this test creates invalid pdfa document.
            String          outPdf       = destinationFolder + "pdfA2b_fileSpecNonConformingTest01.pdf";
            String          cmpPdf       = cmpFolder + "cmp_pdfA2b_fileSpecNonConformingTest01.pdf";
            PdfWriter       writer       = new PdfWriter(outPdf);
            Stream          @is          = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                               , @is);
            PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, outputIntent);
            PdfPage      page        = pdfDocument.AddNewPage();
            PdfFont      font        = PdfFontFactory.CreateFont(sourceFolder + "FreeSans.ttf", "WinAnsi", true);
            PdfCanvas    canvas      = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(36, 700).SetFontAndSize(font, 36).ShowText("Hello World!").EndText
                ().RestoreState();
            byte[] somePdf = new byte[25];
            pdfDocument.AddAssociatedFile("some pdf file", PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, somePdf, "some pdf file"
                                                                                              , "foo.pdf", PdfName.ApplicationPdf, null, new PdfName("Data")));
            pdfDocument.Close();
            CompareResult(outPdf, cmpPdf);
        }
示例#21
0
 public virtual void FileSpecCheckTest01()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer             = new PdfWriter(new MemoryStream());
         Stream @is                   = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfOutputIntent outputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1"
                                                            , @is);
         PdfADocument pdfDocument = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, outputIntent);
         PdfDictionary fileNames  = new PdfDictionary();
         pdfDocument.GetCatalog().Put(PdfName.Names, fileNames);
         PdfDictionary embeddedFiles = new PdfDictionary();
         fileNames.Put(PdfName.EmbeddedFiles, embeddedFiles);
         PdfArray names = new PdfArray();
         fileNames.Put(PdfName.Names, names);
         names.Add(new PdfString("some/file/path"));
         PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDocument, sourceFolder + "sample.wav", "sample.wav"
                                                               , "sample", null, null);
         names.Add(spec.GetPdfObject());
         pdfDocument.AddNewPage();
         pdfDocument.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.A_NAME_DICTIONARY_SHALL_NOT_CONTAIN_THE_EMBEDDED_FILES_KEY))
     ;
 }