I am using a library "com.itextpdf:itextg" for generating PDF files. My requirement is to add images to PDF file in A4 format, One Image per page.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
image.scaleToFit(PageSize.A4);
document.add(image);
By default, images are added as top-aligned and some space is left vacant at bottom of the PDF document page.
I want to centre-align Images, so that equal space is left from all sides and the image is placed at the centre.
I know we have a method setAbsolutePosition, but it requires absoluteX and absoluteY. I needed something relative like CENTRE_HORIZONTAL and CENTRE_VERTICAL. Can someone help in generating PDF with images centre-aligned (vertically and horizontally)?
Place an image or object into a PDFOpen the PDF in Acrobat, and then choose Tools > Edit PDF > Add Image . In the Open dialog box, locate the image file you want to place. Select the image file, and click Open. Click where you want to place the image, or click-drag to size the image as you place it.
There are different strategies for adding an Image to a PdfPCell . cell = new PdfPCell(img[1], true); table. AddCell(cell);
If you really need A4 pages, then you need to calculate the X, Y position for the scaled image so that it is centered both horizontally and vertically.
image.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
float x = (PageSize.A4.getWidth() - image.getScaledWidth()) / 2;
float y = (PageSize.A4.getHeight() - image.getScaledHeight()) / 2;
image.setAbsolutePosition(x, y);
document.add(image);
This will center the image on an A4 page.
However, if I were you, I wouldn't try to center images on an A4 page. Instead, I'd adapt the page size to the size of the image instead.
horizontal center alignment of image can achieve by following code
Image signature = Image.getInstance(stream.toByteArray());
signature.scaleAbsolute(70f, 70f);
signature.setAlignment(Element.ALIGN_CENTER);
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