spire.pdf支持标准字体、truetype字体和cjk字体。本教程展示如何在pdf页面绘制文本时应用这些字体。
import com.spire.pdf.graphics.*;
public class pdffonts {
public static void main(string[] args) {
//创建pdfdocument对象
pdfdocument doc = new pdfdocument();
//添加一页
pdfpagebase page = doc.getpages().add();
//创建画刷
pdfbrush brush = pdfbrushes.getblack();
//初始化y坐标
float y = 30;
//使用standard字体绘制文字
pdffont standardfont = new pdffont(pdffontfamily.helvetica, 14f);
page.getcanvas().drawstring("standard font - helvetica", standardfont, brush, 0, y);
standardfont = new pdffont(pdffontfamily.times_roman, 14f);
page.getcanvas().drawstring("standard font - times_roman", standardfont, brush, 0, (y = y 16));
standardfont = new pdffont(pdffontfamily.courier, 14f);
page.getcanvas().drawstring("standard font - courier", standardfont, brush, 0, (y = y 16));
//使用true type字体绘制文字
java.awt.font font = new java.awt.font("arial", java.awt.font.bold, 14);
pdftruetypefont truetypefont = new pdftruetypefont(font);
page.getcanvas().drawstring("truetype font - arial", truetypefont, brush, 0, (y = y 30f));
//使用私有字体绘制文字
string fontfilename = "c:\\users\\administrator\\desktop\\khadija.ttf";
truetypefont = new pdftruetypefont(fontfilename, 14f);
page.getcanvas().drawstring("private font - khadija", truetypefont, brush, 0, (y = y 30f));
//使用cjk字体绘制文字
pdfcjkstandardfont cjkfont = new pdfcjkstandardfont(pdfcjkfontfamily.monotype_hei_medium, 14f);
page.getcanvas().drawstring("how to say 'font' in chinese? \u5b57\u4f53", cjkfont, brush, 0, (y = y 30f));
cjkfont = new pdfcjkstandardfont(pdfcjkfontfamily.hanyang_systems_gothic_medium, 14f);
page.getcanvas().drawstring("how to say 'font' in japanese? \u30d5\u30a9\u30f3\u30c8", cjkfont, brush, 0, (y = y 16f));
cjkfont = new pdfcjkstandardfont(pdfcjkfontfamily.hanyang_systems_shin_myeong_jo_medium, 14f);
page.getcanvas().drawstring("how to say 'font' in korean? \uae00\uaf34", cjkfont, brush, 0, (y = y 16f));
//保存文档
doc.savetofile("fonts.pdf");
doc.close();
}
}