Example #1
0
        /**
         * Applies a digital signature to a document, possibly as a new revision, making
         * possible multiple signatures. The returned PdfStamper
         * can be used normally as the signature is only applied when closing.
         * <p>
         * A possible use for adding a signature without invalidating an existing one is:
         * <p>
         * <pre>
         * KeyStore ks = KeyStore.getInstance("pkcs12");
         * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
         * String alias = (String)ks.aliases().nextElement();
         * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
         * Certificate[] chain = ks.getCertificateChain(alias);
         * PdfReader reader = new PdfReader("original.pdf");
         * FileOutputStream fout = new FileOutputStream("signed.pdf");
         * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new
         * File("/temp"), true);
         * PdfSignatureAppearance sap = stp.getSignatureAppearance();
         * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
         * sap.setReason("I'm the author");
         * sap.setLocation("Lisbon");
         * // comment next line to have an invisible signature
         * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
         * stp.close();
         * </pre>
         * @param reader the original document
         * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file
         * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
         * document
         * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there.
         *     If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null.
         *     In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE>
         *     no temporary file will be created and memory will be used
         * @param append if <CODE>true</CODE> the signature and all the other content will be added as a
         * new revision thus not invalidating existing signatures
         * @param conformanceLevel PDF/A conformance level of a new PDF document
         * @return a <CODE>PdfAStamper</CODE>
         * @throws DocumentException on error
         * @throws IOException on error
         */
        public static PdfAStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, String tempFile, bool append, PdfAConformanceLevel conformanceLevel)
        {
            PdfAStamper stp;

            if (tempFile == null)
            {
                ByteBuffer bout = new ByteBuffer();
                stp               = new PdfAStamper(reader, bout, pdfVersion, append, conformanceLevel);
                stp.sigApp        = new PdfSignatureAppearance(stp.stamper);
                stp.sigApp.Sigout = bout;
            }
            else
            {
                if (Directory.Exists(tempFile))
                {
                    tempFile  = Path.Combine(tempFile, Path.GetTempFileName());
                    tempFile += ".pdf";
                }
                FileStream fout = new FileStream(tempFile, FileMode.Create);
                stp        = new PdfAStamper(reader, fout, pdfVersion, append, conformanceLevel);
                stp.sigApp = new PdfSignatureAppearance(stp.stamper);
                stp.sigApp.SetTempFile(tempFile);
            }
            stp.sigApp.Originalout = os;
            stp.sigApp.SetStamper(stp);
            stp.hasSignature = true;
            PdfDictionary catalog  = reader.Catalog;
            PdfDictionary acroForm = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.ACROFORM), catalog);

            if (acroForm != null)
            {
                acroForm.Remove(PdfName.NEEDAPPEARANCES);
                stp.stamper.MarkUsed(acroForm);
            }
            return(stp);
        }
Example #2
0
        public void ColorCheckTest4() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "pdfa2ColorCheckTest4.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
            writer.CreateXmpMetadata();
            document.Open();

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));
            document.Close();

            PdfReader reader = new PdfReader(OUT + "pdfa2ColorCheckTest4.pdf");
            PdfAStamper stamper = new PdfAStamper(reader, new FileStream(OUT + "pdfa2ColorCheckTest4_updating_failed.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
            bool exceptionThrown = false;
            try {
                iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read,
                    FileShare.Read);
                icc = ICC_Profile.GetInstance(iccProfileFileStream);
                iccProfileFileStream.Close();

                stamper.Writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
                font.Color = BaseColor.RED;
                PdfContentByte canvas = stamper.GetOverContent(1);
                canvas.SetFontAndSize(font.BaseFont, 12);
                canvas.SetColorFill(BaseColor.RED);
                ColumnText.ShowTextAligned(canvas,
                    Element.ALIGN_LEFT, new Paragraph("Hello World", font), 36, 775, 760);
                stamper.Close();
            }
            catch (PdfAConformanceException) {
                exceptionThrown = true;
            }
            reader.Close();

            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");
        }
Example #3
0
        public void ColorCheckTest3() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "pdfa2ColorCheckTest3.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
            writer.CreateXmpMetadata();
            document.Open();
            PdfDictionary sec = new PdfDictionary();
            sec.Put(PdfName.GAMMA, new PdfArray(new float[] {2.2f, 2.2f, 2.2f}));
            sec.Put(PdfName.MATRIX, new PdfArray(new float[] {0.4124f, 0.2126f, 0.0193f, 0.3576f, 0.7152f, 0.1192f, 0.1805f, 0.0722f, 0.9505f}));
            sec.Put(PdfName.WHITEPOINT, new PdfArray(new float[] {0.9505f, 1f, 1.089f}));
            PdfArray arr = new PdfArray(PdfName.CALRGB);
            arr.Add(sec);
            writer.SetDefaultColorspace(PdfName.DEFAULTGRAY, writer.AddToBody(arr).IndirectReference);
            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));
            document.Close();

            PdfReader reader = new PdfReader(OUT + "pdfa2ColorCheckTest3.pdf");
            PdfAStamper stamper = new PdfAStamper(reader, new FileStream(OUT + "pdfa2ColorCheckTest3_updating_failed.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);
            bool exceptionThrown = false;
            try {
                font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
                font.Color = BaseColor.RED;
                PdfContentByte canvas = stamper.GetOverContent(1);
                canvas.SetFontAndSize(font.BaseFont, 12);
                canvas.SetColorFill(BaseColor.RED);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph("Hello World", font), 36, 775, 0);
                stamper.Close();
            }
            catch (PdfAConformanceException) {
                exceptionThrown = true;
            }
            reader.Close();

            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");

            reader = new PdfReader(OUT + "pdfa2ColorCheckTest3.pdf");
            stamper = new PdfAStamper(reader, new FileStream(OUT + "pdfa2ColorCheckTest3_updating_ok.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_2B);

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            stamper.Writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            font.Color = BaseColor.RED;
            PdfContentByte canvas1 = stamper.GetOverContent(1);
            canvas1.SetFontAndSize(font.BaseFont, 12);
            canvas1.SetColorFill(BaseColor.RED);
            ColumnText.ShowTextAligned(canvas1,
                Element.ALIGN_LEFT, new Paragraph("Hello World", font), 36, 775, 0);
            stamper.Close();
            reader.Close();
        }
Example #4
0
        public virtual void FileSpecCheckTest7() {
            FileStream inPdf = new FileStream(RESOURCES + "fileSpec.pdf", FileMode.Open);
            MemoryStream xml = new MemoryStream();
            StreamWriter sr = new StreamWriter(xml);
            sr.Write("<foo><foo2>Hello world</foo2></foo>");
            sr.Close();

            MemoryStream output = new MemoryStream();
            PdfReader reader = new PdfReader(inPdf);
            PdfAStamper stamper = new PdfAStamper(reader, output, PdfAConformanceLevel.PDF_A_3B);

            stamper.CreateXmpMetadata();

            PdfDictionary embeddedFileParams = new PdfDictionary();
            embeddedFileParams.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(stamper.Writer, "foo", "foo",
                xml.ToArray(), "text/xml", embeddedFileParams, 0);
            fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Source);
            stamper.AddFileAttachment("description", fs);

            stamper.Close();
            reader.Close();
        }
Example #5
0
        public void StamperTextTest() {
            PdfReader reader = new PdfReader(RESOURCES + "pdfa1.pdf");
            PdfAStamper stamper = new PdfAStamper(reader, new FileStream(OUT + "stamperTextTest.pdf", FileMode.Create),
                PdfAConformanceLevel.PDF_A_1A);
            PdfArtifact artifact = new PdfArtifact();
            BaseFont bf = BaseFont.CreateFont(RESOURCES + "FreeMonoBold.ttf",
                BaseFont.WINANSI, BaseFont.EMBEDDED);
            artifact.SetType(PdfArtifact.ArtifactType.LAYOUT);
            PdfContentByte canvas = stamper.GetOverContent(1);
            canvas.OpenMCBlock(artifact);
            canvas.BeginText();
            canvas.SetFontAndSize(bf, 120);
            canvas.ShowTextAligned(Element.ALIGN_CENTER, "TEST", 200, 400, 45);
            canvas.EndText();
            canvas.CloseMCBlock(artifact);

            stamper.Close();
            reader.Close();
        }
Example #6
0
        public void StamperColorCheckTest() {
            bool exceptionThrown = false;
            try {
                PdfReader reader = new PdfReader(RESOURCES + "pdfa1.pdf");
                PdfAStamper stamper = new PdfAStamper(reader, new MemoryStream(), PdfAConformanceLevel.PDF_A_1A);
                PdfContentByte canvas = stamper.GetOverContent(1);
                Rectangle rect = stamper.Writer.PageSize;
                canvas.SetColorFill(new CMYKColor(0.1f, 0.1f, 0.1f, 0.1f));
                canvas.MoveTo(rect.Left, rect.Bottom);
                canvas.LineTo(rect.Right, rect.Bottom);
                canvas.LineTo(rect.Right, rect.Top);
                canvas.Fill();
                stamper.Close();
                reader.Close();
            } catch (PdfAConformanceException exc) {
                exceptionThrown = true;
            }

            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");
        }
Example #7
0
 /**
  * Applies a digital signature to a document, possibly as a new revision, making
  * possible multiple signatures. The returned PdfStamper
  * can be used normally as the signature is only applied when closing.
  * <p>
  * A possible use for adding a signature without invalidating an existing one is:
  * <p>
  * <pre>
  * KeyStore ks = KeyStore.getInstance("pkcs12");
  * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
  * String alias = (String)ks.aliases().nextElement();
  * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
  * Certificate[] chain = ks.getCertificateChain(alias);
  * PdfReader reader = new PdfReader("original.pdf");
  * FileOutputStream fout = new FileOutputStream("signed.pdf");
  * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new
  * File("/temp"), true);
  * PdfSignatureAppearance sap = stp.getSignatureAppearance();
  * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
  * sap.setReason("I'm the author");
  * sap.setLocation("Lisbon");
  * // comment next line to have an invisible signature
  * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
  * stp.close();
  * </pre>
  * @param reader the original document
  * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file
  * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
  * document
  * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there.
  *     If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null.
  *     In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE>
  *     no temporary file will be created and memory will be used
  * @param append if <CODE>true</CODE> the signature and all the other content will be added as a
  * new revision thus not invalidating existing signatures
  * @param conformanceLevel PDF/A conformance level of a new PDF document
  * @return a <CODE>PdfAStamper</CODE>
  * @throws DocumentException on error
  * @throws IOException on error
  */
 public static PdfAStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, String tempFile, bool append, PdfAConformanceLevel conformanceLevel)
 {
     PdfAStamper stp;
     if (tempFile == null) {
         ByteBuffer bout = new ByteBuffer();
         stp = new PdfAStamper(reader, bout, pdfVersion, append, conformanceLevel);
         stp.sigApp = new PdfSignatureAppearance(stp.stamper);
         stp.sigApp.Sigout = bout;
     } else {
         if (Directory.Exists(tempFile)) {
             tempFile = Path.Combine(tempFile, Path.GetTempFileName());
             tempFile += ".pdf";
         }
         FileStream fout = new FileStream(tempFile, FileMode.Create);
         stp = new PdfAStamper(reader, fout, pdfVersion, append, conformanceLevel);
         stp.sigApp = new PdfSignatureAppearance(stp.stamper);
         stp.sigApp.SetTempFile(tempFile);
     }
     stp.sigApp.Originalout = os;
     stp.sigApp.SetStamper(stp);
     stp.hasSignature = true;
     PdfDictionary catalog = reader.Catalog;
     PdfDictionary acroForm = (PdfDictionary) PdfReader.GetPdfObject(catalog.Get(PdfName.ACROFORM), catalog);
     if (acroForm != null) {
         acroForm.Remove(PdfName.NEEDAPPEARANCES);
         stp.stamper.MarkUsed(acroForm);
     }
     return stp;
 }
        virtual public void ManipulatePdfAutomaticTest() {
            String fileName = "xmp_metadata_updated.pdf";
            PdfReader reader = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf");
            PdfStamper stamper = new PdfAStamper(reader, new FileStream(OUT_FOLDER + fileName, FileMode.Create),
                                                 PdfAConformanceLevel.PDF_A_1A);

            stamper.Close();
            reader.Close();
            CompareResults(fileName, fileName);
        }
        virtual public void ManipulatePdf2Test() {
            String fileName = "xmp_metadata_added2.pdf";
            PdfReader reader = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf");
            PdfStamper stamper = new PdfAStamper(reader, new FileStream(OUT_FOLDER + fileName, FileMode.Create),
                                                 PdfAConformanceLevel.PDF_A_1A);
            MemoryStream os = new MemoryStream();
            XmpWriter xmp = new PdfAXmpWriter(os, reader.Info, PdfAConformanceLevel.PDF_A_1A, stamper.Writer);
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata");

            PdfProperties.SetVersion(xmp.XmpMeta, "1.4");
            xmp.Close();
            stamper.XmpMetadata = os.ToArray();
            stamper.Close();
            reader.Close();
            CompareResults(fileName, fileName);
        }
Example #10
0
        virtual public void TestPdfAStamper1()
        {
            string filename = OUT + "TestPdfAStamper1.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);
            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            document.Close();

            PdfReader reader = new PdfReader(filename);
            FileStream stamperFileStream = new FileStream(OUT + "TestPdfAStamper1_.pdf", FileMode.Create);
            PdfAStamper stamper = new PdfAStamper(reader, stamperFileStream, PdfAConformanceLevel.PDF_A_1B);
            stamper.Close();
            stamperFileStream.Close();
            reader.Close();
        }
Example #11
0
        virtual public void TestPdfAStamper3()
        {
            string filename = OUT + "TestPdfAStamper3.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfWriter writer = PdfWriter.GetInstance(document, fos);
            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));
            document.Close();

            PdfReader reader = new PdfReader(filename);
            bool exceptionThrown = false;
            try
            {
                FileStream stamperFileStream = new FileStream(OUT + "TestPdfAStamper3_.pdf", FileMode.Create);
                PdfAStamper stamper = new PdfAStamper(reader, stamperFileStream, PdfAConformanceLevel.PDF_A_1A);
                stamper.Close();
                stamperFileStream.Close();
            }
            catch (PdfAConformanceException)
            {
                exceptionThrown = true;
            }
            reader.Close();
            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");
        }
Example #12
0
        public void TestPdfAStamper2()
        {
            string filename = OUT + "TestPdfAStamper2.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2B);
            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = new FileStream(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            document.Close();

            PdfReader reader = new PdfReader(filename);
            bool exceptionThrown = false;
            try
            {
                FileStream stamperFileStream = new FileStream(OUT + "TestPdfAStamper2_.pdf", FileMode.Create);
                PdfAStamper stamper = new PdfAStamper(reader, stamperFileStream, PdfAConformanceLevel.PDF_A_1B);
                stamper.Close();
                stamperFileStream.Close();
            }
            catch (PdfAConformanceException)
            {
                exceptionThrown = true;
            }
            reader.Close();
            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");
        }