/** * <a href="http://itext.2136553.n4.nabble.com/trying-to-remove-a-signature-from-pdf-file-tt4660983.html"> * trying to remove a signature from pdf file * </a> * <br/> * <a href="http://itext.2136553.n4.nabble.com/attachment/4660983/0/PDFSignedFirmaCerta.pdf"> * PDFSignedFirmaCerta.pdf * </a> * <p> * Indeed, this code fails with a {@link NullPointerException}. The cause is that a dubious construct * created by the signature software then is processed by iText code not sufficiently defensively programmed: * The signature claims to have an annotation on a page but that page does claim not to have any anotations * at all. * </p> */ @Test public void testRemoveSignatureFromPDFSignedFirmaCerta() throws IOException, GeneralSecurityException, DocumentException { try ( InputStream inputStream = getClass().getResourceAsStream("PDFSignedFirmaCerta.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "PDFSignedFirmaCerta-withoutSig.pdf"))) { Provider provider = new BouncyCastleProvider(); Security.addProvider(provider); PdfReader reader = new PdfReader(inputStream, null); AcroFields af = reader.getAcroFields(); ArrayList<String> names = af.getSignatureNames(); for (String name : names) { System.out.println("Signature name: " + name); System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); PdfPKCS7 pk = af.verifySignature(name, provider.getName()); System.out.println("SignatureDate: " + pk.getSignDate()); System.out.println("Certificate: " + pk.getSigningCertificate()); System.out.println("Document modified: " + !pk.verify()); af.removeField(name); } PdfStamper stamper = new PdfStamper(reader, outputStream, '\0'); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/34394199/i-cant-rotate-my-page-from-existing-pdf"> * I can't rotate my page from existing PDF * </a> * <p> * Switching between portrait and landscape like this obviously will cut off some parts of the page. * </p> */ @Test public void testSwitchOrientation() throws DocumentException, IOException { try (InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/n2013.00849449.pdf")) { PdfReader reader = new PdfReader(resourceStream); int n = reader.getNumberOfPages(); PdfDictionary pageDict; for (int i = 1; i <= n; i++) { Rectangle rect = reader.getPageSize(i); Rectangle crop = reader.getCropBox(i); pageDict = reader.getPageN(i); pageDict.put(PdfName.MEDIABOX, new PdfArray(new float[] {rect.getBottom(), rect.getLeft(), rect.getTop(), rect.getRight()})); pageDict.put(PdfName.CROPBOX, new PdfArray(new float[] {crop.getBottom(), crop.getLeft(), crop.getTop(), crop.getRight()})); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "n2013.00849449-switch.pdf"))); stamper.close(); reader.close(); } }
@Test public void sign50MBrunoAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoAppend.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
/** * <a href="http://stackoverflow.com/questions/43511558/how-to-set-attributes-for-existing-pdf-that-contains-only-images-using-java-itex"> * how to set attributes for existing pdf that contains only images using java itext? * </a> * <p> * The OP indicated in a comment that he searches a solution without a second file. * This test shows how to work with a single file, by first loading the file into a byte array. * </p> */ @Test public void testChangeTitleWithoutTempFile() throws IOException, DocumentException { File singleFile = new File(RESULT_FOLDER, "eg_01-singleFile.pdf"); try ( InputStream resource = getClass().getResourceAsStream("eg_01.pdf") ) { Files.copy(resource, singleFile.toPath()); } byte[] original = Files.readAllBytes(singleFile.toPath()); PdfReader reader = new PdfReader(original); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(singleFile)); Map<String, String> info = reader.getInfo(); info.put("Title", "New title"); info.put("CreationDate", new PdfDate().toString()); stamper.setMoreInfo(info); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XmpWriter xmp = new XmpWriter(baos, info); xmp.close(); stamper.setXmpMetadata(baos.toByteArray()); stamper.close(); reader.close(); }
/** * The OP's original code transformed into Java */ void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setColorFill(new BaseColor(255,200,200)); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
/** * The OP's code transformed into Java changed with the work-around. */ void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.setColorFill(new BaseColor(255,200,200)); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader. With a different starting file, though, it doesn't, cf. * {@link #testAddUnicodeStampEg_01()}. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With * a different starting file, though, it doesn't as this test shows. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampEg_01() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("eg_01.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
@Test public void testOPCode() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 ); PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT; PdfAnnotation linkRed = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" ); PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" ); BaseColor baseColorRed = new BaseColor(255,0,0); BaseColor baseColorGreen = new BaseColor(0,255,0); linkRed.setColor(baseColorRed); linkGreen.setColor(baseColorGreen); double angleDegrees = 10; double angleRadians = Math.PI*angleDegrees/180; stamper.addAnnotation(linkRed, 1); linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians)); stamper.addAnnotation(linkGreen, 1); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation without appearance on a page without rotation. Everything looks ok. * </p> * @see #testCreateEllipseAppearance() * @see #testCreateEllipseOnRotated() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipse() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation without appearance on a page with rotation. * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader. * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseAppearance() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipseOnRotated() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90)); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer"> * Filling a PDF with iTextsharp and then hiding the base layer * </a> * <p> * This test shows how to cover all content using a white rectangle. * </p> */ @Test public void testHideContenUnderRectangle() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { Rectangle pageSize = pdfReader.getPageSize(page); PdfContentByte canvas = pdfStamper.getOverContent(page); canvas.setColorFill(BaseColor.WHITE); canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight()); canvas.fill(); } pdfStamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer"> * Filling a PDF with iTextsharp and then hiding the base layer * </a> * <p> * This test shows how to remove all content. * </p> */ @Test public void testRemoveContent() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-removedContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { PdfDictionary pageDictionary = pdfReader.getPageN(page); pageDictionary.remove(PdfName.CONTENTS); } new PdfStamper(pdfReader, result).close(); } }
@Test public void testIdentityTest3() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("test3.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test3-identity.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); PdfContentStreamEditor identityEditor = new PdfContentStreamEditor(); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { identityEditor.editPage(pdfStamper, i); } pdfStamper.close(); } }
@Test public void testIdentity20150211600() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/20150211600.PDF"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "20150211600-identity.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); PdfContentStreamEditor identityEditor = new PdfContentStreamEditor(); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { identityEditor.editPage(pdfStamper, i); } pdfStamper.close(); } }
@Test public void testRemoveTransparentGraphicsTest3() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("test3.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test3-noTransparency.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); PdfContentStreamEditor editor = new TransparentGraphicsRemover(); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { editor.editPage(pdfStamper, i); } pdfStamper.close(); } }
@Test public void testRemoveTransparentGraphicsTransparency() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("transparency.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "transparency-noTransparency.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); PdfContentStreamEditor editor = new TransparentGraphicsRemover(); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { editor.editPage(pdfStamper, i); } pdfStamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/30449348/signing-pdf-memory-consumption"> * Signing PDF - memory consumption * </a> * <br> * <a href="http://50mpdf.tk/50m.pdf">50m.pdf</a> * <p> * {@link #sign50MNaive()} tests the naive approach, * {@link #sign50MBruno()} tests Bruno's original approach, * {@link #sign50MBrunoPartial()} tests Bruno's approach with partial reading, * {@link #sign50MBrunoAppend()} tests Bruno's approach with append mode, and * {@link #sign50MBrunoPartialAppend()} tests Bruno's approach with partial reading and append mode. * </p> */ // runs with -Xmx240m, fails with -Xmx230m @Test public void sign50MNaive() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedNaive.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void sign50MBruno() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBruno.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, false); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void sign50MBrunoPartial() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoPartial.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, false); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void sign50MBrunoPartialAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "50m-signedBrunoPartialAppend.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
/** * <a href="http://stackoverflow.com/questions/30526254/sign-concatenated-pdf-in-append-mode-with-certified-no-changes-allowed"> * Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED * </a> * <br> * <a href="https://www.dropbox.com/s/lea6r9fup6th44c/test_pdf.zip?dl=0">test_pdf.zip</a> * * {@link #signCertifyG()} certifies g.pdf, OK * {@link #sign2g()} merely signs 2g.pdf, OK * {@link #signCertify2gNoAppend()} certifies 2g.pdf but not in append mode, OK * {@link #tidySignCertify2g()} first tidies, then certifies 2g.pdf, OK * {@link #signCertify2g()} certifies 2g.pdf, Adobe says invalid * {@link #signCertify2gFix()} certifies 2g-fix.pdf, OK! * * 2g-fix.pdf is a patched version of 2g.pdf with a valid /Size trailer entry * and a valid, single-sectioned cross reference table */ @Test public void signCertifyG() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "g-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void sign2g() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-signed.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void signCertify2g() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void signCertify2gNoAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified-noAppend.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
@Test public void signCertify2gFix() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g-fix.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-fix-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
public void C2_01_SignHelloWorld_sign(String src, String dest, Certificate[] chain, PrivateKey pk, String digestAlgorithm, String provider, CryptoStandard subfilter, String reason, String location) throws GeneralSecurityException, IOException, DocumentException { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileOutputStream os = new FileOutputStream(dest); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason(reason); appearance.setLocation(location); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalDigest digest = new BouncyCastleDigest(); ExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider); MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, subfilter); }
@Test public void sign2274_2007_H_PROVISIONAL_multifield() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2274_2007_H_PROVISIONAL - multifield.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2274_2007_H_PROVISIONAL - multifield-signed.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature("IntSig1"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
/** * <a href="http://stackoverflow.com/questions/32818522/itextsharp-setvisiblesignature-not-working-as-expected"> * ITextSharp SetVisibleSignature not working as expected * </a> * <p> * The issue observed by the OP (user2699460) occurs since iText(Sharp) 5.5.7 * both of iText and iTextSharp. * </p> * <p> * The file signed in this sample, test-2-user2699460-signed.pdf, has been created * as intermediary result using a simplified version of the OP's c# code. * </p> */ @Test public void signTest_2_user2699460() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/test-2-user2699460.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "test-2-user2699460-signed.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature("Bunker"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
/** * <a href="https://stackoverflow.com/questions/45351357/how-to-decrypt-128bit-rc4-pdf-file-in-java-with-user-password-if-it-is-encrpted"> * How to decrypt 128bit RC4 pdf file in java with user password if it is encrpted with user as well as owner password * </a> * <br/> * <a href="https://www.dropbox.com/s/pc74oox4y19awin/abc.pdf?dl=0"> * abc.pdf * </a> * <p> * This code shows how to decrypt an encrypted PDF for which you have the * user password, not the owner password. The procedure is closely related * to <a href="https://stackoverflow.com/a/27876840/1729265">Bruno's answer * here</a>. * </p> */ @Test public void testDecryptAbc() throws IOException, DocumentException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { try ( InputStream inputStream = getClass().getResourceAsStream("abc.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "abc-decrypted.pdf")) ) { PdfReader.unethicalreading = true; PdfReader reader = new PdfReader(inputStream, "abc123".getBytes()); Field encryptedField = PdfReader.class.getDeclaredField("encrypted"); encryptedField.setAccessible(true); encryptedField.set(reader, false); PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/38278816/remove-header-of-a-pdf-using-itext-pdfcleanupprocessor-does-not-work"> * Remove header of a pdf using iText PdfCleanUpProcessor does not work * </a> * <br/> * <a href="https://www.dropbox.com/s/4u8vupjqc4st3ib/love.pdf?dl=0"> * love.pdf * </a> * <p> * Cannot reproduce, I get a <code>org.apache.commons.imaging.ImageReadException: Invalid marker found in entropy data</code>. * </p> */ @Test public void testRedactLikeShiranSEkanayake() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("love.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "love-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); for(int i=1; i<=reader.getNumberOfPages(); i++) { //System.out.println(i); Rectangle mediabox = reader.getPageSize(i); cleanUpLocations.add(new PdfCleanUpLocation(i, new Rectangle(0,800,1000,1000))); } PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed"> * itextpdf Redaction :Partly redacted text string is fully removed * </a> * <br/> * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view"> * Document.pdf * </a> * <p> * This indeed is a case which shows that glyphs are completely removed even if their * bounding box merely minutely intersects the redaction area. While not desired by * the OP, this is how <code>PdfCleanUp</code> works. * </p> * * @see #testRedactStrictForMayankPandey() * @see #testRedactStrictForMayankPandeyLarge() */ @Test public void testRedactLikeMayankPandey() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("Document.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfCleanUpProcessor cleaner= null; PdfStamper stamper = new PdfStamper(reader, result); stamper.setRotateContents(false); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); Rectangle rectangle = new Rectangle(380, 640, 430, 665); cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK)); cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
/** * <a href="https://stackoverflow.com/questions/44304695/itext-5-5-11-bold-text-looks-blurry-after-using-pdfcleanupprocessor"> * iText 5.5.11 - bold text looks blurry after using PdfCleanUpProcessor * </a> * <br/> * <a href="http://s000.tinyupload.com/index.php?file_id=52420782334200922303"> * before.pdf * </a> * <p> * Indeed, the observation by the OP can be reproduced. The issue has been introduced * into iText in commits d5abd23 and 9967627, both dated May 4th, 2015. * </p> */ @Test public void testRedactLikeTieco() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("before.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "before-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(0f, 0f, 595f, 680f))); PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException { PdfReader reader = new PdfReader(_pdfFile); try ( ByteArrayOutputStream ms = new ByteArrayOutputStream() ) { PdfStamper stamper = new PdfStamper(reader, ms); //Don't delete otherwise the stamper flattens the layers if (readLayers) stamper.getPdfLayers(); PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter()); PdfContentByte cb = stamper.getUnderContent(1); cb.beginLayer(logoLayer); //300dpi iImage.scalePercent(24f); iImage.setAbsolutePosition(x, y); cb.addImage(iImage); cb.endLayer(); stamper.close(); return (ms.toByteArray()); } }
/** * Update NDA file with visitor name and visitor signature. * * @param destFile * @param signatureImage signature file * @param visitorName * @return File */ public static File build(Path destFile, File signatureImage, String visitorName) { try { PdfReader pdfReader = new PdfReader(ndaUrl); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(destFile.toString())); Image image = createNDAImage(signatureImage, 0, 0); PdfContentByte over = pdfStamper.getOverContent(5); over.addImage(image); PdfContentByte pdfContentByte = pdfStamper.getOverContent(5); pdfContentByte.beginText(); pdfContentByte.setFontAndSize(BaseFont.createFont (BaseFont.HELVETICA, BaseFont.CP1257, BaseFont.EMBEDDED ) , 10); pdfContentByte.setTextMatrix(112, 428); pdfContentByte.showText(visitorName); pdfContentByte.setTextMatrix(89, 406); pdfContentByte.showText(new SimpleDateFormat("E, dd MMM yyyy").format(new Date())); pdfContentByte.endText(); pdfStamper.close(); return destFile.toFile(); } catch (IOException | DocumentException | NumberFormatException e) { logger.error("Exception while generating NDA file. ",e); return null; } }
public PDFManager(byte[] pdfData, X509Certificate cert) throws Exception { reader = new PdfReader(pdfData); bout = new ByteArrayOutputStream(); PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true); numPages = reader.getNumberOfPages(); x509Certificate = cert; sap = stp.getSignatureAppearance(); }
/** * Return a stamper for the source reader document that outputs to the provided output stream * @param pOutputStream The stamper output stream * @param pSourceReader The source document reader * @return A stamper that allows the source to be manipulated, output to the provided output stream * @throws ExInternal If the stamper could not be opened using the provided reader */ private PdfStamper getStamper(OutputStream pOutputStream, PdfReader pSourceReader) throws ExInternal { try { return new PdfStamper(pSourceReader, pOutputStream); } catch (IOException | DocumentException e) { throw new ExInternal("Failed to create post processing stamper", e); } }
/** * Closes the stamper and its associated reader * @param pStamper The stamper to close * @throws ExInternal If the stamper could not be closed */ private void closeStamper(PdfStamper pStamper) throws ExInternal { try { pStamper.close(); } catch (IOException | DocumentException e) { throw new ExInternal("Failed to close post processing stamper", e); } }
/** * Render the header/footer to the document on the pages provided in the constructor. Page number placeholders are * set during rendering. * @param pStamper The stamper used to manipulate the completed document */ public void render(PdfStamper pStamper) { PdfPTable lTable = getContentTable(); float lXPosition = mPageAttributes.getMarginLeft(); float lYPosition = mPositionStrategy.getYPosition(mPageAttributes, lTable.getTotalHeight()); int lTotalPageCount = pStamper.getReader().getNumberOfPages(); mPageNumbers.forEach(pPageNumber -> { mPageNumberPlaceholders.forEach(pPageNumberPlaceholder -> pPageNumberPlaceholder.setPageNumber(pPageNumber, lTotalPageCount)); lTable.writeSelectedRows(0, -1, lXPosition, lYPosition, pStamper.getOverContent(pPageNumber)); }); }
/** * This method edits the immediate contents of a page, i.e. its content stream. * It explicitly does not descent into form xobjects, patterns, or annotations. */ public void editPage(PdfStamper pdfStamper, int pageNum) throws IOException { PdfReader pdfReader = pdfStamper.getReader(); PdfDictionary page = pdfReader.getPageN(pageNum); byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum); page.remove(PdfName.CONTENTS); editContent(pageContentInput, page.getAsDict(PdfName.RESOURCES), pdfStamper.getUnderContent(pageNum)); }