最近帮公司写了好多小脚本处理Excel和Pdf,在此记录一下,以备下次使用还能找得到如何实现的,开发过程中主要使用pdfbox实现PDF页面的添加删除操作,Maven依赖如下:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
读取PDF页面内容实现步骤
-
读取PDF文件,创建文件输入流。
String filePath = "D:\\Download\\test.pdf"; FileInputStream fileInputStream = new FileInputStream(new File(filePath); PDDocument document = PDDocument.load(fileInputStream); -
创建PDFTextStripper对象,读取页面的文本内容
使用PDFTextStripper对象需要引入一个Maven依赖<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>fontbox</artifactId> <version>2.0.24</version> </dependency>创建
PDFTextStripper对象,设置要读取第几页到第几页的文本内容,下面的示例中读取第一页的文本内容PDFTextStripper ps = new PDFTextStripper(); ps.setStartPage(1); ps.setEndPage(1); String content = ps.getText(document);
添加新的PDF页面实现步骤
读取PDF文件,创建文件输入流不做演示,这里默认已经创建了文档对象PDDocument
- 加载字体对象
因为内容需要指定字体,所以要创建一个字体对象PDType0FontPDType0Font font = PDType0Font.load(document, new File("D:\\Download\\ZiTiChuanQiNanAnTi-MianFeiShangYong-2.ttf")); - 创建一个新的页面添加到document
PDPage page = new PDPage(); document.addPage(page); - 创建一个PDF页面内容操作流,用来向页面上添加文本内容
showText()用来在页面上添加文本内容,但是必须要在语句前后分别调用beginText()和endText()方法,并且必须调用setFont()方法来设置内容的字体,否则运行会出错!PDPageContentStream contentStream=new PDPageContentStream(document, page); contentStream.beginText(); contentStream.newLineAtOffset(25, 700); contentStream.setFont(font, 14); contentStream.showText("你好"); contentStream.endText(); contentStream.close(); - 保存PDF文档对象到指定文件
document.save("D:\\Download\\newTest.pdf");
删除PDF指定页面实现步骤
删除文件比较简单,只需要调用
document.removePage(index)方法,传入要删除的页码即可,删除后将document对象保存到指定文件。这里创建文件的步骤不做演示,这里就默认已经创建了文档对象PDDocument。
document.removePage(i);
document.save("D:\\Download\\newTest.pdf");