简体   繁体   中英

How to extend the page size of existing PDF to add a footer in iText

I need to add content in the form a footer with a paragraph centered to all pages of an existing PDF file. I've followed this previous answer but the solution does not solve my issue. Although the code works, my PDFs do NOT have enough bottom margin to fit the footer so the text gets on top of the content.

What I need to do before adding the footer is adding some extra margin at the bottom (effectively extending the page size). Similar to what is done in this question but ONLY that I need to add the extra margin at the bottom instead.

I also tried this but didn't work. I'm trying to figure it out myself but no luck so far.

If you know how to add extra space on the side as explained in this question: How to extend the page size of a PDF to add a watermark? then you should know how to add extra space to the bottom too. Your question is a duplicate.

The page size of a PDF document is defined using the /MediaBox . It can be cropped using the /CropBox . In the answer I gave, we change the /MediaBox like this:

PdfArray mediabox = pageDict.getAsArray(PdfName.MEDIABOX);
llx = mediabox.getAsNumber(0).floatValue();
mediabox.set(0, new PdfNumber(llx - 36));

The value of llx is the coordinate of the lower-left X-coordinate, and we subtract half an inch (36 user units).

If you want to change the bottom border, you have to change the lower-left Y-coordinate:

PdfArray mediabox = pageDict.getAsArray(PdfName.MEDIABOX);
lly = mediabox.getAsNumber(1).floatValue();
mediabox.set(1, new PdfNumber(llx - 36));

That's what Mark is doing in his answer to the question How do I resize an existing PDF with Coldfusion/iText

Of course, this won't have any effect if there's a crop box. If there's a crop box, you need to change the llx value of the crop box too:

PdfArray cropbox = pageDict.getAsArray(PdfName.CROPBOX);
if (cropbox != null) {
    lly = cropbox.getAsNumber(1).floatValue();
    cropbox.set(1, new PdfNumber(llx - 36));
}

Obviously, you need to take the change into account when adding the footer. The bottom coordinate is no longer lly but lly - 36 in my example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM