我正在使用 OpenPDF 生成带有添加到 PDF 的页眉和页脚图像的 PDF 文档。需要将一个段落添加到 PDF 的中心,其中一些文本内容是基于输入请求的动态的,并且所有内容都需要被边框包围。我能够生成添加了页眉和页脚的 PDf,但在将段落添加到 pdf 和边框的中心时遇到问题。任何帮助表示赞赏。
我通过添加表格或使用画布尝试了不同的方法,但无法解决。
public void generatePDF(String firstName, String lastName){
try {
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(DEST));
//setting font family, color
Font font = new Font(Font.HELVETICA, 16, Font.BOLDITALIC, Color.RED);
doc.open();
addHeaderImageToPDF(doc,writer);
Paragraph para = new Paragraph("Hello! This PDF is created for "+firstName+" "+lastName, font);
para.setAlignment(Element.ALIGN_MIDDLE);
doc.add(para);
addFooterImageToPDF(doc,writer);
addBorderToPDF(doc);
doc.close();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void addBorderToPDF(Document document){
Rectangle rect= new Rectangle(531.5f,820,38.5f,0); // you can resize rectangle
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorderColor(Color.BLACK);
rect.setBorderWidth(2);
document.add(rect);
}
private void addHeaderImageToPDF(Document document, PdfWriter writer){
try {
Image image = Image.getInstance(HEADER_IMAGE_PATH);
//image = Image.getInstance(IMAGE_PATH);
image.scalePercent(50f);
//image.setAbsolutePosition(0, (float) (PageSize.A4.getHeight() - 20.0));
image.setAbsolutePosition(40, 675);
System.out.println(image.getScaledHeight());
document.add(image);
image.scaleToFit(100f, 100f);
//document.add(image);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void addFooterImageToPDF(Document document, PdfWriter writer){
try {
Image image = Image.getInstance(FOOTER_IMAGE_PATH);
//image = Image.getInstance(IMAGE_PATH);
image.scalePercent(50f);
//image.setAbsolutePosition(0, (float) (PageSize.A4.getHeight() - 20.0));
image.setAbsolutePosition(40, 450);
System.out.println(image.getScaledHeight());
document.add(image);
image.scaleToFit(100f, 100f);
//document.add(image);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
想要在中心添加段落,PDF 的全部内容应该用深蓝色边框包围。任何帮助表示赞赏。