Java实现pdf转图片,分享给大家
pom.xml内容为:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>pdf2img</groupId> <artifactId>pdf2img</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.4</version> </dependency> </dependencies> </project>
单个pdf文件转图片Java代码如下:
public static List<String> pdfToImagePath(String filePath) { List<String> list = new ArrayList<String>(); String fileDirectory = filePath.substring(0, filePath.lastIndexOf("."));//获取去除后缀的文件路径 String imagePath; File file = new File(filePath); try { File f = new File(fileDirectory); if (!f.exists()) { f.mkdir(); } PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { // 方式1,第二个参数是设置缩放比(即像素) // BufferedImage image = renderer.renderImageWithDPI(i, 296); // 方式2,第二个参数是设置缩放比(即像素) BufferedImage image = renderer.renderImage(i, 1.25f); //第二个参数越大生成图片分辨率越高,转换时间也就越长 imagePath = fileDirectory + "/" + i + ".jpg"; ImageIO.write(image, "PNG", new File(imagePath)); list.add(imagePath); } } catch (IOException e) { e.printStackTrace(); } return list; }
多个pdf文件转图片Java代码如下:
public static void main(String[] args) { ArrayList<String> list=getDirPathFiles("D:\\pdf\\3"); for(int i=0;i<list.size();i++){ try { String filePath = list.get(i); System.out.println(list.size() + "//" + i + "//" + filePath); pdfToImagePath(filePath, "D:\\pdf\\3save", "3-"+i + ""); }catch (Exception e){ e.printStackTrace(); continue; } } } public static List<String> pdfToImagePath(String filePath,String savePath,String subStr) { List<String> list = new ArrayList<String>(); String fileDirectory = filePath.substring(0, filePath.lastIndexOf("."));//获取去除后缀的文件路径 String imagePath; File file = new File(filePath); try { File f = new File(fileDirectory); if (!f.exists()) { f.mkdir(); } PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { // 方式1,第二个参数是设置缩放比(即像素) // BufferedImage image = renderer.renderImageWithDPI(i, 296); // 方式2,第二个参数是设置缩放比(即像素) BufferedImage image = renderer.renderImage(i, 1.25f); //第二个参数越大生成图片分辨率越高,转换时间也就越长 imagePath = savePath + "/"+subStr+"-" + i + ".jpg"; ImageIO.write(image, "PNG", new File(imagePath)); list.add(imagePath); } } catch (Exception e) { e.printStackTrace(); } return list; } //获取文件夹下所有文件 public static ArrayList getDirPathFiles(String path) { ArrayList files = new ArrayList<String>(); File file = new File(path); File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { files.add(tempList[i].toString()); } } return files; }