- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单的图形用户界面
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用资源
- Java - 快速指南
- Java - 有用资源
如何使用 Java 向 PDF 中添加文本
问题描述
如何使用 Java 向 PDF 中添加文本。
解决方案
以下是使用 Java 向 PDF 文档中添加文本的示例程序。
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 AddingTextToAPdf {
public static void main(String args[]) throws IOException {
//Loading an existing document
PDDocument doc = PDDocument.load(new File("C:/pdfBox/AddText_IP.pdf"));
//Creating a PDF Document
PDPage page = doc.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
//Setting the position for the line
contentStream.newLineAtOffset(25, 725 );
String text = "This is an example of adding text to a page in the pdf document.
we can add as many lines as we want like this using the draw string method
of the ContentStream class";
//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
doc.save(new File("C:/pdfBox/AddText_OP.pdf"));
//Closing the document
doc.close();
}
}
输入
输出
java_apache_pdf_box
广告