How to position text relative to page using iText?

2020-02-07 04:57发布

问题:

How do I set the position of text so that it is centered vertically relative to its page size? I want to position it say for example x number of points from right and centered vertically. The text of course is rotated 90 degrees.

            int n = reader.getNumberOfPages();
            PdfImportedPage page;
            PdfCopy.PageStamp stamp;
            for (int j = 0; j < n; )
            {
                ++j;
                page = writer.getImportedPage(reader, j);
                stamp = writer.createPageStamp(page);
                Rectangle crop = reader.getCropBox(1);
                // add overlay text
                Phrase phrase = new Phrase("Overlay Text");
                ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, phrase,
                        crop.getRight(72f), crop.getHeight() / 2, 90);
                stamp.alterContents();
                writer.addPage(page);
            }

The code above gives me inconsistent position of text, and in some pages, only a portion of the "Overlay text" is visible. Please help, I don't know how to properly use mediabox and cropbox and I'm new to itext.

Thanks!

回答1:

Regarding the inconsistent position: that should be fixed by adding the vertical offset:

crop.getRight(72f), crop.getBottom() + crop.getHeight() / 2

Do you see? You took the right border with a margin of 1 inch as x coordinate, but you forgot to take into account the y coordinate of the bottom of the page (it's not always 0). Normally, this should fix the positioning problem.

Regarding the fact that only a portion of the overlay text is visible: my first guess was that you're adding content under the existing content, but that guess is wrong (you're using getOverContent()). What exactly do you mean by that second question? Do yo mean the text is clipped by the CropBox? Are you looking for a way to measure the content of phrase to see if it fits the height before you add it?



标签: java pdf itext