pdfbox 使用入门[原]
添加依赖
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>fontbox</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>jempbox</artifactId> <version>1.8.11</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>xmpbox</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>preflight</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-tools</artifactId> <version>2.0.0</version> </dependency>
生成pdf并创建背景和创建文本
package com.bobo.code.web.controller.web; 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; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MailApplication { public static void main(String args[]) throws Exception { //Creating PDF document object PDDocument document = new PDDocument(); for (int i=0; i<1; i++) { //Creating a blank page PDPage blankPage = new PDPage(); //Adding the blank page to the document document.addPage( blankPage ); } //Creating PDImageXObject object PDImageXObject pdImage = PDImageXObject.createFromFile("D:/temp/pdf/sisi.png",document); PDPageContentStream pdfPageContent = new PDPageContentStream(document, document.getPage(0)); //Drawing the image in the PDF document pdfPageContent.drawImage(pdImage, 10, 10,400,800); System.out.println("Image inserted"); //Begin the Content stream pdfPageContent.beginText(); //Setting the font to the Content stream pdfPageContent.setFont(PDType1Font.TIMES_ROMAN, 12); //Setting the position for the line pdfPageContent.newLineAtOffset(25, 500); String text = "abc"; //Adding text in the form of string pdfPageContent.showText(text); //Ending the content stream pdfPageContent.endText(); System.out.println("Content added"); //Closing the content stream pdfPageContent.close(); //Saving the document document.save("D:/temp/pdf/sisi.pdf"); System.out.println("PDF created"); //Closing the document document.close(); } }
效果
缺点
对中文不友好,嵌入中文会乱码,需要先添加字体库, 如果还是乱码, 则建议先生成中文模式的图片, 再将图片放到pdf背景指定x,y位置
参考
WIKI教程==>https://iowiki.com/pdfbox/ 非常清晰,强力推荐
使用Apache PDFBox实现拆分、合并PDF==>https://blog.csdn.net/qq_38998209/article/details/127983909
感觉空虚寂寞,只是因为你无所关注,无处付出。