itextpdf使用itextpdf默认字体
时间: 2025-05-14 13:02:25 浏览: 56
### iTextPDF 默认字体的使用与设置
在 iTextPDF 中,默认情况下使用的字体是标准 PDF 字体之一,这些字体被称为 **Base 14 Fonts**。它们包括 Times-Roman、Helvetica 和 Courier 等字体[^3]。然而需要注意的是,这些默认字体并不支持中文字符集。如果尝试直接渲染中文内容而未指定合适的中文字体,则可能会导致乱码或其他显示问题。
#### 设置默认字体的方法
以下是通过 Java 实现的一个简单示例来展示如何利用 iTextPDF 的默认字体创建 PDF 文档:
```java
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
public class DefaultFontExample {
public static void main(String[] args) throws Exception {
String dest = "./default_font_example.pdf";
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// 添加一段英文文本作为测试数据
Paragraph paragraphEnglish = new Paragraph("This is a test using the default font.");
document.add(paragraphEnglish);
// 尝试添加中文文本(不推荐)
Paragraph paragraphChinese = new Paragraph("这是使用默认字体的一段中文测试");
document.add(paragraphChinese);
document.close();
}
}
```
上述代码会生成一份包含英汉两种语言的 PDF 文件。对于英语部分来说,由于其属于 ASCII 范围内的字符集合,因此能够正常呈现;但对于汉字而言,在没有特别设定适合处理 CJK (Chinese, Japanese, Korean) 编码环境下的字体之前,通常会出现不可读的结果或空白区域[^4]。
#### 解决方案:加载自定义中文字体
为了使 PDF 支持并正确显示中文字符,需引入特定于亚洲语言的支持库以及相应的字型档案文件(.ttf,.otf),例如 `STSong-Light` 或其他兼容 Unicode GB 标准的 TrueType 字形资源。下面给出了一种解决方案的具体实现方式:
```java
import java.io.File;
import java.io.IOException;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
public class ChineseFontExample {
private final static String DEST = "./chinese_font_example.pdf";
public static void main(String[] args) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
try(PdfWriter writer = new PdfWriter(file)){
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc, PageSize.A4.rotate());
// 加载中文字体
PdfFont chineseFont = PdfFontFactory.createFont(
"C:/Windows/Fonts/simsun.ttc",
PdfEncodings.IDENTITY_H,
true
);
// 英文段落保持原样
doc.add(new Paragraph("Default English text without any special settings."));
// 使用 SimSun 宋体 显示中文内容
doc.add(new Paragraph("这是一个带有宋体字体的例子").setFont(chineseFont));
doc.close();
} catch(Exception e){
System.out.println(e.getMessage());
}
}
}
```
此脚本展示了怎样导入外部 TTF 类型的字体档案至项目当中,并将其应用于文档内部的不同元素之上。这里选用 Windows 平台自带的 “SimSun” (宋体)为例说明操作流程[^5]。
### 注意事项
当采用嵌入式字体策略时,请务必确认目标设备上存在相应字体文件或者已随同发布包一同分发出去,否则可能导致最终输出效果不符合预期。
阅读全文
相关推荐


















