Why are images getting cropped while converting Images to PDF using iText library in android

When you do this:

Document document = new Document();

Then you implicitly create a document of which the pages have a page size known as A4. That is: a width of 595 and a height 842 user units.

If you add images that are smaller, they won't be cropped. If you add images that are bigger. The images will be cropped...

If you want an image to fit a page exactly, you have two options:

  1. Adapt the size of the pages, or
  2. Adapt the size of the image.

Both options are equivalent, as iText will not change the resolution of the images: every pixel will be preserved.

Option 1:

See my answer to the question: Adding maps at iText Java

In this question, I do this:

Image img = Image.getInstance(IMG);
Document document = new Document(img);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
img.setAbsolutePosition(0, 0);
document.add(img);
document.close();

The Document object accepts a Rectangle as parameter. This Rectangle defines the page size in user units. As the Image class is a subclass of the Rectangle class, I can use the Image instance as a parameter to create the Document instance.

Another option would be to do this:

Rectangle pagesize = new Rectangle(img.getScaledWidth(), img.getScaledHeight());
Document document = new Document(pagesize);

If your document has different pages, you must use the setPageSize() method before triggering a new page.

Option 2:

See my answer to the question: Backgroundimage in landscape and cover whole pdf with iTextSharp

The code looks like this (well, the actual code is a tad different, but this will work too):

Document document = new Document(PageSize.A4.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Image image = Image.getInstance(IMAGE);
image.scaleAbsolute(PageSize.A4.rotate());
image.setAbsolutePosition(0, 0);
document.add(image);
document.close();

Here I have pages with size A4 in landscape, and I scale the image so that it fits the page completely. That is dangerous because this changes the aspect-ratio of the image. This can result in distorted images. Replacing scaleAbsolute() by scaleToFit() will avoid that problem, but you'll have some white margins if the aspect-ratio of the image is different from the aspect-ratio of the page.

Important: Note that I used setAbsolutePosition(0, 0); in both cases. I am introducing this line so that the lower-left corner of the image coincides with the lower-left corner of the page. If you don't do this, you will see a margin to the bottom and to the left, and your image will be clipped to the top and the right.

Tags:

Pdf

Android

Itext