I have a file jpg file: 2480 x 3508 pixels which is the suitable size for 4A. I need to put this file in a pdf.
PDDocument doc = new PDDocument();
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream certificate = getClass().getResourceAsStream("certificate.jpg");
BufferedImage bi = ImageIO.read(certificate);
PDPage page = new PDPage(PDRectangle.A4);//<<---- A4
doc.addPage(page);
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, bi);
PDPageContentStream contentStream = new PDPageContentStream(doc, page,
PDPageContentStream.AppendMode.APPEND, false);
contentStream.drawImage(pdImageXObject, 0, -10);
contentStream.close();
doc.save( "c://appfiles//PDF_image.pdf" );
doc.close();
The problem is that the generated file is totally off and not fitting the A4 size in the PDF.
The source file: https://i.stack.imgur.com/a0ZHG.jpg
The generated File: https://www.dropbox.com/s/ufo3246b6eoz3f5/PDF_image.pdf?dl=1
I know I can play with the width and height but then the printing quality drops and I think the PDRectangle.A4
was intended to prevent these kind of manipulations.
How can I make the 2480 x 3508 pixels
fit to PDRectangle.A4
pdf page?
Thanks
The dimensions of PDF are on 72 dpi,
System.out.println(PDRectangle.A4); // output is [0.0,0.0,595.27563,841.8898]
your image is 300 dpi, so you have to scale:
contentStream.drawImage(pdImageXObject, 0f, -10f,
pdImageXObject.getWidth() / 300f * 72,
pdImageXObject.getHeight() / 300f * 72);
I also recommend to use JPEGFactory.createFromStream()
, this is faster, smaller and uses the jpeg stream directly. Your result PDF file is 580 KB instead of 2555 KB.