Adding footer to existing PDF

2019-06-03 20:19发布

问题:

I am trying to add footer to my existing PDF. I did add one footer to the PDF.

Is there anyway to add 2 lines of footer? This is my code below:

Document document = new Document(); 

PdfCopy copy = new PdfCopy(document, new FileOutputStream(new File("D:/TestDestination/Merge Output1.pdf")));
document.open();

PdfReader reader1 = new PdfReader("D:/TestDestination/Merge Output.pdf");
int n1 = reader1.getNumberOfPages();

PdfImportedPage page;
PdfCopy.PageStamp stamp;
Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);

for (int i = 0; i < n1; ) {
    page = copy.getImportedPage(reader1, ++i);
    stamp = copy.createPageStamp(page);
    ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER,new Phrase(String.format("page %d of %d", i, n1)),297.5f, 28, 0);
    stamp.alterContents();
    copy.addPage(page);
}

document.close();
reader1.close();

回答1:

Please go to the official documentation and click Q&A to go to the Frequently Asked Questions. Select Absolute positioning of text.

You are currently using ColumnText in a way that allows you to add a single line of text. You are using ColumnText.showTextAligned(...) as explained in my answer to the question How to rotate a single line of text?

You should read the answers to questions such as:

  • How to add text at an absolute position on the top of the first page?
  • How to add text inside a rectangle?
  • How to truncate text within a bounding box?
  • How to fit a String inside a rectangle?
  • How to reduce redundant code when adding content at absolute positions?

Assuming that you don't have access to the official web site (otherwise you wouldn't have posted your question), I'm adding a short code snippet:

ColumnText ct = new ColumnText(stamp.getUnderContent());
ct.setSimpleColumn(rectangle);
ct.addElement(new Paragraph("Whatever text needs to fit inside the rectangle"));
ct.go();

In this snippet, stamp is the object you created in your code. The rectangle object is of type Rectangle. Its parameters are the coordinates of the lower-left and upper-right corner of the rectangle in which you want to render the multi-line text.

Caveat: all text that doesn't fit the rectangle will be dropped. You can avoid this by adding the text in simulation mode first. If the text fits, add it for real. If it doesn't fit, try anew using a smaller font or a bigger rectangle.



标签: java pdf itext