slamek10
slamek10

Reputation: 93

Absolute position with itext7

I have a problem with adding a image with absolute position relative to page size in itext7.

In itext5 I used the code below to determine the image position relative to the page that I'm adding it to

for (int i = 0; i < numberOfPages;) {
    page = copy.getImportedPage(reader, ++i);

    if(page.getBoundingBox().getWidth() != 595.00f) {
        img.setAbsolutePosition(page.getBoundingBox().getWidth() - (595-img.getAbsoluteX()),img.getAbsoluteY());
    }
    if(page.getBoundingBox().getHeight() != 842.00f) {
        img.setAbsolutePosition(img.getAbsoluteX(), page.getBoundingBox().getHeight() - (842-img.getAbsoluteY()));
    }

    stamp = copy.createPageStamp(page);
    stamp.getOverContent().addImage(img);
    stamp.alterContents();
    copy.addPage(page);
}

Now for itext7 I'm using

public static void addImageToPDF(String inputFilePath, Image img) throws IOException, DocumentException {    

    File inFile = new File(inputFilePath);
    File outFile = new File(inputFilePath + "_image.pdf");

    PdfDocument pdfDoc = new PdfDocument(new PdfReader(inFile), new PdfWriter(outFile));

    Document document = new Document(pdfDoc);
    int numberOfPages = pdfDoc.getNumberOfPages();

    Rectangle pageSize;

    // Loop over the pages of document
    for (int i = 1; i <= numberOfPages; i++) {

        pageSize = pdfDoc.getPage(i).getPageSize();

        if(pageSize.getWidth() != 595.00f) {
            img.setFixedPosition(pageSize.getWidth() - (595-img.getImageWidth()),img.getImageHeight());
        }
        if(pageSize.getHeight() != 842.00f) {
            img.setFixedPosition(img.getImageWidth(), pageSize.getHeight() - (842-img.getImageHeight()));
        }

        document.add(img);
    }
}

I need the image to be added in the right top corner relative to the page, but now it adds it in the middle of the screen on the right.

Is there a way to set absolute position in itext7 when adding an image? The image is not always on the same position to the exact width and height so I's a problem for me using fixed position.

Upvotes: 3

Views: 6020

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

I don't get why you need two cases in your for loop. If your goal is to place the image to the top right position of the page and you know the image width and height as well as page width and height, all you need to do is calculate the coordinates to pass to setFixedPosition method.

setFixedPosition accepts x and y coordinates which are image's left bottom coordinates in PDF coordinate system, i.e. left to right, top to bottom.

So you need to subtract image width from page width and do the same for height, which results in the following one-liner:

img.setFixedPosition(pageSize.getWidth() - img.getImageWidth(), pageSize.getHeight() - img.getImageHeight());

Upvotes: 5

Related Questions