iText生成pdf文件时,会遇到分页(page X of Y)的需求。
iText分页主要有2个方法:
1. 创建一个document(不含page X of Y信息)放内存中,新建一个PdfReader对象,通过PdfReader对象得到PdfStamper,使用PdfStamper把分页号写入每一页的页眉或页脚。当需要生成pdf的页面较多时,计算页号就有可能发生不准确。
2. 在Page Event(如onEndPage)里增加Page X of 信息,同时增加一个空的模板应用到所有的页面上。当onCloseDocument事件发生时, 设置Y的值到模板上,并应用到每个页面上。
下面重点来聊聊第二种方法。
1. onStartPage() - 当一个新的页面开始时触发 Triggered when a new page is started. Don’t add content in
this event, not even a header or footer . Use this event for initializing vari-
ables or setting parameters that are page specific, such as the transition or
duration parameters.
2. onEndPage()—Triggered just before starting a new page. This is the best place to add a header, a footer, a watermark, and so on.
3. onOpenDocument()—Triggered when a document is opened, just before onStartPage() is called for the first time. This is a good place to initialize variables that will be needed for all the pages of the document.
4. onCloseDocument()—Triggered just before the document is closed. This is the ideal place to release resources (if necessary) and to fill in the total number of pages in a page X of Y footer.
5. onParagraph()—In chapter 7, “Constructing columns,” you used get-VerticalPosition() to retrieve the current Y coordinate. With the onParagraph() method, you get this value automatically every time a new Paragraph is started.
6. onParagraphEnd()—Differs from onParagraph() in that the Y position where the paragraph ends is provided, instead of the starting position.
7. onChapter()—Similar to onParagraph(), but also gives you the title of the Chapter object (in the form of a Paragraph).
8. onChapterEnd()—Similar to onParagraphEnd(), but for the Chapter object.
9. onSection()—Similar to onChapter(), but for the Section object.
10. onSectionEnd()—Similar to onChapterEnd(), but for the Section object.
11. onGenericTag()—See section 4.6, “Generic Chunk functionality.”
以上是生成pdf时会发生的事件。
我遇到的分页问题:
当批量产生pdf时, 即把多个文件生成到一个pdf时,有这样的需求。
对所有的页面生成总页码X/Y,对被包含的子文件, 也要对其内部分页,并显示相应的页码x/y。
原理:
在document里,应用多个模板, 他们分别对应显示总页码,下面的子页码。
建两个变量来统计子页码
- int msgpagecount = 0;
- int msgtotal = 1;
- public void onEndPage(PdfWriter writer, Document document) {
- int pageN = writer.getPageNumber();
- String text = "message " + (pageN-msgpagecount+1) + " of ";
- float len = bf.getWidthPoint(text, 8);
- cb.beginText();
- cb.setFontAndSize(bf, 8);
- cb.setTextMatrix(280, document.bottom());
- cb.showText(text);
- cb.endText();
- cb.addTemplate(tmplmsg, 280+len, document.bottom());
- }
- public void onParagraph(PdfWriter writer, Document document, float position) {
- msgpagecount = writer.getPageNumber();
- tmplmsg = cb.createTemplate(50, 50);
- }
- public void onParagraphEnd(PdfWriter writer, Document document, float position){
- msgtotal=writer.getPageNumber()-msgpagecount+1;
- tmplmsg.beginText();
- tmplmsg.setFontAndSize(bf, 8);
- tmplmsg.showText(String.valueOf(msgtotal));
- tmplmsg.endText();
- }
睡觉.