gpt4 book ai didi

java - 在StartPage itextPdf上添加对象(最后一页除外)

转载 作者:行者123 更新时间:2023-12-02 10:43:19 25 4
gpt4 key购买 nike

我在所有页面的页面顶部添加一个矩形,但我不希望在最后一页上添加矩形。这是我的代码:

 @Override
public void onStartPage(PdfWriter writer, Document output) {
Font bold = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
bold.setStyle(Font.UNDERLINE);
bold.setColor(new BaseColor(171, 75, 15));
PdfContentByte cb = writer.getDirectContent();
// Bottom left coordinates x & y, followed by width, height and radius of corners.
cb.roundRectangle(100f, 1180f, 400f, 100f, 5f);//I dont want this on the ;ast page
cb.stroke();
try {
output.add(new Paragraph("STATEMENT OF ACCOUNT", bold));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
Image logo = Image.getInstance(imagepath);
logo.setAbsolutePosition(780, 1230);
logo.scaleAbsolute(200, 180);
writer.getDirectContent().addImage(logo);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}

有没有办法从文档的最后一页跳过或删除这个矩形?

最佳答案

首先,iText 开发人员经常强调,在 onStartPage 中,不得向 PDF 添加内容。原因是在某些情况下,会创建未使用的页面并为它们调用 onStartPage 但随后将其删除。但是,如果您在 onStartPage 中向它们添加内容,它们不会被删除,而是保留在您的文档中。

因此,请始终使用 onEndPage 将任何内容添加到页面。

<小时/>

在您的用例中,使用onEndPage还有另一个原因:通常只有当最后一位内容添加到文档中时,才会清楚给定页面是最后一页。这通常发生在为页面调用 onStartPage 之后、onEndPage 之前。

因此,在将最后一位常规页面内容添加到文档后,您可以简单地在页面事件监听器中设置一个标志,表明当前页面是最终文档页面。现在,以下 onEndPage 调用知道它会处理最终页面,并且可以以不同的方式添加内容。

所以页面事件监听器看起来像这样

class MyPageEventListener extends PdfPageEventHelper {
public boolean lastPage = false;

@Override
public void onEndPage(PdfWriter writer, Document output) {
if (!lastPage) {
[add extra content for page before the last one]
} else {
[add extra content for last page]
}
}

...
}

并像这样使用

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, TARGET);
MyPageEventListener pageEventListener = new MyPageEventListener();
writer.setPageEvent(pageEventListener);
document.open();
[add all regular content to the document]
pageEventListener.lastPage = true;
document.close();

关于java - 在StartPage itextPdf上添加对象(最后一页除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com