在上一章中,我们讨论了如何将页面添加到PDF文档中.在本章中,我们将讨论如何将文本添加到现有PDF文档.
您可以添加内容对于使用PDFBox库的文档,这为您提供了一个名为PDPageContentStream的类,其中包含在PDFDocument的页面中插入文本,图像和其他类型内容所需的方法.
关注是创建空文档并向其中的页面添加内容的步骤.
您可以加载使用PDDocument类的 load()方法的现有文档.因此,实例化此类并加载所需的文档,如下所示.
File file = new File("Path of the document"); PDDocument doc = document.load(file);
您可以使用在文档中获取所需页面getPage()方法.通过将索引传递给此方法来检索所需页面的对象,如下所示.
PDPage page = doc.getPage(1);
您可以使用类的对象插入各种数据元素 PDPageContentStream .您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递前面步骤中创建的这两个对象来实例化此类,如下所示.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
在PDF文档中插入文本时,可以指定开始和结束使用PDPageContentStream类的beginText()和endText()方法的文本点,如下所示.
contentStream.beginText(); ……………………….. code to add text content ……………………….. contentStream.endText();
因此,请使用 beginText()方法开始文本,如下所示.
contentStream.beginText();
使用 newLineAtOffset()方法,您可以在页面中的内容流上设置位置.
//Setting the position for the line contentStream.newLineAtOffset(25, 700);
您可以使用
contentStream.setFont( font_type, font_size );
您可以使用 ShowText将文本插入页面( ) PDPageContentStream 类的方法,如下所示.此方法以字符串形式接受所需文本.
contentStream.showText(text);
插入文本后,需要使用
contentStream.endText() ;
使用<b关闭 PDPageContentStream 对象> close()方法如下所示.
contentstream.close();
添加所需内容后,使用保存PDF文档 PDDocument 类的save()方法,如以下代码块所示.
doc.save("Path");
最后,使用关闭() PDDocument 类的方法,如下所示.
doc.close();
此示例演示如何向文档中的页面添加内容.在这里,我们将创建一个Java程序来加载名为 my_doc.pdf 的PDF文档,该文档保存在路径 C:/PdfBox_Examples/中,并为其添加一些文本.将此代码保存在名为 AddingContent.java 的文件中.
import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; public class AddingContent { public static void main (String args[]) throws IOException { //Loading an existing document File file = new File("C:/PdfBox_Examples/my_doc.pdf"); PDDocument document = PDDocument.load(file); //Retrieving the pages of the document PDPage page = document.getPage(1); PDPageContentStream contentStream = new PDPageContentStream(document, page); //Begin the Content stream contentStream.beginText(); //Setting the font to the Content stream contentStream.setFont(PDType1Font.TIMES_ROMAN, 12); //Setting the position for the line contentStream.newLineAtOffset(25, 500); String text = "This is the sample document and we are adding content to it."; //Adding text in the form of string contentStream.showText(text); //Ending the content stream contentStream.endText(); System.out.println("Content added"); //Closing the content stream contentStream.close(); //Saving the document document.save(new File("C:/PdfBox_Examples/new.pdf")); //Closing the document document.close(); } }
使用以下命令从命令提示符编译并执行保存的Java文件.
javac AddingContent.java java AddingContent
执行时,上述程序添加给定文本到文档并显示以下消息.
Content added
如果您在指定路径中验证PDF文档 new.pdf ,您可以观察到给定内容已添加到文档中,如下所示.