Search code examples
javajfreechartbufferedimagepdfbox

Add BufferedImage to PDFBox 2.0 document


First time poster, bear with me...

I have two questions. First, I want to know how to add an image to a PDFBox 2.0 document using a BufferedImage. The question has been asked here: Add BufferedImage to PDFBox document

PDFBox has since excluded the PDJpeg class and the xobject section as a whole.

Second, if someone has already asked this question and it has been answered, but the answer is deprecated; what's the best way to update/the best way to connect these two questions? (I don't have any points so I can't comment).


Solution

  • PDFBox has since excluded the PDJpeg class and the xobject section as a whole.

    There indeed has been a lot of refactoring (and re-refactoring and re-re-refactoring etc) during the development of version 2, and this refactoring often goes beyond mere package changes. And quite often it is not obvious where some functionality is now.

    But a basic functionality like adding a BufferedImage to a document can be counted on not being lost.

    There now is the JPEGFactory which provides methods to create image XObjects from a BufferedImage, in particular:

    /**
     * Creates a new JPEG Image XObject from a Buffered Image.
     * @param document the document where the image will be created
     * @param image the buffered image to embed
     * @return a new Image XObject
     * @throws IOException if the JPEG data cannot be written
     */
    public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
    
    /**
     * Creates a new JPEG Image XObject from a Buffered Image and a given quality.
     * The image will be created at 72 DPI.
     * @param document the document where the image will be created
     * @param image the buffered image to embed
     * @param quality the desired JPEG compression quality
     * @return a new Image XObject
     * @throws IOException if the JPEG data cannot be written
     */
    public static PDImageXObject createFromImage(PDDocument document, BufferedImage image, float quality)
    
    /**
     * Creates a new JPEG Image XObject from a Buffered Image, a given quality and DPI.
     * @param document the document where the image will be created
     * @param image the buffered image to embed
     * @param quality the desired JPEG compression quality
     * @param dpi the desired DPI (resolution) of the JPEG
     * @return a new Image XObject
     * @throws IOException if the JPEG data cannot be written
     */
    public static PDImageXObject createFromImage(PDDocument document, BufferedImage image, float quality, int dpi)