下面是示例代碼
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.BaseColor;
public class Test {
public static void main(String[] args) {
Rectangle pSize = new Rectangle(300, 400);
Document doc = new Document(pSize); //創建文檔
try {
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("testpdf.pdf"));
doc.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); //創建文字字體
BaseFont bfc = BaseFont.createFont("D:/ht.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //創建中文的文字字體,自定義字體文件
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.beginText();
cb.moveText(20, 300); //設置文字的位置
cb.setFontAndSize(bf, 12); //設置文字的大小
cb.setColorFill(BaseColor.RED); //設置文字顏色
cb.showText("this is an English test."); //設置文字內容
cb.endText();
cb.restoreState();
cb.saveState();
cb.beginText();
cb.moveText(20, 280);
cb.setFontAndSize(bfc, 12);
cb.showText("這是一個中文測試。It can also English."); //中文文字的測試
cb.endText();
cb.restoreState();
} catch (DocumentException | IOException e) {
e.printStackTrace();
} finally {
doc.close();
}
}
}