一、首先是,使用windows字體的正常方式。
@Test /** * 使用windows系統下的字體,new Font方式 */ public void test1_1() throws DocumentException, IOException { String path = "C:/WINDOWS/Fonts/simhei.ttf";//windows里的字體資源路徑 BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, 10f, Font.NORMAL, BaseColor.BLACK); createPdf(font); }
createFont(String name, String encoding, boolean embedded),
1、name參數是字體路徑,該字體是黑體常規,如圖:
2、encoding,是字體的編碼方式,BaseFont.IDENTITY_H在源碼中的意思是:帶有垂直書寫的Unicode編碼,源碼解釋如下:
/** The Unicode encoding with horizontal writing. */ public static final String IDENTITY_H = "Identity-H";
3、embedded,是個boolean值,如果字體要嵌入到PDF中,則為true。
二、如何准確的找到windows下的字體
首先去C:/WINDOWS/Fonts,這個文件夾下來選擇想要使用的字體,例如,使用楷體 常規字體,:
1、右鍵打開屬性,會看到文件名,如圖:

2、復制文件名到代碼中,即可使用。
另外,需要注意的幾點是:
1、有些字體是文件夾,需要打開后才能查看屬性,如圖:

2、有些字體文件后綴名為ttc,是需要多選的,代碼如下:
BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
數字是它有取決於他有幾個可選項,從0開始。
可以打開文件后,通過下一步來查看:

如果數字寫錯,也可以通過報錯信息查看它的范圍:
Exception in thread "main" com.itextpdf.text.DocumentException: The font index for C:/WINDOWS/Fonts/simsun.ttc must be between 0 and 1. It was 3. at com.itextpdf.text.pdf.TrueTypeFont.process(TrueTypeFont.java:656) at com.itextpdf.text.pdf.TrueTypeFontUnicode.process(TrueTypeFontUnicode.java:122) at com.itextpdf.text.pdf.TrueTypeFontUnicode.<init>(TrueTypeFontUnicode.java:99) at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:706) at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:626) at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:461) at pdf.Pdf556Custom.main(Pdf556Custom.java:21)
,它會提示你,只能在0和1中選擇,不能選擇3.
