如何使用 Java 格式化 PDF 中的文本
问题描述
如何使用 Java 格式化 PDF 中的文本。
解决方案
以下是使用 Java 格式化 PDF 中的文本的程序。
import com.itextpdf.io.font.FontConstants; import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Text; public class FormatTextInPdf { public static void main(String args[]) throws Exception { String file = "C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf"; //创建一个 PdfDocument 对象 PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); //创建一个文档对象 Document doc = new Document(pdfDoc); //向文档添加文本 Text text1 = new Text("Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms."); //设置文本颜色 text1.setFontColor(Color.RED); //设置文本的字体 text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); //创建段落 1 Paragraph para1 = new Paragraph(text1); Text text2 = new Text("The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more."); //设置文本颜色 text2.setFontColor(Color.RED); //设置文本的字体 text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); //创建段落 2 Paragraph para2 = new Paragraph(text2); //向文档添加段落 doc.add(para1); doc.add(para2); //关闭文档 doc.close(); System.out.println("Text added successfully.."); } }
输出

java_itext.html