maven依賴:java
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.4</version> <scope>test</scope> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency>
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import com.lowagie.text.pdf.PdfReader; public class test1 { public static void main(String[] args) { pdf2Image("D:/1.pdf", "D:/pdf", 130); } /*** * PDF文件轉PNG圖片,所有頁數 * * @param PdfFilePath pdf完整路徑 * @param imgFilePath 圖片存放的文件夾 * @param dpi dpi越大轉換後越清晰,相對轉換速度越慢 * @return */ public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) { File file = new File(PdfFilePath); PDDocument pdDocument; 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)) { pdDocument = PDDocument.load(file); 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(".png"); File dstFile = new File(imgFilePath.toString()); BufferedImage image = renderer.renderImageWithDPI(i, dpi); ImageIO.write(image, "png", 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(); } } }