Center alignment of images in the generated iText PDF

I use the library "com.itextpdf: itextg" to create PDF files. My requirement is to add images to a 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 aligned to the top, and some space remains free at the bottom of the PDF document page.

I want to center the image so that equal space remains on all sides and the image is centered.

I know that we have a setAbsolutePosition method, but this requires absoluteX and absoluteY. I need something like CENTER_HORIZONTAL and CENTER_VERTICAL. Can someone help in creating a PDF with the image centered (vertically and horizontally)?

+4
source share
3 answers

If you really need A4 pages, 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 centers the image on the A4 page.

However, if I were you, I would not center the images on an A4 page. Instead, I would adapt the page size to the image size.

+3
source

horizontal alignment in the center of the image can be achieved with the following code

        Image signature = Image.getInstance(stream.toByteArray());
        signature.scaleAbsolute(70f, 70f);
        signature.setAlignment(Element.ALIGN_CENTER);
0
source

use setAlignment()to center the image.

Image image = Image.getInstance(stream.toByteArray());
image .setAlignment(Image.MIDDLE);

For more information read this.

-1
source

Source: https://habr.com/ru/post/1691439/


All Articles