Add BufferedImage to PDFBox 2.0 document
Asked Answered
M

1

10

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).

Magnetron answered 1/4, 2016 at 23:55 Comment(1)
Thank you for citing the original question; Migration to PDFBox 2.0.0: Working with Images may help; if you get something working, please add an answer there.Dardani
T
17

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)
Tough answered 3/4, 2016 at 16:23 Comment(1)
Thank you much! If anyone stumbles on this and is wondering about the PNG version: PDImageXObject pdImage= LosslessFactory.createFromImage(doc, bufferedImage);Magnetron

© 2022 - 2024 — McMap. All rights reserved.