Package org.apache.pdfbox.pdmodel

Examples of org.apache.pdfbox.pdmodel.PDDocument


    }

    private void checkPerms(byte[] inputFileAsByteArray, String password, boolean nonSeq,
            AccessPermission expectedPermissions) throws IOException
    {
        PDDocument doc;
        if (nonSeq)
        {
            doc = PDDocument.loadNonSeq(
                    new ByteArrayInputStream(inputFileAsByteArray),
                    password);
        }
        else
        {
            doc = PDDocument.load(new ByteArrayInputStream(inputFileAsByteArray));
            Assert.assertTrue(doc.isEncrypted());
            DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(password);
            doc.openProtection(decryptionMaterial);
        }
        AccessPermission currentAccessPermission = doc.getCurrentAccessPermission();

        // check permissions
        assertEquals(expectedPermissions.isOwnerPermission(), currentAccessPermission.isOwnerPermission());
        assertEquals(expectedPermissions.isReadOnly(), 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();
    }
View Full Code Here


    private void testSymmEncrForKeySize(int keyLength,
            int sizePriorToEncr, byte[] inputFileAsByteArray,
            String userpassword, String ownerpassword,
            AccessPermission permission, boolean nonSeq) throws IOException
    {
        PDDocument document = PDDocument.load(new ByteArrayInputStream(inputFileAsByteArray));
        String prefix = "Simple-";
        int numSrcPages = document.getNumberOfPages();
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        ArrayList<BufferedImage> srcImgTab = new ArrayList<BufferedImage>();
        ArrayList<ByteArrayOutputStream> srcContentStreamTab = new ArrayList<ByteArrayOutputStream>();
        for (int i = 0; i < numSrcPages; ++i)
        {
            srcImgTab.add(pdfRenderer.renderImage(i));
            COSStream contentStream = document.getPage(i).getContentStream();
            InputStream unfilteredStream = contentStream.getUnfilteredStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(unfilteredStream, baos);
            unfilteredStream.close();
            srcContentStreamTab.add(baos);
        }

        PDDocument encryptedDoc = encrypt(keyLength, sizePriorToEncr, document,
                prefix, permission, nonSeq, userpassword, ownerpassword);

        Assert.assertEquals(numSrcPages, encryptedDoc.getNumberOfPages());
        pdfRenderer = new PDFRenderer(encryptedDoc);
        for (int i = 0; i < encryptedDoc.getNumberOfPages(); ++i)
        {
            // compare rendering
            BufferedImage bim = pdfRenderer.renderImage(i);
            ValidateXImage.checkIdent(bim, srcImgTab.get(i));

            // compare content streams
            COSStream contentStreamDecr = encryptedDoc.getPage(i).getContentStream();
            InputStream unfilteredStream = contentStreamDecr.getUnfilteredStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(unfilteredStream, baos);
            unfilteredStream.close();
            Assert.assertArrayEquals("content stream of page " + i + " not identical",
                    srcContentStreamTab.get(i).toByteArray(),
                    baos.toByteArray());
        }

        File pdfFile = new File(testResultsDir, prefix + keyLength + "-bit-decrypted.pdf");
        encryptedDoc.setAllSecurityToBeRemoved(true);
        encryptedDoc.save(pdfFile);
        encryptedDoc.close();
    }
View Full Code Here

        long sizeEncrypted = pdfFile.length();
        Assert.assertTrue(keyLength
                + "-bit encrypted pdf should not have same size as plain one",
                sizeEncrypted != sizePriorToEncr);

        PDDocument encryptedDoc;

        // test with owner password => full permissions
        if (nonSeq)
        {
            encryptedDoc = PDDocument.loadNonSeq(pdfFile, ownerpassword);
        }
        else
        {
            encryptedDoc = PDDocument.load(pdfFile);
            Assert.assertTrue(encryptedDoc.isEncrypted());
            DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(ownerpassword);
            encryptedDoc.openProtection(decryptionMaterial);
        }
        Assert.assertTrue(encryptedDoc.getCurrentAccessPermission().isOwnerPermission());
        encryptedDoc.close();

        // test with owner password => restricted permissions
        if (nonSeq)
        {
            encryptedDoc = PDDocument.loadNonSeq(pdfFile, userpassword);
        }
        else
        {
            encryptedDoc = PDDocument.load(pdfFile);
            Assert.assertTrue(encryptedDoc.isEncrypted());
            DecryptionMaterial decryptionMaterial = new StandardDecryptionMaterial(userpassword);
            encryptedDoc.openProtection(decryptionMaterial);
        }
        Assert.assertFalse(encryptedDoc.getCurrentAccessPermission().isOwnerPermission());

        assertEquals(permission.getPermissionBytes(), encryptedDoc.getCurrentAccessPermission().getPermissionBytes());

        return encryptedDoc;
    }
View Full Code Here

        {
            usage();
        }
        else
        {
            PDDocument document = null;
            try
            {
                document = PDDocument.load( args[0]);
                if( document.isEncrypted() )
                {
                    try
                    {
                        StandardDecryptionMaterial sdm = new StandardDecryptionMaterial("");
                        document.openProtection(sdm);
                    }
                    catch( InvalidPasswordException e )
                    {
                        System.err.println( "Error: Document is encrypted with a password." );
                        System.exit( 1 );
                    }
                }
                PrintDocumentMetaData meta = new PrintDocumentMetaData();
                meta.printMetadata( document );
            }
            finally
            {
                if( document != null )
                {
                    document.close();
                }
            }
        }
    }
View Full Code Here

                if (prefix == null && pdfFile.length() > 4)
                {
                    prefix = pdfFile.substring(0, pdfFile.length() - 4);
                }

                PDDocument document = null;

                try
                {
                    document = PDDocument.load(pdfFile);

                    if (document.isEncrypted())
                    {
                        StandardDecryptionMaterial sdm = new StandardDecryptionMaterial(password);
                        document.openProtection(sdm);
                    }
                    for (PDPage page : document.getPages())
                    {
                        PDResources resources = page.getResources();
                        // extract all fonts which are part of the page resources
                        processResources(resources, prefix, addKey);
                    }
                }
                finally
                {
                    if (document != null)
                    {
                        document.close();
                    }
                }
            }
        }
    }
View Full Code Here

     *
     * @throws java.io.IOException
     */
    public void testCreateLosslessFromImageRGB() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));

        PDImageXObject ximage1 = LosslessFactory.createFromImage(document, image);
        validate(ximage1, 8, image.getWidth(), image.getHeight(), "png", PDDeviceRGB.INSTANCE.getName());
        checkIdent(image, ximage1.getImage());

        // Create a grayscale image
        BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = grayImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        PDImageXObject ximage2 = LosslessFactory.createFromImage(document, grayImage);
        validate(ximage2, 8, grayImage.getWidth(), grayImage.getHeight(), "png", PDDeviceGray.INSTANCE.getName());
        checkIdent(grayImage, ximage2.getImage());

        // Create a bitonal image
        BufferedImage bitonalImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);

        // avoid multiple of 8 to test padding
        assertFalse(bitonalImage.getWidth() % 8 == 0);
       
        g = bitonalImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        PDImageXObject ximage3 = LosslessFactory.createFromImage(document, bitonalImage);
        validate(ximage3, 1, bitonalImage.getWidth(), bitonalImage.getHeight(), "png", PDDeviceGray.INSTANCE.getName());
        checkIdent(bitonalImage, ximage3.getImage());

        // This part isn't really needed because this test doesn't break
        // if the mask has the wrong colorspace (PDFBOX-2057), but it is still useful
        // if something goes wrong in the future and we want to have a PDF to open.
        PDPage page = new PDPage();
        document.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, false);
        contentStream.drawXObject(ximage1, 200, 300, ximage1.getWidth() / 2, ximage1.getHeight() / 2);
        contentStream.drawXObject(ximage2, 200, 450, ximage2.getWidth() / 2, ximage2.getHeight() / 2);
        contentStream.drawXObject(ximage3, 200, 600, ximage3.getWidth() / 2, ximage3.getHeight() / 2);
        contentStream.close();
       
        File pdfFile = new File(testResultsDir, "misc.pdf");
        document.save(pdfFile);
        document.close();
       
        document = PDDocument.loadNonSeq(pdfFile, null);
        new PDFRenderer(document).renderImage(0);
        document.close();
    }
View Full Code Here

     *
     * @throws java.io.IOException
     */
    public void testCreateLosslessFromImageINT_ARGB() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));

        // create an ARGB image
        int w = image.getWidth();
        int h = image.getHeight();
View Full Code Here

     * @param outDir Name of the output directory
     * @throws IOException when there is an exception
     */
    private void doTestFile(File file, String outDir) throws IOException
    {
        PDDocument document = null;
        String imageType = "png";
        LOG.info("Preparing to convert " + file.getName());
        try
        {
            float dpi = 36; // low DPI so that rendering is FAST
            document = PDDocument.load(file);

            // Save image resources of first page
            checkSaveResources(document.getPage(0).getResources());

            // testing PNG
            writeImage(document, imageType, outDir + file.getName() + "-", ImageType.RGB, dpi);
            checkResolution(outDir + file.getName() + "-1." + imageType, (int) dpi);

            // testing JPG/JPEG
            imageType = "jpg";
            writeImage(document, imageType, outDir + file.getName() + "-", ImageType.RGB, dpi);
            checkResolution(outDir + file.getName() + "-1." + imageType, (int) dpi);

            // testing BMP
            imageType = "bmp";
            writeImage(document, imageType, outDir + file.getName() + "-", ImageType.RGB, dpi);
            checkResolution(outDir + file.getName() + "-1." + imageType, (int) dpi);

            // testing GIF
            imageType = "gif";
            writeImage(document, imageType, outDir + file.getName() + "-", ImageType.RGB, dpi);
            // no META data posible for GIF, thus no test

            // testing WBMP
            imageType = "wbmp";
            writeImage(document, imageType, outDir + file.getName() + "-", ImageType.BINARY, dpi);
            // no META data posible for WBMP, thus no test

            // testing TIFF
            imageType = "tif";
            writeImage(document, imageType, outDir + file.getName() + "-bw-", ImageType.BINARY, dpi);
            checkResolution(outDir + file.getName() + "-bw-1." + imageType, (int) dpi);
            checkTiffCompression(outDir + file.getName() + "-bw-1." + imageType, "CCITT T.6");
            writeImage(document, imageType, outDir + file.getName() + "-co-", ImageType.RGB, dpi);
            checkResolution(outDir + file.getName() + "-co-1." + imageType, (int) dpi);
            checkTiffCompression(outDir + file.getName() + "-co-1." + imageType, "LZW");
        }
        finally
        {
            if (document != null)
            {
                document.close();
            }
        }
    }
View Full Code Here

     *
     * @throws java.io.IOException
     */
    public void testCreateLosslessFromImage4BYTE_ABGR() throws IOException
    {
        PDDocument document = new PDDocument();
        BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));

        // create an ARGB image
        int w = image.getWidth();
        int h = image.getHeight();
View Full Code Here

        }
    }

    private void doBitmaskTransparencyTest(int imageType, String pdfFilename) throws IOException
    {
        PDDocument document = new PDDocument();

        int width = 257;
        int height = 256;

        // create an ARGB image
        BufferedImage argbImage = new BufferedImage(width, height, imageType);

        // from there, create an image with Transparency.BITMASK
        Graphics2D g = argbImage.createGraphics();
        GraphicsConfiguration gc = g.getDeviceConfiguration();
        argbImage = gc.createCompatibleImage(width, height, Transparency.BITMASK);
        g.dispose();
        // create a red rectangle
        g = argbImage.createGraphics();
        g.setColor(Color.red);
        g.fillRect(0, 0, width, height);
        g.dispose();

        Random random = new Random();
        random.setSeed(12345);
        // create a transparency cross: only pixels in the
        // interval max/2 - max/8 ... max/2 + max/8 will be visible
        int startX = width / 2 - width / 8;
        int endX = width / 2 + width / 8;
        int startY = height / 2 - height / 8;
        int endY = height / 2 + height / 8;
        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                // create pseudorandom alpha values, but those within the cross
                // must be >= 128 and those outside must be < 128
                int alpha;
                if ((x >= startX && x <= endX) || y >= startY && y <= endY)
                {
                    alpha = 128 + (int) (random.nextFloat() * 127);
                    assertTrue(alpha >= 128);
                    argbImage.setRGB(x, y, (argbImage.getRGB(x, y) & 0xFFFFFF) | (alpha << 24));
                    assertEquals(255, argbImage.getRGB(x, y) >>> 24);
                }
                else
                {
                    alpha = (int) (random.nextFloat() * 127);
                    assertTrue(alpha < 128);
                    argbImage.setRGB(x, y, (argbImage.getRGB(x, y) & 0xFFFFFF) | (alpha << 24));
                    assertEquals(0, argbImage.getRGB(x, y) >>> 24);
                }
            }
        }

        PDImageXObject ximage = LosslessFactory.createFromImage(document, argbImage);
        validate(ximage, 8, width, height, "png", PDDeviceRGB.INSTANCE.getName());
        checkIdent(argbImage, ximage.getImage());
        checkIdentRGB(argbImage, ximage.getOpaqueImage());

        assertNotNull(ximage.getSoftMask());
        validate(ximage.getSoftMask(), 1, width, height, "png", PDDeviceGray.INSTANCE.getName());
        assertEquals(2, colorCount(ximage.getSoftMask().getImage()));

        // check whether the mask is a b/w cross
        BufferedImage maskImage = ximage.getSoftMask().getImage();
       
        // avoid multiple of 8 to test padding
        assertFalse(maskImage.getWidth() % 8 == 0);
       
        assertEquals(Transparency.OPAQUE, maskImage.getTransparency());
        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                if ((x >= startX && x <= endX) || y >= startY && y <= endY)
                {
                    assertEquals(0xFFFFFF, maskImage.getRGB(x, y) & 0xFFFFFF);
                }
                else
                {
                    assertEquals(0, maskImage.getRGB(x, y) & 0xFFFFFF);
                }
            }
        }

        // This part isn't really needed because this test doesn't break
        // if the mask has the wrong colorspace (PDFBOX-2057), but it is still useful
        // if something goes wrong in the future and we want to have a PDF to open.
        // Create a rectangle
        BufferedImage rectImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g = rectImage.createGraphics();
        g.setColor(Color.blue);
        g.fillRect(0, 0, width, height);
        g.dispose();
        PDImageXObject ximage2 = LosslessFactory.createFromImage(document, rectImage);

        PDPage page = new PDPage();
        document.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, false);
        contentStream.drawXObject(ximage2, 150, 300, ximage2.getWidth(), ximage2.getHeight());
        contentStream.drawXObject(ximage, 150, 300, ximage.getWidth(), ximage.getHeight());
        contentStream.close();
        File pdfFile = new File(testResultsDir, pdfFilename);
        document.save(pdfFile);
        document.close();
        document = PDDocument.loadNonSeq(pdfFile, null);
        new PDFRenderer(document).renderImage(0);
        document.close();
    }
View Full Code Here

TOP

Related Classes of org.apache.pdfbox.pdmodel.PDDocument

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.