Java如何在iText中为文本对象定义字体?
我们可以设置为文本对象,如字体样式Chunk,Phrase,Paragraph,等用com.itextpdf.text.Font类。我们可以使用此类定义字体的外观,大小,样式及其颜色。
package org.nhooo.example.itextpdf; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class FontDemo { public static void main(String[] args) { Document doc = new Document(); try { PdfWriter.getInstance(doc, new FileOutputStream("FontDemo.pdf")); doc.open(); //创建一些字体 Font largeBold = new Font(Font.FontFamily.COURIER, 32, Font.BOLD); Font smallItalic = new Font(Font.FontFamily.HELVETICA, 10, Font.ITALIC); Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.ITALIC | Font.UNDERLINE, BaseColor.RED); //用字体创建块,短语和段落 //信息。 Chunk chunk = new Chunk("Hello World", largeBold); Phrase phrase = new Phrase("The quick brown fox ", smallItalic); Paragraph paragraph = new Paragraph("jumps over the lazy dog", redFont); doc.add(chunk); doc.add(phrase); doc.add(paragraph); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { doc.close(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency>