Example usage for org.apache.pdfbox.pdmodel PDDocument protect

List of usage examples for org.apache.pdfbox.pdmodel PDDocument protect

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument protect.

Prototype

public void protect(ProtectionPolicy policy) throws IOException 

Source Link

Document

Protects the document with a protection policy.

Usage

From source file:com.ackpdfbox.app.Encrypt.java

License:Apache License

private void encrypt(String[] args) throws IOException, CertificateException {
    if (args.length < 1) {
        usage();//from  w  ww. j  av  a2  s  . c  o  m
    } else {
        AccessPermission ap = new AccessPermission();

        String infile = null;
        String outfile = null;
        String certFile = null;
        String userPassword = "";
        String ownerPassword = "";

        int keyLength = 40;

        PDDocument document = null;

        try {
            for (int i = 0; i < args.length; i++) {
                String key = args[i];
                if (key.equals("-O")) {
                    ownerPassword = args[++i];
                } else if (key.equals("-U")) {
                    userPassword = args[++i];
                } else if (key.equals("-canAssemble")) {
                    ap.setCanAssembleDocument(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canExtractContent")) {
                    ap.setCanExtractContent(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canExtractForAccessibility")) {
                    ap.setCanExtractForAccessibility(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canFillInForm")) {
                    ap.setCanFillInForm(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canModify")) {
                    ap.setCanModify(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canModifyAnnotations")) {
                    ap.setCanModifyAnnotations(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canPrint")) {
                    ap.setCanPrint(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canPrintDegraded")) {
                    ap.setCanPrintDegraded(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-certFile")) {
                    certFile = args[++i];
                } else if (key.equals("-keyLength")) {
                    try {
                        keyLength = Integer.parseInt(args[++i]);
                    } catch (NumberFormatException e) {
                        throw new NumberFormatException(
                                "Error: -keyLength is not an integer '" + args[i] + "'");
                    }
                } else if (infile == null) {
                    infile = key;
                } else if (outfile == null) {
                    outfile = key;
                } else {
                    usage();
                }
            }
            if (infile == null) {
                usage();
            }
            if (outfile == null) {
                outfile = infile;
            }
            document = PDDocument.load(new File(infile));

            if (!document.isEncrypted()) {
                if (certFile != null) {
                    PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy();
                    PublicKeyRecipient recip = new PublicKeyRecipient();
                    recip.setPermission(ap);

                    CertificateFactory cf = CertificateFactory.getInstance("X.509");

                    InputStream inStream = null;
                    try {
                        inStream = new FileInputStream(certFile);
                        X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream);
                        recip.setX509(certificate);
                    } finally {
                        if (inStream != null) {
                            inStream.close();
                        }
                    }

                    ppp.addRecipient(recip);

                    ppp.setEncryptionKeyLength(keyLength);

                    document.protect(ppp);
                } else {
                    StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword,
                            ap);
                    spp.setEncryptionKeyLength(keyLength);
                    document.protect(spp);
                }
                document.save(outfile);
            } else {
                System.err.println("Error: Document is already encrypted.");
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java

License:Open Source License

private void encryptPDF(InputStream inputStream, OutputStream outputStream, String password) throws Exception {
    PDDocument document = null;

    try {//from  w  ww .  ja v a  2s .c o  m
        document = PDDocument.load(inputStream);

        AccessPermission accessPermission = new AccessPermission();
        accessPermission.setCanAssembleDocument(false);
        accessPermission.setCanExtractContent(true);
        accessPermission.setCanExtractForAccessibility(false);
        accessPermission.setCanFillInForm(false);
        accessPermission.setCanModify(false);
        accessPermission.setCanModifyAnnotations(false);
        accessPermission.setCanPrint(true);
        accessPermission.setCanPrintDegraded(true);

        String ownerPassword = System.currentTimeMillis() + "+" + Runtime.getRuntime().freeMemory() + "+"
                + (ownerPasswordSeq++);
        StandardProtectionPolicy policy = new StandardProtectionPolicy(ownerPassword, password,
                accessPermission);
        policy.setEncryptionKeyLength(128);
        document.protect(policy);

        document.save(outputStream);
    } catch (Exception e) {
        throw e;
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:noprint.NoPrint.java

/**
 * @param args the command line arguments
 * @throws IOException in case input file is can't be read or output written
 * @throws org.apache.pdfbox.pdmodel.encryption.BadSecurityHandlerException
 * @throws org.apache.pdfbox.exceptions.COSVisitorException
 *//*from   w  ww  .  j  a v  a 2s. c o m*/
public static void main(String[] args) throws IOException, BadSecurityHandlerException, COSVisitorException {
    String infile = "input.pdf";
    String outfile = "output.pdf";

    String ownerPass = "";
    String userPass = "";
    /**
     * TODO: read up what the actual difference is between
     * userpassword and ownerpassword.
     */
    int keylength = 40;

    AccessPermission ap = new AccessPermission();
    PDDocument document = null;

    ap.setCanAssembleDocument(true);
    ap.setCanExtractContent(true);
    ap.setCanExtractForAccessibility(true);
    ap.setCanFillInForm(true);
    ap.setCanModify(true);
    ap.setCanModifyAnnotations(true);
    ap.setCanPrintDegraded(true);

    ap.setCanPrint(false);
    // YOU CAN'T PRINT
    // at least not when your PDFreader adheres to DRM (some don't)
    // also this is trivial to remove

    document = PDDocument.load(infile);

    if (!document.isEncrypted()) {
        StandardProtectionPolicy spp;
        spp = new StandardProtectionPolicy(ownerPass, userPass, ap);
        spp.setEncryptionKeyLength(keylength);
        document.protect(spp);
        document.save(outfile);
    }

    if (document != null) {
        document.close();
    }
}

From source file:org.apache.camel.component.pdf.PdfAppendTest.java

License:Apache License

@Test
public void testAppendEncrypted() throws Exception {
    final String originalText = "Test";
    final String textToAppend = "Append";
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/* ww w.  j  av a 2s .co  m*/
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(originalText);
    contentStream.endText();
    contentStream.close();

    final String ownerPass = "ownerPass";
    final String userPass = "userPass";
    AccessPermission accessPermission = new AccessPermission();
    accessPermission.setCanExtractContent(false);
    StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass,
            accessPermission);
    protectionPolicy.setEncryptionKeyLength(128);

    document.protect(protectionPolicy);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    document.save(output);

    // Encryption happens after saving.
    PDDocument encryptedDocument = PDDocument.load(new ByteArrayInputStream(output.toByteArray()));

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(PdfHeaderConstants.PDF_DOCUMENT_HEADER_NAME, encryptedDocument);
    headers.put(PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass));

    template.sendBodyAndHeaders("direct:start", textToAppend, headers);

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(ByteArrayOutputStream.class));
            try {
                PDDocument doc = PDDocument
                        .load(new ByteArrayInputStream(((ByteArrayOutputStream) body).toByteArray()));
                PDFTextStripper pdfTextStripper = new PDFTextStripper();
                String text = pdfTextStripper.getText(doc);
                assertEquals(2, doc.getNumberOfPages());
                assertThat(text, containsString(originalText));
                assertThat(text, containsString(textToAppend));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();

}

From source file:org.apache.camel.component.pdf.PdfProducer.java

License:Apache License

private void appendToPdfDocument(String text, PDDocument document, ProtectionPolicy protectionPolicy)
        throws IOException, BadSecurityHandlerException {
    Collection<String> words = splitStrategy.split(text);
    Collection<String> lines = lineBuilderStrategy.buildLines(words);
    writeStrategy.write(lines, document);
    if (protectionPolicy != null) {
        document.protect(protectionPolicy);
    }//from  w  w  w  .jav  a2  s  .c  om
}

From source file:org.apache.camel.component.pdf.PdfTextExtractionTest.java

License:Apache License

@Test
public void testExtractTextFromEncrypted() throws Exception {
    final String ownerPass = "ownerPass";
    final String userPass = "userPass";
    AccessPermission accessPermission = new AccessPermission();
    accessPermission.setCanExtractContent(false);
    StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass,
            accessPermission);//from ww  w. j a v a2  s .co  m
    protectionPolicy.setEncryptionKeyLength(128);
    PDDocument document = new PDDocument();

    final String expectedText = "Test string";
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(expectedText);
    contentStream.endText();
    contentStream.close();

    document.protect(protectionPolicy);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    document.save(output);

    // Encryption happens after saving.
    PDDocument encryptedDocument = PDDocument.load(new ByteArrayInputStream(output.toByteArray()));

    template.sendBodyAndHeader("direct:start", encryptedDocument,
            PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass));

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(String.class));
            assertThat((String) body, containsString(expectedText));
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();
    document.isEncrypted();
}

From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java

License:Open Source License

@Override
public void protect(final String inputUri, final String outputUri, final String password)
        throws IOException, BadSecurityHandlerException, COSVisitorException {

    if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri)
            && StringUtils.isNotBlank(password)) {

        final PDDocument doc = PDDocument.load(inputUri);

        final StandardProtectionPolicy pp = new StandardProtectionPolicy(password, password,
                new AccessPermission());
        doc.protect(pp);

        doc.save(outputUri);// ww w .  java2s  .  c o  m

        doc.close();

    } else {
        throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
    }
}

From source file:org.pdfgal.pdfgal.pdfgal.impl.PDFGalImpl.java

License:Open Source License

@Override
public void unProtect(final String inputUri, final String outputUri, final String password)
        throws IOException, COSVisitorException, BadSecurityHandlerException, CryptographyException {

    if (StringUtils.isNotBlank(inputUri) && StringUtils.isNotBlank(outputUri)
            && StringUtils.isNotBlank(password)) {

        final PDDocument doc = PDDocument.load(inputUri);

        final DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(password);
        doc.openProtection(decryptionMaterial);

        final StandardProtectionPolicy pp = new StandardProtectionPolicy(null, null, new AccessPermission());
        doc.protect(pp);

        doc.save(outputUri);/* w  w  w.j  a  v  a  2s.co m*/

        doc.close();

    } else {
        throw new IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
    }
}