失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > iText创建一个含有中文的pdf文档

iText创建一个含有中文的pdf文档

时间:2023-01-19 18:51:15

相关推荐

iText创建一个含有中文的pdf文档

有朋友问我pdfbox支不支持向pdf文档中写入中文。然后试了好多遍都是有乱码,也找了好多资料没有找到解决办法。

但是在查找资料的过程中发现了另一个处理pdf的开源库iText.官方介绍 /

在这参考了两篇博客

博客1.pdfbox&iText生成PDF文件格式及读取PDF资料内容的小示例-完美支持中文版

博客2.iText生成pdf

iText的功能很强大,用起来也很灵活,我这里只是简单的了解了一下创建一个包含中文的pdf的方法。以后有时间在深入了解。

废话不多说,正题!

下载jar包,官网没找到o(╯□╰)o,jarfire上收录了一些jar包,下载jar包 我下载的是itext-2.0.6.jar.zip

上代码

1 package pdf.itext; 2 3 import java.awt.Color; 4 import java.io.File; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 import com.lowagie.text.Document; 9 import com.lowagie.text.DocumentException;10 import com.lowagie.text.Font;11 import com.lowagie.text.PageSize;12 import com.lowagie.text.Paragraph;13 import com.lowagie.text.Rectangle;14 import com.lowagie.text.pdf.BaseFont;15 import com.lowagie.text.pdf.PdfWriter;16 17 public class Handler {18private static String CHINESE_FONT = "SIMFANG.TTF";//仿宋字体,在C:/Windows/fonts里找的font文件放到src目录下,参见 博客119public static final Rectangle PAGE_SIZE = PageSize.A4;20public static final float MARGIN_LEFT = 50;21public static final float MARGIN_RIGHT = 50;22public static final float MARGIN_TOP = 50;23public static final float MARGIN_BOTTOM = 50;24public static final float SPACING = 20;25 26public static void createPDF(String fileName,String content) throws DocumentException, IOException {27 File file = new File(fileName);//生成的文件28 FileOutputStream fout = new FileOutputStream(file);//输出流29 Document document = new Document(PAGE_SIZE, MARGIN_LEFT, MARGIN_RIGHT, MARGIN_TOP, MARGIN_BOTTOM);//页面大小以及布局30 PdfWriter.getInstance(document, fout);//将文档添加的输出流31 document.open();//打开文档准备写入32 BaseFont baseFont = BaseFont.createFont(CHINESE_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//创建一个支持中文的字体33 Font chinese = new Font(baseFont, 20, Font.BOLDITALIC, Color.red);//博客1里的BaseColor在我下载的jar包中没有就用java.awt.color代替了34 document.add(new Paragraph(content, chinese));//写入内容35 document.close();//关闭文档36}37public static void main(String[] args) throws DocumentException, IOException {38 createPDF("apdf.pdf", "正在使用iText创建一个包含中文的pdf文档!");39}40 }

不同版本的jar包,差异应该还挺大的,我的代码中包结构还有方法等和博客1的差异比较大,和博客2的基本一致。

相关信息官网肯定,由于时间问题没有仔细查看。留后吧(*^__^*) 。

写入内容 方法比较多,创建pdf也很具体详细,很灵活。

TO BE CONTINUED……

如果觉得《iText创建一个含有中文的pdf文档》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。