I'm trying to scaling an image with size = 2496 x 3512 into a PDF document. I'm using PDFBox to generate it but the scaled image ends up blurred.
Here are some snippets:
PDF Page size (A4) returned by page.findMediaBox().createDimension(): java.awt.Dimension[width=612,height=792]
Then I calculate the scaled dimension based on the Page size vs. Image size which returns: java.awt.Dimension[width=562,height=792] I use the code below in order to calculate the scaled dimension:
public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
}
And to actually perform the image scaling I'm using Image Scalr API:
BufferedImage newImg = Scalr.resize(img, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT,
scaledWidth, scaledHeight, Scalr.OP_ANTIALIAS);
My question is what am I doing wrong? A big image shouldn't be blurred when scaled to a smaller size. Is this something related to the PDF page resolution/size?
Thank you,
Gyo
Ok, I found a way to add images without losing the quality.
Actually to make the image not be blurred I let PDFBox to resize the image by giving it the desired size. Like the code below:
PDXObjectImage ximage = new PDJpeg(doc, new FileInputStream(new File("/usr/gyo/my_large_image.jpg")), 1.0f);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
Dimension scaledDim = getScaledDimension(new Dimension(ximage.getWidth(), ximage.getHeight()), page.getMediaBox().createDimension());
contentStream.drawXObject(ximage, 1, 1, scaledDim.width, scaledDim.height);
contentStream.close();
Thank you,
Gyo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With