java 使用itext導出PDF文件,中文不顯示問題解決

之前寫的java 使用itext 導出pdf 發現有個問題,在今天使用的時候,發現一個問題,就是當單元格中寫中文的時候,導出來的pdf中文不顯示。
java 使用itext導出PDF文件,圖片文字左右佈局
解決辦法:設置字體格式,兼容中文字符。
如下:

 	//新增改進代碼 -------------------------------
	BaseFont bfChinese = BaseFont.createFont("C:\\Windows\\Fonts\\simsun.ttc,1",  BaseFont.IDENTITY_H, 	BaseFont.NOT_EMBEDDED);//1 不能省略
	 Font fontChinese = new Font(bfChinese, 10, Font.NORMAL);
	 // ------------------------
	 //3、創建左邊數據表格PdfPTable iTable,劃分爲N列

	 PdfPTable leftTable = new PdfPTable(4);//創建左邊表格
	 //4、往左邊表格中寫入數據,加入iTable中
	 //4-1表格中可以合併單元格
	 PdfPCell leftCell = new PdfPCell(new Paragraph("Hello"));
	 leftCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	 leftCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	 leftCell.setFixedHeight(lineHeight1);
	 leftCell.setColspan(4);
	 leftTable.addCell(leftCell);
	 //4-2填充數據
		for(int i=0;i<24;i++){
			//此處爲改進代碼,在進行寫入中文測試的時候,增加對中文的兼容。
			 leftCell = new PdfPCell(new Paragraph("測試",fontChinese));
			 leftCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			 leftCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			 leftCell.setFixedHeight(lineHeight2);
			 leftTable.addCell(leftCell);
		}

遇到問題:com.lowagie.text.DocumentException: Font ‘C:\Windows\Fontssimsun.ttc’ with ‘Identity-H’ is not recognized.
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
at com.lowagie.text.pdf.BaseFont.createFont(Unknown Source)
at MergeCell.main(MergeCell.java:4

解決方案:
BaseFont bfChinese = BaseFont.createFont(“C:\Windows\Fonts\simsun.ttc,1”, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//1 不能省略,省略會報以上錯誤。
Font fontChinese = new Font(bfChinese, 10, Font.NORMAL);

暫不知道爲何在使用本地字體後方需要加個數字。
在實際使用項目過程中,將該字體放入項目根路徑,修改上方的路徑即可。

參考文章:https://www.cnblogs.com/LUA123/p/5108007.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章