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

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

Introduction

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

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

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);/*from   w w w.  ja  va 2s.  c  om*/
    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.PdfCreationTest.java

License:Apache License

@Test
public void testPdfCreation() throws Exception {
    final String expectedText = "expectedText";
    template.sendBody("direct:start", expectedText);
    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override//from   w w  w  . j a  v  a  2 s.c  o  m
        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(1, doc.getNumberOfPages());
                assertThat(text, containsString(expectedText));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();
}

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);//w w w.  j  a v a 2s .  c  om
    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.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 w  w  w .  ja v a2 s . c  o  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.apache.camel.FopComponentTest.java

License:Apache License

@Ignore
@Test//  w  w w .jav  a  2  s.c o  m
public void createPDFUsingXMLDataAndXSLTTransformation() throws Exception {
    resultEndpoint.expectedMessageCount(1);
    FileInputStream inputStream = new FileInputStream("src/test/data/xml/data.xml");

    template.sendBody(inputStream);
    resultEndpoint.assertIsSatisfied();

    PDDocument document = PDDocument.load("target/data/result.pdf");
    String pdfText = FopHelper.extractTextFrom(document);
    assertTrue(pdfText.contains("Project")); //from xsl template
    assertTrue(pdfText.contains("John Doe")); //from data xml
}

From source file:org.apache.fop.render.pdf.DocumentRootModifierTestCase.java

License:Apache License

@Test
public void testStructTreeRootEntriesToCopy() throws IOException {
    Rectangle2D r = new Rectangle2D.Double();
    PDFDocument pdfDoc = new PDFDocument("");
    PDFPage page = new PDFPage(new PDFResources(pdfDoc), 0, r, r, r, r);
    page.setObjectNumber(1);//from   w ww. j  a  v  a2 s  . com
    page.setDocument(pdfDoc);
    pdfDoc.makeStructTreeRoot(null);
    PDFStructTreeRoot structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary rootBaseRoleMap = new PDFDictionary();
    PDFBoxAdapter adapter = new PDFBoxAdapter(page, new HashMap(), new HashMap<Integer, PDFArray>());
    DocumentRootModifier modifier = new DocumentRootModifier(adapter, pdfDoc);
    COSDictionary root = new COSDictionary();
    COSDictionary mapRole = new COSDictionary();
    mapRole.setName("Icon", "Figure");
    root.setItem(COSName.ROLE_MAP, mapRole);
    modifier.structTreeRootEntriesToCopy(root);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary baseRoot = (PDFDictionary) structTreeRoot.get("RoleMap");
    String test = baseRoot.get("Icon").toString();
    String expected = "/Figure";
    Assert.assertEquals(test, expected);

    PDFName para = new PDFName("P");
    rootBaseRoleMap.put("MyPara", para);
    structTreeRoot.put("RoleMap", rootBaseRoleMap);
    modifier.structTreeRootEntriesToCopy(root);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary baseRoot2 = (PDFDictionary) structTreeRoot.get("RoleMap");
    PDFName nameIcon = (PDFName) baseRoot2.get("Icon");
    PDFName myPara = (PDFName) baseRoot2.get("MyPara");
    test = nameIcon.getName();
    expected = "Figure";
    Assert.assertEquals(test, expected);
    test = myPara.getName();
    expected = "P";
    Assert.assertEquals(test, expected);

    PDDocument doc = PDDocument.load(new File(getClass().getResource(CLASSMAP).getFile()));
    COSDictionary temp = (COSDictionary) doc.getDocumentCatalog().getStructureTreeRoot().getCOSObject();
    PDFDictionary classMap = new PDFDictionary();
    PDFDictionary inner = new PDFDictionary();
    inner.put("StartIndent", 0);
    classMap.put("Normal2", inner);
    structTreeRoot.put("ClassMap", classMap);
    modifier.structTreeRootEntriesToCopy(temp);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary testDict = (PDFDictionary) structTreeRoot.get("ClassMap");
    Assert.assertNotNull(testDict.get("Normal2"));
}

From source file:org.apache.fop.render.pdf.PageParentTreeFinderTestCase.java

License:Apache License

@Test
public void testGetPageParentTreeArray() throws IOException {
    File resource = new File(getClass().getResource(LINK).getFile());
    PDDocument doc = PDDocument.load(resource);
    PDPage srcPage = doc.getPage(0);/* w  ww . ja  v  a 2s.  c o  m*/
    PageParentTreeFinder finder = new PageParentTreeFinder(srcPage);
    COSArray markedContentParents = finder.getPageParentTreeArray(doc);
    Assert.assertEquals(markedContentParents.size(), 3);
    COSObject firstObj = (COSObject) markedContentParents.get(0);
    COSObject secObj = (COSObject) markedContentParents.get(1);
    COSArray firstKids = (COSArray) firstObj.getDictionaryObject(COSName.K);
    COSDictionary firstKid = (COSDictionary) firstKids.get(0);
    int test = firstKid.getInt("MCID");
    int expected = 0;
    Assert.assertEquals(test, expected);
    COSDictionary firstKidBrother = (COSDictionary) firstKids.get(2);
    test = firstKidBrother.getInt("MCID");
    expected = 2;
    Assert.assertEquals(test, expected);
    COSArray secKidsArray = (COSArray) secObj.getDictionaryObject(COSName.K);
    COSDictionary secondKid = (COSDictionary) secKidsArray.get(0);
    test = secondKid.getInt("MCID");
    expected = 1;
    Assert.assertEquals(test, expected);
}

From source file:org.apache.fop.render.pdf.PDFBoxAdapterTestCase.java

License:Apache License

private PDDocument getResource(String pdf) throws IOException {
    return PDDocument.load(new File(getClass().getResource(pdf).getFile()));
}

From source file:org.apache.fop.render.pdf.StructureTreeMergerTestCase.java

License:Apache License

@Test
public void testCopyStructure() throws IOException {
    setUp();//from   w  ww  . jav  a 2 s .co m
    PDDocument doc = PDDocument.load(new File(getClass().getResource(LINK).getFile()));
    PDPage srcPage = doc.getPage(0);
    PageParentTreeFinder finder = new PageParentTreeFinder(srcPage);
    COSArray markedContentParents = finder.getPageParentTreeArray(doc);
    PDFStructElem elem = new PDFStructElem();
    elem.setObjectNumber(2);
    adapter = new PDFBoxAdapter(pdfPage, new HashMap(), new HashMap<Integer, PDFArray>());
    adapter.setCurrentMCID(1);
    PDFLogicalStructureHandler handler = setUpPDFLogicalStructureHandler();
    StructureTreeMerger merger = new StructureTreeMerger(elem, handler, adapter, srcPage);
    merger.copyStructure(markedContentParents);
    PDFArray array = handler.getPageParentTree();
    checkMarkedContentsParentsForLinkTest(array);
    PDFStructElem first = (PDFStructElem) array.get(0);
    checkParentForLinkTest(first, 0);
}

From source file:org.apache.fop.render.pdf.StructureTreeMergerTestCase.java

License:Apache License

@Test
public void testNullEntriesInParentTree() throws IOException {
    setUp();//from w w w.j  av  a 2s  .  c  o m
    PDDocument doc = PDDocument.load(new File(getClass().getResource(LINK).getFile()));
    PDPage srcPage = doc.getPage(0);
    PageParentTreeFinder finder = new PageParentTreeFinder(srcPage);
    COSArray markedContentParents = finder.getPageParentTreeArray(doc);
    markedContentParents.add(0, null);
    PDFStructElem elem = new PDFStructElem();
    elem.setObjectNumber(2);
    adapter = new PDFBoxAdapter(pdfPage, new HashMap(), new HashMap<Integer, PDFArray>());
    PDFLogicalStructureHandler handler = setUpPDFLogicalStructureHandler();
    StructureTreeMerger merger = new StructureTreeMerger(elem, handler, adapter, srcPage);
    merger.copyStructure(markedContentParents);
    PDFArray array = handler.getPageParentTree();
    Assert.assertNull(array.get(0));
}