首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > PowerDesigner >

itext 在pdf展示第XX页

2012-12-20 
itext 在pdf显示第XX页如果想在每页显示第x页/共y页这样的功能,实现起来没有那么轻松。 官方页面有具体实现

itext 在pdf显示第XX页

如果想在每页显示第x页/共y页这样的功能,实现起来没有那么轻松。
官方页面有具体实现的例子,连接地址:
http://itextdocs.lowagie.com/tutorial/directcontent/pageevents/index.php
源码:
http://itextdocs.lowagie.com/examples/com/lowagie/examples/directcontent/pageevents/PageNumbersWatermark.java

源码里面的东西比较繁多,精简以后如下:

?


Java代码
1.import java.io.FileOutputStream;
2.
3.import com.lowagie.text.Document;
4.import com.lowagie.text.Element;
5.import com.lowagie.text.ExceptionConverter;
6.import com.lowagie.text.Font;
7.import com.lowagie.text.PageSize;
8.import com.lowagie.text.Paragraph;
9.import com.lowagie.text.pdf.BaseFont;
10.import com.lowagie.text.pdf.PdfContentByte;
11.import com.lowagie.text.pdf.PdfPageEventHelper;
12.import com.lowagie.text.pdf.PdfTemplate;
13.import com.lowagie.text.pdf.PdfWriter;
14.
15.public class PdfExport extends PdfPageEventHelper{
16.
17. public PdfTemplate tpl;
18. public BaseFont bf;
19.
20. public static void main(String[] args) {
21. Document document = new Document(PageSize.A4, 20, 20, 20, 20);
22. try {
23. PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\HelloItext.pdf"));
24. writer.setPageEvent(new PdfExport());
25.
26. BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
27.
28. document.open();
29.
30. Paragraph title = new Paragraph("测试内容。。。。", new Font(bfChinese,15));
31. title.setAlignment(Element.ALIGN_CENTER);
32. document.add(title);
33. } catch (Exception de) {
34. de.printStackTrace();
35. }
36. document.close();
37. }
38.
39. public void onOpenDocument(PdfWriter writer, Document document) {
40. try {
41. tpl = writer.getDirectContent().createTemplate(100, 100);
42. bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
43. }
44. catch(Exception e) {
45. throw new ExceptionConverter(e);
46. }
47. }
48.
49. public void onEndPage(PdfWriter writer, Document document) {
50. //在每页结束的时候把“第x页”信息写道模版指定位置
51. PdfContentByte cb = writer.getDirectContent();
52. cb.saveState();
53. String text = "第" + writer.getPageNumber() + "页,共";
54. cb.beginText();
55. cb.setFontAndSize(bf, 8);
56. cb.setTextMatrix(460, 786);//定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标
57. cb.showText(text);
58. cb.endText();
59. cb.addTemplate(tpl, 492, 786);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标
60.
61. cb.saveState();
62. cb.stroke();
63. cb.restoreState();
64. cb.closePath();//sanityCheck();
65. }
66.
67. public void onCloseDocument(PdfWriter writer, Document document) {
68. //关闭document的时候获取总页数,并把总页数按模版写道之前预留的位置
69. tpl.beginText();
70. tpl.setFontAndSize(bf, 8);
71. tpl.showText(Integer.toString(writer.getPageNumber() - 1)+"页");
72. tpl.endText();
73. tpl.closePath();//sanityCheck();
74. }
75.}

热点排行