maven依赖:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.2.0</version> </dependency> <!-- PDF输出中文的扩展包 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
操作:
package excel; import java.io.FileOutputStream; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; /** * 利用Itext导出PDF 文档 * * @author GIE * */ public class CreatPdf { public static void main(String[] args) { Document doc = null; try { doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("C:\\itext.pdf")); doc.open(); doc.addTitle("测试标题"); doc.addAuthor("gie"); doc.addCreationDate(); doc.addSubject("测试主题"); // itext 中文的处理 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); Paragraph pragraph = new Paragraph("你好", FontChinese); doc.add(pragraph); } catch (Exception e) { e.printStackTrace(); } finally { doc.close(); } } }
关键点:
iText 本身不支持中文 需要扩展包
时间: 2024-10-16 15:46:10