一.准备工作
首先需要加载 itext-1.1.4.jar和iTextAsian.jar两个jar包,其中iTextAsian.jar用于中日韩文字的显示问题.
二.主要类
Paragraph
作为题目并使用 int
作为章节号码来创建它。 ListItems
。 SIMSUN.TTC:宋体和新宋体
SIMKAI.TTF:楷体
SIMHEI.TTF:黑体
SIMFANG.TTF:仿宋体
三.步骤
一个PDF文件的输出,总共只需要5个步骤
a.创建一个Document实例
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
第一个参数是页面大小A4大小,默认为竖置,改为横置则PageSize.A4.rotate();。接下来的参数分别是左、右、上和下页边距。
b.将Document实例和文件输出流用PdfWriter类绑定在一起
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf"));
其他写入器为 HtmlWriter、RtfWriter、XmlWriter 等等,不同的类对应不同的文件格式.
c.打开文档
document.open();
d.在文档中添加文字, 图片、表格、标题等.
1.添加章
chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 18,
com.lowagie.text.Font.NORMAL, Color.black); // 设置字体大小、颜色
Paragraph cTitle = new Paragraph("第一章", chapterFont);
chapter1 = new Chapter(cTitle, 1);
document.add(chapter1); //添加新章
2.添加节
Paragraph sTitle = new Paragraph("第一章第一节", , sectionFont);
Section section = chapter1.addSection(sTitle, 2);
3.添加表格
table = new Table(n); //n表示有多少列
Table table = new Table(8);
float[] widths = { 0.10f, 0.15f, 0.21f, 0.22f, 0.08f, 0.08f, 0.10f,
0.06f };
table.setWidths(widths); //假设有8列,并设置每列的列宽
table中添加cell内容,
Cell cell = new Cell(new Phrase("内容", tableHeaderFont));// 或者 Cell cell = new Cell("内容");
cell.setBackgroundColor(Color.gray); //设置背景色
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //设置为居中,默认为左对齐
table.addCell(cell);
section.add(table); //把表加入节中
4.添加图片
Section subsection = section21.addSection(subTitle, 3); //节下再加新的节
subsection.add("图表"); //给图表加个小标题
通过URL得到图片实例:
Image wmf = Image.getInstance(new URL("../examples/harbour.wmf"));
Image gif = Image.getInstance(new URL("../examples/vonnegut.gif"));
Image jpeg = Image.getInstance(new URL("../examples/myKids.jpg"));
Image png = Image.getInstance(new URL("../examples/hitchcock.png"));
通过文件名得到图片实例:
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png"); // 在本地的完整路径也可以
subsection.add(image);
Paragraph endPgh = new Paragraph("\n"); //换行的作用
endPgh.setAlignment(com.lowagie.text.Image.MIDDLE); //设置图表位置
subsection.add(endPgh);
5.一般的文字
document.add(new Paragraph("Hello World"));
6.添加页码
HeaderFooter footer = new HeaderFooter(new Phrase("页码:",getChineseFont()), true);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
document.open();
e.关闭文档
document.close();