Positioning A4 image as page inside PDF file using pdfbox - java

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.

Related

Pdfbox : Draw image in rotated page by 270 degree [duplicate]

I have a simple A4 pdf document with a property /Rotate 90 : The original version of my pdf is landscape but printed portrait.
I am trying to draw a small image at the bottom left of the portait document.
Here is my code so far :
File file = new File("rotated90.pdf");
try (final PDDocument doc = PDDocument.load(file)) {
PDPage page = doc.getPage(0);
PDImageXObject image = PDImageXObject.createFromFile("image.jpg", doc);
PDPageContentStream contents = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, false, true);
contents.drawImage(image, 0, 0);
contents.close();
doc.save(new File("newpdf.pdf"));
}
Here is the end result : As you can see the image was placed at the top left (which was the 0,0 coordinate before rotation) and was not rotated.
I tried playing with drawImage(PDImageXObject image, Matrix matrix) without success.
Here is the orignal document pdf with 90° rotation
Here's a solution for a page that is rotated 90°:
PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
PDImageXObject image = ....
cs.saveGraphicsState();
cs.transform(Matrix.getRotateInstance(Math.toRadians(90), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), 0));
cs.drawImage(image, 0, 0);
cs.restoreGraphicsState();
cs.close();
If it is only the image, then you don't need the save/restore.
Solution for a page that is rotated 270°:
cs.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));
For 180°:
cs.transform(Matrix.getRotateInstance(Math.toRadians(180), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));

Flip PDF with pdfbox

I've been trying to figure out how to flip a pdf for a while, but haven't figured out yet.
I've only found how to flip image using Graphics2D:
// Flip the image vertically
AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -image.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
Could you please help me to get it with PDFbox?
Thanks!!
With PDFBox 2.*, you need to prepend it to the page content stream. Optionally save and restore graphics state, useful for further modifications. (All based on this answer)
PDPage page = doc.getPage(0);
try (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.PREPEND, true))
{
cs.saveGraphicsState();
cs.transform(Matrix.getScaleInstance(1, -1));
cs.transform(Matrix.getTranslateInstance(0, -page.getCropBox().getHeight()));
cs.saveGraphicsState();
}
try (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true))
{
cs.restoreGraphicsState();
cs.restoreGraphicsState();
}

How to render part of a PDF file as an image using PDFBox?

PDFBox offer functions to render a entire page, but no way to render only a specific rectangle of the page.
This code is working for me. But as mentioned above it renders the whole page and I need a method to render a little area of the pdf file:
File file = new File("package.pdf");
PDDocument document = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImageWithDPI(0, 400);
ImageIO.write(image, "PNG", new File("C:/package1.png"));
document.close();
I would be very happy about a solution, since I have not found a solution for hours
I have found a soulution by myself. CropBox was the deciding keyword i did not know about.
File file = new File("package.pdf");
PDDocument document = PDDocument.load(file);
PDPage page = document.getPage(0);
page.setCropBox(new PDRectangle(133f, 150f, 100f, 100f)); // Here you draw a rectangle around the area you want to specify
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImageWithDPI(0, 400);
ImageIO.write(image, "PNG", new File("C:/fatihabi.png"));
document.close();

What is the recommended way to write a BufferedImage to a PDF using PDFBox?

I'm trying to convert a TIFF to a PDF using Apache Imaging and PDFBox. Everything I've tried results in a blank (but non-zero-byte) pdf.
There are some examples in other SO questions like Add BufferedImage to PDFBox document and PDFBox draw black image from BufferedImage which I've tried.
I know the buffered image that I'm reading from the TIFF is valid because I can display it and see it in a JFrame.
I've also tried a PDFJpeg instead of a PDFPixelMap, and contentStream.drawImage() instead of .drawXObject(), the result is always the same.
I also tried creating the PDXObjectImage before the content stream and writing multiple images as recommended in Can't add an image to a pdf using PDFBox, the result is still the same. The output file is larger when I write the image multiple times, so it's doing "something" but I don't know what it is.
How can I write a BufferedImage to a page on a PDF using PDFBox?
try(PDDocument document = new PDDocument();ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
PDPage blankPage = new PDPage();
document.addPage( blankPage );
// PDXObjectImage pdImage = new PDJpeg(document, image);
PDXObjectImage pdImage = new PDPixelMap(document, image);
// contentStream.drawImage(pdImage, 5, 300);
PDPageContentStream contentStream = new PDPageContentStream(document, blankPage);
contentStream.drawXObject(pdImage, 5, 5, 100, 100);
document.save("test.pdf");
contentStream.close();
}
catch(COSVisitorException ex) {
throw new IOException(ex);
}

Insert image as new layer to existing PDF using PdfBox 1.8.8

I'm using PDFBox in my application to modify existing PDF files.
I need to place a barcode to the first page of the PDF document.
So first i create new PDF file with inserted barcode:
PDDocument document = new PDDocument();
PDXObjectImage ximage = new PDPixelMap(document, awtImage);
PDPage pag = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight()));
document.addPage(pag);
PDPageContentStream stream = new PDPageContentStream(document, pag, false, false);
stream.drawXObject(ximage, 0, 0, ximage.getWidth(), ximage.getHeight());
stream.close();
Then i try to place it as new layer into existing PDF:
Point barlocation = new Point(0,0);
float Height = page.getMediaBox().getHeight();
float Width = page.getMediaBox().getWidth();
barlocation.setLocation(Width - pag.getMediaBox().getWidth(), Height - pag.getMediaBox().getHeight()); //I need to place it in the top right corner
LayerUtility layerUtility = new LayerUtility(doc);
List bigPages = doc.getDocumentCatalog().getAllPages();
PDXObjectForm firstForm = layerUtility.importPageAsForm(document, 0);
AffineTransform affineTransform = new AffineTransform();
affineTransform.translate(barlocation.x , barlocation.y);
layerUtility.appendFormAsLayer((PDPage) bigPages.get(0), firstForm, affineTransform, "barcode layer");
doc.save(path);
doc.close();
So it works well with PDF document ver 1.5 (created in MS Word 2010/2013). But it's not working correctly with PDF document version 1.6 position and size of the inserted layer are wrong (i can't post an image, so you can see the result here:http://img4.imagetitan.com/img.php?image=11_capture567.png
What should I change? Thanks for reading and sorry for my bad English.

Categories

Resources