0
votes

I am trying to overlay an image on PDF pages. When I try to do that using adobe acrobat and select vertical distance from top and left equal to 0, then image overlays correctly at the required location.

I am trying to achieve the same using iText API but can't seem to position the image at correct location on the pdf.

The values for position are trail and error. The size of the pdf is 612X792 and the size of the image is 1699.0x817.0 so I scaled the image to fit the pdf size.

The left of the image and pdf align correctly but the tops have issue. I tried with all the values and somehow 792/2+100 matches this but again will change in case I get a different pdf or image.

Somehow adobe reader is able to do that. Is there a way to align left and top in iText or any other library.

The pdf is existing pdf generated from some other source.

Updated source code

public void manipulatePdfNoTransparency(String inputFileName,
        String outputfileName, String overlayFilePath, 
        int altPage) throws IOException, DocumentException {

    System.out.println("outputfileName :"+outputfileName);
    PdfReader reader = new PdfReader(inputFileName);
    int n = reader.getNumberOfPages();
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputfileName));

    stamper.setRotateContents(false);
    // image watermark

    Image img = Image.getInstance(overlayFilePath);

    float yOffset=calculateYOffset(reader.getPageSize(1).getWidth(), reader.getPageSize(1)
            .getHeight(),img.getWidth(),img.getHeight());

    img.scaleToFit(reader.getPageSize(1).getWidth(), reader.getPageSize(1)
            .getHeight());
    Rectangle pagesize;
    float x, y;
    // loop over every page

    //int i=1;

    pagesize = reader.getPageSize(1);
    x = (pagesize.getLeft() + pagesize.getRight()) / 2;
    y = (pagesize.getTop() + pagesize.getBottom()) / 2;
    img.setAbsolutePosition(0,yOffset);

    for (int i = 1; i <= n; i = i + altPage) {
        stamper.getUnderContent(i).addImage(img);
    }
    stamper.close();
    reader.close();
    System.out.println("File created at "+outputfileName);
}

public static float calculateYOffset(float pdfWidth,float pdfHeight, float originalImageWidth,float originalImageHeight) {
    // size of image 1699.0x817.0
    // size of pdf 612X792
    //This means that the scaled image has a height of 817 * (612/1699) = ca. 294.3 PDF coordinate system units.
    System.out.println("pdfWidth : "+pdfWidth+ " pdfHeight : "+pdfHeight+" originalImageWidth : "+originalImageWidth+" originalImageHeight : "+originalImageHeight);

    float scaledImageHeight = originalImageHeight*pdfWidth / originalImageWidth;
    //The image shall be positioned on the page by putting its top left corner onto the top left corner of the page. 
    //Thus, the x coordinate of its lower left corner is 0, and the y coordinate of its lower left corner is 
    //the y coordinate of the upper left corner of the page minus the height of the scaled image, 
    //i.e. ca. 792 - 294.3 = 497.7.

    float yOffset = pdfHeight-scaledImageHeight;
    System.out.println("yoffset : "+ yOffset);
    return yOffset;

}
2
somehow 792/2+100 matches this - actually that is off by about 1.7. You only need very simple math to calculate this.mkl
@mkl hi. when you say it is off by 1.7 and simple math is required to calculate this. could you please let me know what math and how you arrived at 1.7. thank you.gaganuser165851

2 Answers

0
votes

In a comment to the question I mentioned

somehow 792/2+100 matches this - actually that is off by about 1.7. You only need very simple math to calculate this.

and the OP responded

when you say it is off by 1.7 and simple math is required to calculate this. could you please let me know what math and how you arrived at 1.7.

This answer explains that math.

Assumed requirements

From the question and later comments by the OP I deduced these requirements:

  • An image shall be overlayed over a PDF page.
  • The image for this shall be scaled, keeping its aspect ratio. After scaling it shall completely fit onto the page and at least one dimension shall equal the corresponding page dimension.
  • It shall be positioned on the page by putting its top left corner onto the top left corner of the page, no rotation shall be applied.
  • The crop box of the PDF page coincides with the media box.

Calculation at hand

In the case at hand, the size of the pdf is 612X792 and the size of the image is 1699.0x817.0. Furthermore, the OP's comments imply that the bottom left corner of the page actually is the origin of the coordinate system.

To scale the horizontal extent of the image to exactly fit the page, one has to scale by 612/1699. To scale the vertical extent to exactly fit the page, one has to scale by 792/817. To make the whole image fit the page with aspect ration kept, one has to use the smaller scaling factor, 612/1699. This is what the OP's

img.scaleToFit(reader.getPageSize(1).getWidth(),reader.getPageSize(1).getHeight());

does, assuming the crop box coincides with the media box.

This means that the scaled image has a height of 817 * (612/1699) = ca. 294.3 PDF coordinate system units.

When positioning an image on a PDF page, you usually do that by giving the coordinates where the bottom left corner of the image shall go.

The image shall be positioned on the page by putting its top left corner onto the top left corner of the page. Thus, the x coordinate of its lower left corner is 0, and the y coordinate of its lower left corner is the y coordinate of the upper left corner of the page minus the height of the scaled image, i.e. ca. 792 - 294.3 = 497.7.

Thus, the scaled image shall be positioned at (0, 497.7).

The numbers the OP found by trial and error are 0 for x and middle height plus 100 for y. The middle height is (792 + 0)/2 = 396. Thus, he uses the coordinates (0, 496) which (see above) vertically are off by ca. 1.7.

1
votes

First let's take a look at this line:

img.scaleToFit(
    reader.getPageSize(1).getWidth(),
    reader.getPageSize(1).getHeight());

The scaleToFit() method resizes an images keeping the aspect ratio intact. You seem to overlook that, so let me give you an example of what it means to keep the aspect ratio intact.

Suppose that you have an image img400x600 that measures 400 x 600 user units, and you scale that image to fit a rectangle of 200 x 10,000 user units:

 img400x600.scaleToFit(200, 10000);

What will be the size of image400x600? You seem to think that the size will be 200 x 10,000, but that assumption is incorrect. The new size of the image will be 200 x 300, because the aspect ratio is width = 0.66666 * height.

You complain that the size of the image doesn't equal the size of the page when you use scaleToFit(), but that is normal if the aspect ratio of the image is different from the aspect ratio of the page.

If you really want the image to have the same size of the page, you need to use the scaleAbsolute() method:

img.scaleAbsolute(
    reader.getPageSize(1).getWidth(),
    reader.getPageSize(1).getHeight());

However, this might result in really distorted images, because scaleAbsolute() doesn't respect the aspect ratio. For instance: I have seen developers who used scaleAbsolute() on portraits of people, and the result was that the picture of these people became ugly; either their head became extremely fat, or it became extremely thin depending on the different in aspect ratio.

Now let's take a look at this line:

img.setAbsolutePosition(0,y+100);

That is a very strange line. You are making the assumption that the x coordinate of the lower left corner is 0; I understand that y + 100 was obtained through trial and error.

Let's see what the official documentation has to say about defining the offset of objects added to an existing PDF document. There are several FAQ items on this subject:

You currently only look at the value of the /MediaBox (you obtain this value using the getPageSize() method), and you ignore the /CropBox (in case it is present).

If I were you, I'd do this:

Rectangle pageSize = reader.getCropBox(pageNumber);
if (pageSize == null)
    pageSize = reader.getPageSize(pageNumber);

Once you have the pageSize, you need to add the take into account the offset when adding content. The origin might not coincide with the (0, 0) coordinate:

img.setAbsolutePosition(pageSize.getLeft(), pageSize.getBottom());

As you can see: there is no need for trial and error. All the values that you need can be calculated.

Update:

In the comments, @mkl clarifies that @Gagan wants the image to fit the height exactly. That is easy to achieve.

If the aspect ratio needs to be preserved, it's sufficient to scaleToFit the height like this:

img.scaleToFit(100000f, pageSize.getHeight());

In this case, the image won't be deformed, but part of the image will not be visible.

If the aspect ratio doesn't need to be preserved, the image can be scaled like this:

img.scaleAbsolute(pageSize.getWidth(), pageSize.getHeight());

If this still doesn't answer the question, I suggest that the OP clarifies what it is that is unclear about the math.