我正在使用iText生成PDF。我创建了一个自定义的PdfPageEventHelper来为每个页面添加页眉(和页脚)。
我的问题是我不知道如何添加图像,因此它显示在“标题框”中。我只知道如何将图像添加到文档内容本身(如果有意义的话)。
这是一些代码片段......
public static void main(String[] args) {
Rectangle headerBox = new Rectangle(36, 54, 559, 788);
/* ... */
Document document = new Document(PageSize.A4, 36, 36, 154, 54);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILENAME));
HeaderFooter event = new HeaderFooter();
writer.setBoxSize("headerBox", headerBox);
writer.setPageEvent(event);
document.open();
addContent();
document.close();
}
static class HeaderFooter extends PdfPageEventHelper {
public void onEndPage(PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("headerBox");
// add header text
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, new Phrase("Hello", fontHeader1),
rect.getLeft(), rect.getTop(), 0);
// add header image
try {
Image img = Image.getInstance("c:/mylogo.PNG");
img.scaleToFit(100,100);
document.add(img);
} catch (Exception x) {
x.printStackTrace();
}
}
}
非常感谢有关将图像添加到标题的适当方法的任何建议!!
罗布
答案 0 :(得分:11)
你犯了两个重大错误。
Image
方法之外创建onEndPage()
对象,然后重复使用它。这样,图像字节将仅添加到PDF一次。Document
方法的onEndPage()
应被视为只读参数。禁止向其添加内容。它与您使用new Document(PageSize.A4, 36, 36, 154, 54)
创建的对象不同。实际上,它是PdfDocument
实例在内部创建的PdfWriter
类的实例。要添加图片,您需要从编写者处获取PdfContentByte
,然后使用addImage()
添加图片。阅读文档可以轻松避免这样的错误。阅读我的书iText in Action可以节省大量时间。
答案 1 :(得分:5)
你能试试吗
img.setAbsolutePosition(10, 10);
writer.getDirectContent().addImage(img);
而不是
document.add(img);
在onPageEnd
内?
答案 2 :(得分:1)
我已经为图像设置了绝对位置和对齐方式(在这种情况下,我将图像放在标题中)
try {
Image img = Image.getInstance("url/logo.png");
img.scaleToFit(100,100);
img.setAbsolutePosition((rect.getLeft() + rect.getRight()) / 2 - 45, rect.getTop() - 50);
img.setAlignment(Element.ALIGN_CENTER);
writer.getDirectContent().addImage(img);
} catch (Exception x) {
x.printStackTrace();
}
我还调整了文档边距,以便在文档的页眉和页脚中分隔空格。
document.setMargins(20, 20, 100, 100);
答案 3 :(得分:1)
在页面顶部添加图片的通用解决方案。我们也可以通过将图像置于顶部来实现。它可能会修复您的要求
public static void main(String[] args) throws MalformedURLException, IOException, DocumentException {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
//
// Scale the image to a certain percentage
//
String filename = "image.jpg";
Image image = Image.getInstance(filename);
image = Image.getInstance(filename);
image.scalePercent(200f);
image.setAbsolutePosition(0, (float) (PageSize.A4.getHeight() - 20.0));
System.out.println(image.getScaledHeight());
document.add(image);
//
// Scales the image so that it fits a certain width and
// height
//
image.scaleToFit(100f, 200f);
document.add(image);
document.add(new Chunk("This is chunk 3. "));
System.out.println("created");
} catch (DocumentException | IOException e) {
e.printStackTrace();
} finally {
document.close();
}
}
}