简体   繁体   English

使用带有Java的itext api在pdf中获得额外的页数

[英]getting extra page count in pdf using itext api with Java

I have an issue with the page count in a PDF.我对 PDF 中的页数有疑问。

Suppose that we have a pdf with page count 3, but in the footer it's returning "Page 1 Of 4".假设我们有一个页数为 3 的 pdf,但在页脚中它返回“第 1 页,共 4 页”。 We are getting the 4 from the Eventer class.我们从 Eventer 类中得到了 4。

Jar : com.lowagie.text-2.1.7.jar罐子:com.lowagie.text-2.1.7.jar

Eventer class : PdfPageEventHelper.java事件类:PdfPageEventHelper.java

在此处输入图片说明

Please read the official documentation, and you'll discover that the example on the unoffical web site you consulted is wrong.请阅读官方文档,你会发现你查阅的非官方网站上的例子是错误的。

In chapter 5 of my book "iText in Action - Second Edition", you'll find the MovieCountries1 example.在我的书“iText in Action - 第二版”的第 5 章中,您将找到MovieCountries1示例。 As you can see, we use writer.getPageNumber() - 1 in the onCloseDocument() method.如您所见,我们在onCloseDocument()方法中使用了writer.getPageNumber() - 1

public void onCloseDocument(PdfWriter writer, Document document) {
    ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
            new Phrase(String.valueOf(writer.getPageNumber() - 1)),
            2, 2, 0);
}

The reason for this is explained in the NOTE on page 152 of the book:原因在本书第 152 页的注释中进行了解释:

NOTE When the document is closed, the newPage() method is triggered to perform finilizations on the current page.注意当文档关闭时,会触发newPage()方法对当前页面执行完成。 When newPage() is called, the page number is augmented, so you need to use (writer.getPageNumber() - 1) if you want to add the total number of pages in the onCloseDocument() method.调用newPage()增加了页码,所以如果要在onCloseDocument()方法中增加总页数,需要使用(writer.getPageNumber() - 1)

If you need another example, take a look at the FillTemplateHelper example on the official web site.如果您需要另一个示例,请查看官方网站上的FillTemplateHelper示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM