我正在使用 iText 5.0 将静态文本添加到几个现有的 PDF 中。以下代码适用于纵向 PDF,但不适用于横向 PDF。我一直在努力让这项工作正常进行,我会感谢任何关于我可能在这里遗漏的提示。
横向示例 PDF:http: //mirrors.ibiblio.org/CTAN/macros/latex/contrib/mwe/example-image-a4-landscape.pdf
代码块:
private static void addTextToPDF(int pageNr, PdfReader reader, PdfStamper pdfStamper) {
for (int i = 1; i <= reader.getNumberOfPages(); i++)
{
Rectangle pageSize = reader.getPageSizeWithRotation(i);
PdfContentByte pdfPageContents = pdfStamper.getUnderContent(i);
pdfPageContents.beginText();
BaseFont baseFont = null;
try {
baseFont = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
pdfPageContents.setFontAndSize(baseFont, 40);
pdfPageContents.setRGBColorFill(255, 0, 0);
pdfPageContents.showTextAligned(PdfContentByte.ALIGN_CENTER, "Put this text on the page!!",
pageSize.getWidth()/2,
pageSize.getHeight()/2,
0.0f);
pdfPageContents.endText();
System.out.println("Wriiten at:" + pageSize.getWidth()/2 + " " + pageSize.getHeight()/2);
}
pdfStamper.setFormFlattening(true);
}