com.itextpdf.text.pdf.PdfStamper Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfStamper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 9 votes vote down vote up
/**
 * 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();
}
 
Example #2
Source File: AddAnnotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41949253/how-to-add-columntext-as-an-annotation-in-itext-pdf">
 * How to add columnText as an annotation in itext pdf
 * </a>
 * <p>
 * This test demonstrates how to use a columntext in combination with an annotation.
 * </p>
 */
@Test
public void testAddAnnotationLikeJasonY() throws IOException, DocumentException
{
    String html ="<html><h1>Header</h1><p>A paragraph</p><p>Another Paragraph</p></html>";
    String css = "h1 {color: red;}";
    ElementList elementsList = XMLWorkerHelper.parseToElementList(html, css);

    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "JasonY.pdf"))   )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        Rectangle cropBox = reader.getCropBox(1);

        PdfAnnotation annotation = stamper.getWriter().createAnnotation(cropBox, PdfName.FREETEXT);
        PdfAppearance appearance = PdfAppearance.createAppearance(stamper.getWriter(), cropBox.getWidth(), cropBox.getHeight());

        ColumnText ct = new ColumnText(appearance);
        ct.setSimpleColumn(new Rectangle(cropBox.getWidth(), cropBox.getHeight()));
        elementsList.forEach(element -> ct.addElement(element));
        ct.go();

        annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);
        stamper.addAnnotation(annotation, 1);

        stamper.close();
        reader.close();
    }
}
 
Example #3
Source File: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example #4
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * 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();
}
 
Example #5
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #7
Source File: ComplexSignatureFields.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: UpdateMetaData.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
}
 
Example #9
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #12
Source File: ComplexSignatureFields.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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);
}
 
Example #13
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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-signedNaive.pdf";//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, "53m-signedNaive.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(56, 648, 124, 780), 1, "sig2");
    // 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);
}
 
Example #15
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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);
}
 
Example #16
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #17
Source File: PDFUtil.java    From pdf-bookmark with MIT License 6 votes vote down vote up
private static void addOutlines(List<HashMap<String, Object>> outlines, String srcFile, String destFile) {
    try {
        class MyPdfReader extends PdfReader {
            public MyPdfReader(String fileName) throws IOException {
                super(fileName);
                unethicalreading = true;
                encrypted = false;
            }
        }
        PdfReader reader = new MyPdfReader(srcFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
        stamper.setOutlines(outlines);
        stamper.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: RemoveSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #20
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #21
Source File: DecryptUserOnly.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #22
Source File: RedactText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #23
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
    }
}
 
Example #24
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #25
Source File: CreateEllipse.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #26
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
    }
}
 
Example #27
Source File: EditPageContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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();
    }
}
 
Example #28
Source File: HideContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #29
Source File: HideContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example #30
Source File: SwitchPageCanvas.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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();
    }
}