Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre-align images in generated iText PDF document

Tags:

android

itext

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

like image 811
Tarun Deep Attri Avatar asked Dec 28 '17 03:12

Tarun Deep Attri


People also ask

How to set image position in PDF?

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.

How do I add a picture on PdfPCell?

There are different strategies for adding an Image to a PdfPCell . cell = new PdfPCell(img[1], true); table. AddCell(cell);


2 Answers

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.

like image 132
Bruno Lowagie Avatar answered Sep 28 '22 23:09

Bruno Lowagie


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);
like image 41
Sumit Kumar Avatar answered Sep 29 '22 00:09

Sumit Kumar