iText生成pdf中文字体

用iText生成pdf时,内容有中文的时候用到中文字体。

直接使用iTextAsian.jar中的字体

BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

或者使用系统字体文件

BaseFont.createFont("C:/WINDOWS/Fonts/simsun.ttc", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

或者把字体文件放到项目使用

BaseFont.createFont("/simsun.ttc", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 

这样就解决了中文不显示的问题,但是使用第一个的时候有一个问题,就是当字符中存在英文的时候看起来不整齐,有的中间会有空格,代码:

Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream("D:/test/test_cn.pdf"));
document.addTitle("中文测试");
document.open();
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(base, 30);
Paragraph p = new Paragraph();
p.setFont(font);
p.add("这是一个段落 hello world");
document.add(p);
Phrase ph = new Phrase("中文测试 My name is Jim Green.", font);
document.add(ph);
document.close();

结果:

iText生成pdf中文字体_第1张图片

这时候可以用到com.itextpdf.text.pdf.FontSelector,根据保存的字体,选择包含正确呈现文本所需的字形的相应字体。 按顺序检查字体,直到找到该字符。

Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream("D:/test/test_cn.pdf"));
document.addTitle("中文测试");
document.open();
FontSelector selector = new FontSelector();
selector.addFont(FontFactory.getFont(FontFactory.TIMES_ROMAN, 30));
selector.addFont(FontFactory.getFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, 30));
Phrase ph = selector.process("中文测试 My name is Jim Green.");
document.add(ph);
document.close();

结果:

iText生成pdf中文字体_第2张图片

你可能感兴趣的:(java)