List of usage examples for org.apache.pdfbox.pdmodel PDDocument isEncrypted
public boolean isEncrypted()
From source file:no.digipost.print.validate.PdfValidator.java
License:Apache License
/** * Leser hele dokumentet inn i minnet/*from w w w.j a v a2s . c om*/ */ private List<PdfValidationError> validerDokumentForPrint(final PDDocument pdDoc, final PdfValidationSettings innstillinger) throws IOException { List<PdfValidationError> errors = new ArrayList<>(); if (pdDoc.isEncrypted()) { return failValidationIfEncrypted(errors); } if (innstillinger.validerSideantall) { validerSideantall(pdDoc.getNumberOfPages(), errors); } if (innstillinger.validerPDFversjon) { validerPdfVersjon(pdDoc.getDocument().getVersion(), errors); } boolean dokumentHarUgyldigeDimensjoner = false; for (PDPage page : getAllPagesFrom(pdDoc)) { if (harUgyldigeDimensjoner(page)) { dokumentHarUgyldigeDimensjoner = true; break; } } leggTilValideringsfeil(dokumentHarUgyldigeDimensjoner, UNSUPPORTED_DIMENSIONS, errors); boolean harTekstIStrekkodeomraade = false; boolean dokumentHarSiderHvisMarginIkkeLarSegVerifisereForPrint = false; if (innstillinger.validerVenstremarg) { for (PDPage page : getAllPagesFrom(pdDoc)) { try { if (harTekstIStrekkodeomraade(page)) { harTekstIStrekkodeomraade = true; break; } } catch (NullPointerException npe) { dokumentHarSiderHvisMarginIkkeLarSegVerifisereForPrint = true; LOG.info("Klarte ikke verifiserere margen p en side"); } } } leggTilValideringsfeil(dokumentHarSiderHvisMarginIkkeLarSegVerifisereForPrint, UNABLE_TO_VERIFY_SUITABLE_MARGIN_FOR_PRINT, errors); leggTilValideringsfeil(harTekstIStrekkodeomraade, INSUFFICIENT_MARGIN_FOR_PRINT, errors); if (innstillinger.validerFonter) { for (PDPage page : getAllPagesFrom(pdDoc)) { validerFonter(fontValidator.getPageFonts(page), errors); } } return errors; }
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 av a2 s .co 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.ala.harvester.ExtractPubfSciNamesAndImages.java
License:Apache License
/** * This will print the documents text in a certain area. * * @param args The command line arguments. * * @throws Exception If there is an error parsing the document. */// ww w .j a v a2 s . com public static void main(String[] args) throws Exception { if (args.length != 1) { usage(); } else { PDDocument document = null; try { document = PDDocument.load(args[0]); if (document.isEncrypted()) { try { document.decrypt(""); } catch (InvalidPasswordException e) { System.err.println("Error: Document is encrypted with a password."); System.exit(1); } } extractSciNameAndImages(document); } finally { if (document != null) { document.close(); } } } }
From source file:org.apache.camel.component.fop.FopEndpointTest.java
License:Apache License
@Test public void encryptPdfWithUserPassword() throws Exception { Endpoint endpoint = context().getEndpoint("fop:application/pdf"); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); exchange.getIn().setHeader("CamelFop.Encrypt.userPassword", "secret"); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange);//from w w w . j a v a 2s . com PDDocument document = getDocumentFrom(exchange); assertTrue(document.isEncrypted()); }
From source file:org.apache.camel.component.fop.FopHelper.java
License:Apache License
public static void decryptPDFN(PDDocument document, String password) throws IOException, CryptographyException, BadSecurityHandlerException { if (document.isEncrypted()) { DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(password); document.openProtection(decryptionMaterial); } else {/*from www. java 2s .c om*/ throw new RuntimeException("Document not encrypted"); } }
From source file:org.apache.camel.component.pdf.PdfCreationTest.java
License:Apache License
@Test public void testPdfCreationWithEncryption() throws Exception { final String ownerPass = "ownerPass"; final String userPass = "userPass"; final String expectedText = "expectedText"; AccessPermission accessPermission = new AccessPermission(); accessPermission.setCanPrint(false); StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass, accessPermission);/*from ww w .java 2 s. c o m*/ protectionPolicy.setEncryptionKeyLength(128); template.sendBodyAndHeader("direct:start", expectedText, PdfHeaderConstants.PROTECTION_POLICY_HEADER_NAME, protectionPolicy); 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())); assertTrue("Expected encrypted document", doc.isEncrypted()); doc.decrypt(userPass); assertFalse("Printing should not be permitted", doc.getCurrentAccessPermission().canPrint()); PDFTextStripper pdfTextStripper = new PDFTextStripper(); String text = pdfTextStripper.getText(doc); assertEquals(1, doc.getNumberOfPages()); assertThat(text, containsString(expectedText)); } catch (Exception e) { throw new RuntimeException(e); } return true; } }); resultEndpoint.assertIsSatisfied(); }
From source file:org.apache.camel.component.pdf.PdfProducer.java
License:Apache License
private Object doAppend(Exchange exchange) throws IOException, BadSecurityHandlerException, CryptographyException, InvalidPasswordException, COSVisitorException { LOG.debug("Got {} operation, going to append text to provided pdf.", pdfConfiguration.getOperation()); String body = exchange.getIn().getBody(String.class); PDDocument document = exchange.getIn().getHeader(PDF_DOCUMENT_HEADER_NAME, PDDocument.class); if (document == null) { throw new IllegalArgumentException( String.format("%s header is expected for append operation", PDF_DOCUMENT_HEADER_NAME)); }/*ww w .j a v a 2 s.c o m*/ if (document.isEncrypted()) { DecryptionMaterial decryptionMaterial = exchange.getIn().getHeader(DECRYPTION_MATERIAL_HEADER_NAME, DecryptionMaterial.class); if (decryptionMaterial == null) { throw new IllegalArgumentException( String.format("%s header is expected for %s operation " + "on encrypted document", DECRYPTION_MATERIAL_HEADER_NAME, pdfConfiguration.getOperation())); } document.openProtection(decryptionMaterial); document.setAllSecurityToBeRemoved(true); } ProtectionPolicy protectionPolicy = exchange.getIn().getHeader(PROTECTION_POLICY_HEADER_NAME, ProtectionPolicy.class); appendToPdfDocument(body, document, protectionPolicy); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.save(byteArrayOutputStream); return byteArrayOutputStream; }
From source file:org.apache.camel.component.pdf.PdfProducer.java
License:Apache License
private String doExtractText(Exchange exchange) throws IOException, CryptographyException, InvalidPasswordException, BadSecurityHandlerException { LOG.debug("Got {} operation, going to extract text from provided pdf.", pdfConfiguration.getOperation()); PDDocument document = exchange.getIn().getBody(PDDocument.class); if (document.isEncrypted()) { DecryptionMaterial decryptionMaterial = exchange.getIn().getHeader(DECRYPTION_MATERIAL_HEADER_NAME, DecryptionMaterial.class); if (decryptionMaterial == null) { throw new IllegalArgumentException( String.format("%s header is expected for %s operation " + "on encrypted document", DECRYPTION_MATERIAL_HEADER_NAME, pdfConfiguration.getOperation())); }// ww w.java 2 s .com document.openProtection(decryptionMaterial); } PDFTextStripper pdfTextStripper = new PDFTextStripper(); return pdfTextStripper.getText(document); }
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);// w ww .j a v a2 s . c om 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.apache.camel.FopEndpointTest.java
License:Apache License
@Test public void encryptPDFWithUserPassword() throws Exception { Endpoint endpoint = context().getEndpoint("fop:application/pdf"); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); exchange.getIn().setHeader("CamelFop.encrypt.userPassword", "secret"); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange);//from w w w . ja v a 2s. c o m PDDocument document = getDocumentFrom(exchange); assertTrue(document.isEncrypted()); }