【发布时间】:2015-06-04 06:03:32
【问题描述】:
我可以使用 java 和 itext 创建一个带有页眉和正文内容的 pdf 文件。您可以在文件共享站点by clicking on this link 查看生成的文件。
如何更改下面的代码,以便在页面底部创建页脚?我希望页脚显示“MyCity、MyState、MyPostalCode MyPhoneNumber”。我还希望页脚在其上方有一行,就像在上面的示例链接中页眉在其上方有一行一样。
这是在上面的链接中生成示例 PDF 的代码:
public class HeaderFooter {
public static final String RESULT = "C:\\path\\to\\headerfooter.pdf";
public static void main(String[] args) throws SQLException, DocumentException, IOException {
Document document = new Document(PageSize.A4, 36, 36, 54, 36);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph(""));
document.add(Chunk.NEWLINE);
document.add(new Paragraph("First paragraph."));
document.add(new Paragraph("Second paragraph."));
document.add(new Paragraph("Third paragraph."));
document.newPage();
document.close();
PdfReader reader = new PdfReader(baos.toByteArray());
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
getHeader(i, n).writeSelectedRows(0, -1, 34, 803, stamper.getOverContent(i));
}
stamper.close();
reader.close();
}
public static PdfPTable getHeader(int x, int y) {
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(527);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell("This is the Document's Title.");
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
return table;
}
}
对于任何想要花一分钟时间让上述代码在他们的计算机上运行的人,添加到 pom.xml 的 maven 依赖项是:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.5</version>
</dependency>
【问题讨论】:
-
你知道
writeSelectedRows参数的含义吧?因此,它应该是相当明显的......提示:您的34, 803是添加标题表的坐标。对于页脚表,使用相当小的 y 坐标。
标签: java pdf pdf-generation itext