Document Rendering

Convert a Document to Images

This small sample shows how to render (convert to images) a PDF document using PDFBox.

:::java
    String filename = "YOURFILENAMEHERE.pdf";

    // open the document
    PDDocument doc = PDDocument.loadNonSeq(new File(filename), null);

    boolean b;
    List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
    for (int p = 0; p < pages.size(); ++p)
    {
        // RGB image with 300 dpi
        BufferedImage bim = pages.get(p).convertToImage(BufferedImage.TYPE_INT_RGB, 300);
        
        // save as PNG with default metadata
        b = ImageIO.write(bim, "png", new File("rgbpage" + (p+1) + ".png"));
        if (!b)
        {
            // error handling
        }

        // B/W image with 300 dpi
        bim = pages.get(p).convertToImage(BufferedImage.TYPE_BYTE_BINARY, 300);
        
        // save as TIF with dpi in the metadata
        // PDFBox will choose the best compression for you - here: CCITT G4
        // you need to add jai_imageio.jar to your classpath for this to work
        b = ImageIOUtil.writeImage(bim, "bwpage-" + (p+1) + ".tif", 300);
        if (!b)
        {
            // error handling
        }
    }

    doc.close();