javaPDF转图片
import java.io.FileNotFoundException; import java.io.IOException; @SpringBootApplication @EnableScheduling public class ApplicationProject extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication application = new SpringApplication(new Class<?>[] { ApplicationProject.class }); application.run(args); pdf2Image("F:/tpl.pdf", "F:/pdf2", 300); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(ApplicationProject.class); } /*** * PDF文件转PNG图片,全部页数 * * @param PdfFilePath pdf完整路径 * @param dstImgFolder 图片存放的文件夹 * @param dpi dpi越大转换后越清晰,相对转换速度越慢 * @return */ public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) { File file = new File(PdfFilePath); PDDocument pdDocument = null; try { String imgPDFPath = file.getParent(); int dot = file.getName().lastIndexOf('.'); String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名 String imgFolderPath = null; if (dstImgFolder.equals("")) { imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径 } else { imgFolderPath = dstImgFolder + File.separator + imagePDFName; } if (createDirectory(imgFolderPath)) { try { pdDocument = PDDocument.load(file); } catch (IOException e) { e.printStackTrace(); } PDFRenderer renderer = new PDFRenderer(pdDocument); /* dpi越大转换后越清晰,相对转换速度越慢 */ PdfReader reader = new PdfReader(PdfFilePath); int pages = reader.getNumberOfPages(); StringBuffer imgFilePath = null; for (int i = 0; i < pages; i++) { String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName; imgFilePath = new StringBuffer(); imgFilePath.append(imgFilePathPrefix); imgFilePath.append("_"); imgFilePath.append(String.valueOf(i + 1)); imgFilePath.append(".jpg"); File dstFile = new File(imgFilePath.toString()); BufferedImage image = renderer.renderImageWithDPI(i, dpi); ImageIO.write(image, "jpg", dstFile); } System.out.println("PDF文档转PNG图片成功!"); } else { System.out.println("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败"); } } catch (IOException e) { e.printStackTrace(); } } private static boolean createDirectory(String folder) { File dir = new File(folder); if (dir.exists()) { return true; } else { return dir.mkdirs(); } } }
我要引入一个jar包,我是用maven来管理的,maven引入的方式如下:
1 <!-- PDF转图片 --> 2 <dependency> 3 <groupId>org.apache.pdfbox</groupId> 4 <artifactId>fontbox</artifactId> 5 <version>2.0.1</version> 6 </dependency> 7 <dependency> 8 <groupId>org.apache.pdfbox</groupId> 9 <artifactId>pdfbox</artifactId> 10 <version>2.0.1</version> 11 </dependency>
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

更多精彩