Search in sources :

Example 1 with PDFRenderer

use of com.tom_roush.pdfbox.rendering.PDFRenderer in project PdfBox-Android by TomRoush.

the class TestSymmetricKeyEncryption method checkPerms.

private void checkPerms(byte[] inputFileAsByteArray, String password, AccessPermission expectedPermissions) throws IOException {
    PDDocument doc = PDDocument.load(inputFileAsByteArray, password);
    AccessPermission currentAccessPermission = doc.getCurrentAccessPermission();
    // check permissions
    assertEquals(expectedPermissions.isOwnerPermission(), currentAccessPermission.isOwnerPermission());
    if (!expectedPermissions.isOwnerPermission()) {
        assertEquals(true, currentAccessPermission.isReadOnly());
    }
    assertEquals(expectedPermissions.canAssembleDocument(), currentAccessPermission.canAssembleDocument());
    assertEquals(expectedPermissions.canExtractContent(), currentAccessPermission.canExtractContent());
    assertEquals(expectedPermissions.canExtractForAccessibility(), currentAccessPermission.canExtractForAccessibility());
    assertEquals(expectedPermissions.canFillInForm(), currentAccessPermission.canFillInForm());
    assertEquals(expectedPermissions.canModify(), currentAccessPermission.canModify());
    assertEquals(expectedPermissions.canModifyAnnotations(), currentAccessPermission.canModifyAnnotations());
    assertEquals(expectedPermissions.canPrint(), currentAccessPermission.canPrint());
    assertEquals(expectedPermissions.canPrintDegraded(), currentAccessPermission.canPrintDegraded());
    new PDFRenderer(doc).renderImage(0);
    doc.close();
}
Also used : PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) AccessPermission(com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission) PDFRenderer(com.tom_roush.pdfbox.rendering.PDFRenderer)

Example 2 with PDFRenderer

use of com.tom_roush.pdfbox.rendering.PDFRenderer in project PdfBox-Android by TomRoush.

the class TestPDFParserInstrumentation method testPDFBox3950.

/**
 * PDFBOX-3950: test parsing and rendering of truncated file with missing pages.
 *
 * @throws IOException
 */
@Test
public void testPDFBox3950() throws IOException {
    File TARGETPDFDIR = new File(testContext.getCacheDir(), "pdfs");
    TARGETPDFDIR.mkdirs();
    File pdfFile = TestResourceGenerator.downloadTestResource(TARGETPDFDIR, "PDFBOX-3950-23EGDHXSBBYQLKYOKGZUOVYVNE675PRD.pdf", "https://issues.apache.org/jira/secure/attachment/12890042/23EGDHXSBBYQLKYOKGZUOVYVNE675PRD.pdf");
    assumeTrue(pdfFile.exists());
    PDDocument doc = PDDocument.load(pdfFile);
    assertEquals(4, doc.getNumberOfPages());
    PDFRenderer renderer = new PDFRenderer(doc);
    for (int i = 0; i < doc.getNumberOfPages(); ++i) {
        try {
            renderer.renderImage(i);
        } catch (IOException ex) {
            if (i == 3 && ex.getMessage().equals("Missing descendant font array")) {
                continue;
            }
            throw ex;
        }
    }
    doc.close();
}
Also used : PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) IOException(java.io.IOException) File(java.io.File) PDFRenderer(com.tom_roush.pdfbox.rendering.PDFRenderer) Test(org.junit.Test)

Example 3 with PDFRenderer

use of com.tom_roush.pdfbox.rendering.PDFRenderer in project PdfBox-Android by TomRoush.

the class PDFontTest method testPDFBox3826checkFonts.

private void testPDFBox3826checkFonts(byte[] byteArray, File fontFile) throws IOException {
    PDDocument doc = PDDocument.load(byteArray);
    PDPage page2 = doc.getPage(0);
    // F1 = type0 subset
    PDType0Font fontF1 = (PDType0Font) page2.getResources().getFont(COSName.getPDFName("F1"));
    Assert.assertTrue(fontF1.getName().contains("+"));
    Assert.assertTrue(fontFile.length() > fontF1.getFontDescriptor().getFontFile2().toByteArray().length);
    // F2 = type0 full embed
    PDType0Font fontF2 = (PDType0Font) page2.getResources().getFont(COSName.getPDFName("F2"));
    Assert.assertFalse(fontF2.getName().contains("+"));
    Assert.assertEquals(fontFile.length(), fontF2.getFontDescriptor().getFontFile2().toByteArray().length);
    // F3 = tt full embed
    PDTrueTypeFont fontF3 = (PDTrueTypeFont) page2.getResources().getFont(COSName.getPDFName("F3"));
    Assert.assertFalse(fontF2.getName().contains("+"));
    Assert.assertEquals(fontFile.length(), fontF3.getFontDescriptor().getFontFile2().toByteArray().length);
    new PDFRenderer(doc).renderImage(0);
    PDFTextStripper stripper = new PDFTextStripper();
    stripper.setLineSeparator("\n");
    String text = stripper.getText(doc);
    Assert.assertEquals("testMultipleFontFileReuse1\ntestMultipleFontFileReuse2\ntestMultipleFontFileReuse3", text.trim());
    doc.close();
}
Also used : PDPage(com.tom_roush.pdfbox.pdmodel.PDPage) PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) PDFRenderer(com.tom_roush.pdfbox.rendering.PDFRenderer) PDFTextStripper(com.tom_roush.pdfbox.text.PDFTextStripper)

Example 4 with PDFRenderer

use of com.tom_roush.pdfbox.rendering.PDFRenderer in project PdfBox-Android by TomRoush.

the class PDInlineImageTest method testInlineImage.

/**
 * Tests PDInlineImage#PDInlineImage(COSDictionary parameters, byte[] data,
 * Map<String, PDColorSpace> colorSpaces)
 */
@Test
public void testInlineImage() throws IOException {
    COSDictionary dict = new COSDictionary();
    dict.setBoolean(COSName.IM, true);
    int width = 31;
    int height = 27;
    dict.setInt(COSName.W, width);
    dict.setInt(COSName.H, height);
    dict.setInt(COSName.BPC, 1);
    int rowbytes = width / 8;
    if (rowbytes * 8 < width) {
        // PDF spec:
        // If the number of data bits per row is not a multiple of 8,
        // the end of the row is padded with extra bits to fill out the last byte.
        ++rowbytes;
    }
    // draw a grid
    int datalen = rowbytes * height;
    byte[] data = new byte[datalen];
    for (int i = 0; i < datalen; ++i) {
        data[i] = (i / 4 % 2 == 0) ? (byte) Integer.parseInt("10101010", 2) : 0;
    }
    PDInlineImage inlineImage1 = new PDInlineImage(dict, data, null);
    assertTrue(inlineImage1.isStencil());
    assertEquals(width, inlineImage1.getWidth());
    assertEquals(height, inlineImage1.getHeight());
    assertEquals(1, inlineImage1.getBitsPerComponent());
    COSDictionary dict2 = new COSDictionary();
    dict2.addAll(dict);
    // use decode array to revert in image2
    COSArray decodeArray = new COSArray();
    decodeArray.add(COSInteger.ONE);
    decodeArray.add(COSInteger.ZERO);
    dict2.setItem(COSName.DECODE, decodeArray);
    PDInlineImage inlineImage2 = new PDInlineImage(dict2, data, null);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    Bitmap stencilImage = inlineImage1.getStencilImage(paint);
    assertEquals(width, stencilImage.getWidth());
    assertEquals(height, stencilImage.getHeight());
    Bitmap stencilImage2 = inlineImage2.getStencilImage(paint);
    assertEquals(width, stencilImage2.getWidth());
    assertEquals(height, stencilImage2.getHeight());
    Bitmap image1 = inlineImage1.getImage();
    assertEquals(width, image1.getWidth());
    assertEquals(height, image1.getHeight());
    Bitmap image2 = inlineImage2.getImage();
    assertEquals(width, image2.getWidth());
    assertEquals(height, image2.getHeight());
    // write and read
    boolean writeOk = image1.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(testResultsDir.getPath() + "/inline-grid1.png"));
    assertTrue(writeOk);
    Bitmap bim1 = BitmapFactory.decodeFile(new File(testResultsDir + "/inline-grid1.png").getPath());
    assertNotNull(bim1);
    assertEquals(width, bim1.getWidth());
    assertEquals(height, bim1.getHeight());
    writeOk = image2.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(testResultsDir.getPath() + "/inline-grid2.png"));
    assertTrue(writeOk);
    Bitmap bim2 = BitmapFactory.decodeFile(new File(testResultsDir + "/inline-grid2.png").getPath());
    assertNotNull(bim2);
    assertEquals(width, bim2.getWidth());
    assertEquals(height, bim2.getHeight());
    // compare: pixels with even coordinates are white (FF), all others are black (0)
    int[] bimPixels = new int[width * height];
    bim1.getPixels(bimPixels, 0, width, 0, 0, width, height);
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            if (x % 2 == 0 && y % 2 == 0) {
                assertEquals(0xFFFFFF, bimPixels[x + width * y] & 0xFFFFFF);
            } else {
                assertEquals(0, bimPixels[x + width * y] & 0xFFFFFF);
            }
        }
    }
    // compare: pixels with odd coordinates are white (FF), all others are black (0)
    bim2.getPixels(bimPixels, 0, width, 0, 0, width, height);
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            if (x % 2 == 0 && y % 2 == 0) {
                assertEquals(0, bimPixels[x + width * y] & 0xFFFFFF);
            } else {
                assertEquals(0xFFFFFF, bimPixels[x + width * y] & 0xFFFFFF);
            }
        }
    }
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, false);
    contentStream.drawImage(inlineImage1, 150, 400);
    contentStream.drawImage(inlineImage1, 150, 500, inlineImage1.getWidth() * 2, inlineImage1.getHeight() * 2);
    contentStream.drawImage(inlineImage1, 150, 600, inlineImage1.getWidth() * 4, inlineImage1.getHeight() * 4);
    contentStream.drawImage(inlineImage2, 350, 400);
    contentStream.drawImage(inlineImage2, 350, 500, inlineImage2.getWidth() * 2, inlineImage2.getHeight() * 2);
    contentStream.drawImage(inlineImage2, 350, 600, inlineImage2.getWidth() * 4, inlineImage2.getHeight() * 4);
    contentStream.close();
    File pdfFile = new File(testResultsDir, "inline.pdf");
    document.save(pdfFile);
    document.close();
    document = PDDocument.load(pdfFile, (String) null);
    new PDFRenderer(document).renderImage(0);
    document.close();
}
Also used : COSDictionary(com.tom_roush.pdfbox.cos.COSDictionary) PDPage(com.tom_roush.pdfbox.pdmodel.PDPage) Paint(android.graphics.Paint) Paint(android.graphics.Paint) Bitmap(android.graphics.Bitmap) COSArray(com.tom_roush.pdfbox.cos.COSArray) FileOutputStream(java.io.FileOutputStream) PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) PDPageContentStream(com.tom_roush.pdfbox.pdmodel.PDPageContentStream) File(java.io.File) PDFRenderer(com.tom_roush.pdfbox.rendering.PDFRenderer) Test(org.junit.Test)

Example 5 with PDFRenderer

use of com.tom_roush.pdfbox.rendering.PDFRenderer in project PdfBox-Android by TomRoush.

the class TestOptionalContentGroupsInstrumentationTest method testOCGGenerationSameNameCanHaveSameVisibilityOff.

/**
 * PDFBOX-4496: setGroupEnabled(String, boolean) must catch all OCGs of a name even when several
 * names are identical.
 *
 * @throws IOException
 */
@Test
public void testOCGGenerationSameNameCanHaveSameVisibilityOff() throws IOException {
    Bitmap expectedImage;
    Bitmap actualImage;
    PDDocument doc = new PDDocument();
    try {
        // Create new page
        PDPage page = new PDPage();
        doc.addPage(page);
        PDResources resources = page.getResources();
        if (resources == null) {
            resources = new PDResources();
            page.setResources(resources);
        }
        // Prepare OCG functionality
        PDOptionalContentProperties ocprops = new PDOptionalContentProperties();
        doc.getDocumentCatalog().setOCProperties(ocprops);
        // ocprops.setBaseState(BaseState.ON); //ON=default
        // Create OCG for background
        PDOptionalContentGroup background = new PDOptionalContentGroup("background");
        ocprops.addGroup(background);
        assertTrue(ocprops.isGroupEnabled("background"));
        // Create OCG for enabled
        PDOptionalContentGroup enabled = new PDOptionalContentGroup("science");
        ocprops.addGroup(enabled);
        assertFalse(ocprops.setGroupEnabled("science", true));
        assertTrue(ocprops.isGroupEnabled("science"));
        // Create OCG for disabled1
        PDOptionalContentGroup disabled1 = new PDOptionalContentGroup("alternative");
        ocprops.addGroup(disabled1);
        // Create OCG for disabled2 with same name as disabled1
        PDOptionalContentGroup disabled2 = new PDOptionalContentGroup("alternative");
        ocprops.addGroup(disabled2);
        assertFalse(ocprops.setGroupEnabled("alternative", false));
        assertFalse(ocprops.isGroupEnabled("alternative"));
        // Setup page content stream and paint background/title
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
        PDFont font = PDType1Font.HELVETICA_BOLD;
        contentStream.beginMarkedContent(COSName.OC, background);
        contentStream.beginText();
        contentStream.setFont(font, 14);
        contentStream.newLineAtOffset(80, 700);
        contentStream.showText("PDF 1.5: Optional Content Groups");
        contentStream.endText();
        contentStream.endMarkedContent();
        font = PDType1Font.HELVETICA;
        // Paint enabled layer
        contentStream.beginMarkedContent(COSName.OC, enabled);
        contentStream.setNonStrokingColor(AWTColor.GREEN);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(80, 600);
        contentStream.showText("The earth is a sphere");
        contentStream.endText();
        contentStream.endMarkedContent();
        // Paint disabled layer1
        contentStream.beginMarkedContent(COSName.OC, disabled1);
        contentStream.setNonStrokingColor(AWTColor.RED);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(80, 500);
        contentStream.showText("Alternative 1: The earth is a flat circle");
        contentStream.endText();
        contentStream.endMarkedContent();
        // Paint disabled layer2
        contentStream.beginMarkedContent(COSName.OC, disabled2);
        contentStream.setNonStrokingColor(AWTColor.BLUE);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(80, 450);
        contentStream.showText("Alternative 2: The earth is a flat parallelogram");
        contentStream.endText();
        contentStream.endMarkedContent();
        contentStream.close();
        doc.getDocumentCatalog().setPageMode(PageMode.USE_OPTIONAL_CONTENT);
        File targetFile = new File(testResultsDir, "ocg-generation-same-name-off.pdf");
        doc.save(targetFile.getAbsolutePath());
        doc.close();
        // render PDF with science disabled and alternatives with same name enabled
        doc = PDDocument.load(new File(testResultsDir, "ocg-generation-same-name-off.pdf"));
        doc.getDocumentCatalog().getOCProperties().setGroupEnabled("background", false);
        doc.getDocumentCatalog().getOCProperties().setGroupEnabled("science", false);
        doc.getDocumentCatalog().getOCProperties().setGroupEnabled("alternative", true);
        actualImage = new PDFRenderer(doc).renderImage(0, 2);
        actualImage.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File(testResultsDir, "ocg-generation-same-name-off-actual.png")));
    } finally {
        doc.close();
    }
    // create PDF without OCGs to created expected rendering
    PDDocument doc2 = new PDDocument();
    try {
        // Create new page
        PDPage page = new PDPage();
        doc2.addPage(page);
        PDResources resources = page.getResources();
        if (resources == null) {
            resources = new PDResources();
            page.setResources(resources);
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc2, page, AppendMode.OVERWRITE, false);
        PDFont font = PDType1Font.HELVETICA;
        contentStream.setNonStrokingColor(AWTColor.RED);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(80, 500);
        contentStream.showText("Alternative 1: The earth is a flat circle");
        contentStream.endText();
        contentStream.setNonStrokingColor(AWTColor.BLUE);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(80, 450);
        contentStream.showText("Alternative 2: The earth is a flat parallelogram");
        contentStream.endText();
        contentStream.close();
        expectedImage = new PDFRenderer(doc2).renderImage(0, 2);
        actualImage.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File(testResultsDir, "ocg-generation-same-name-off-expected.png")));
    } finally {
        doc2.close();
    }
    // compare images
    int height = expectedImage.getHeight();
    int width = expectedImage.getWidth();
    int[] expectedImagePixels = new int[width * height];
    expectedImage.getPixels(expectedImagePixels, 0, width, 0, 0, width, height);
    int[] actualImagePixels = new int[width * height];
    actualImage.getPixels(actualImagePixels, 0, width, 0, 0, width, height);
    Assert.assertArrayEquals(expectedImagePixels, actualImagePixels);
}
Also used : PDFont(com.tom_roush.pdfbox.pdmodel.font.PDFont) PDPage(com.tom_roush.pdfbox.pdmodel.PDPage) PDResources(com.tom_roush.pdfbox.pdmodel.PDResources) Bitmap(android.graphics.Bitmap) PDDocument(com.tom_roush.pdfbox.pdmodel.PDDocument) FileOutputStream(java.io.FileOutputStream) PDPageContentStream(com.tom_roush.pdfbox.pdmodel.PDPageContentStream) File(java.io.File) PDFRenderer(com.tom_roush.pdfbox.rendering.PDFRenderer) Test(org.junit.Test)

Aggregations

PDFRenderer (com.tom_roush.pdfbox.rendering.PDFRenderer)12 PDDocument (com.tom_roush.pdfbox.pdmodel.PDDocument)11 File (java.io.File)10 Bitmap (android.graphics.Bitmap)6 PDPage (com.tom_roush.pdfbox.pdmodel.PDPage)5 FileOutputStream (java.io.FileOutputStream)5 Test (org.junit.Test)5 PDPageContentStream (com.tom_roush.pdfbox.pdmodel.PDPageContentStream)4 Paint (android.graphics.Paint)2 IOException (java.io.IOException)2 Canvas (android.graphics.Canvas)1 FlakyTest (androidx.test.filters.FlakyTest)1 COSArray (com.tom_roush.pdfbox.cos.COSArray)1 COSDictionary (com.tom_roush.pdfbox.cos.COSDictionary)1 PDResources (com.tom_roush.pdfbox.pdmodel.PDResources)1 PDEmbeddedFile (com.tom_roush.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile)1 AccessPermission (com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission)1 PDFont (com.tom_roush.pdfbox.pdmodel.font.PDFont)1 PDFTextStripper (com.tom_roush.pdfbox.text.PDFTextStripper)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1