一。首先引用pom:
<!-- pdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.2.0</version> </dependency> <!--pdf中文支持,不引用此jar,中文将显示空白--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
二。 代码部分:
// 1.新建document对象 // 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。 document = new Document(PageSize.A4, 50, 50, 50, 50); // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。 // 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // 3.打开文档 document.open(); // 4.向文档中添加内容 // 通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落 //设置中文样式,不设置时如果pdf中有中文,将显示空白 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font fontChinese_italic = new Font(bfChinese, 13, Font.ITALIC, BaseColor.LIGHT_GRAY); Font fontChinese_title = new Font(bfChinese, 14, Font.BOLD, BaseColor.BLACK); Font fontChinese_content = new Font(bfChinese, 14, Font.NORMAL, BaseColor.BLACK); Paragraph hintP = new Paragraph(hints, fontChinese_italic); document.add(hintP); // 5.关闭文档,不要放在finally里关闭,在finally关闭生成的pdf是空白 document.close();