目录

如何使用Java将文本作为段落添加到PDF文档中。(How to add text to a PDF document as paragraphs using Java.)

问题描述 (Problem Description)

如何使用Java将文本作为段落添加到PDF文档中。

解决方案 (Solution)

以下是使用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 AddingParagraphsToPdf { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf"; 
      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));     
      //Creating a Document object 
      Document doc = new Document(pdfDoc);        
      //Adding text to the document 
      Text text1 = new Text("IOWIKI 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.");
      //Setting color to the text 
      text1.setFontColor(Color.RED); 
      //Setting font to the text  
      text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 
      //Creating a paragraph 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.");  
      //Setting color to the text 
      text2.setFontColor(Color.RED); 
      //Setting font to the text  
      text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 
      //Creating a paragraph 2 
      Paragraph para2 = new Paragraph(text2); 
      //Adding paragraphs to the document 
      doc.add(para1);
      doc.add(para2); 
      //Closing the document 
      doc.close(); 
      System.out.println("Text added successfully.."); 
   } 
}

输出 (Output)

添加文字
↑回到顶部↑
WIKI教程 @2018