java實現PDF轉圖片(每頁轉換成一張圖片,可單頁轉換或指定頁數)
阿新 • • 發佈:2018-12-26
話不多說,直接上程式碼
本方案使用的是PDFbox jar包,使用的是JDK1.8。public class PDF2IMAGE { public static void main(String[] args) { if(args!=null && args.length>=4) { String pdfPath = args[0]; String imgPath = args[1]; int dpi = Integer.parseInt(args[2]); int flag = Integer.parseInt(args[3]); File file = new File(pdfPath); if(file.isFile()&&file.exists()) { pdf2Image(pdfPath, imgPath, dpi,flag); } } //pdf2Image("D:/hvdGBFLoo.pdf", "D:/pdf", 300,2); } /*** * PDF檔案轉PNG圖片 * @param PdfFilePath pdf完整路徑 * @param imgFilePath 圖片存放的資料夾 * @param dpi dpi越大轉換後越清晰,相對轉換速度越慢 * @param flag 頁數 為0則轉換全部頁數 * @return */ public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi,int flag) { 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 ; } else { imgFolderPath = dstImgFolder; } if (createDirectory(imgFolderPath)) { pdDocument = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(pdDocument); int pages = pdDocument.getNumberOfPages(); if(flag > 0) {//大於0則列印具體頁數 if(flag<pages) { pages = flag; } } 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("success"); } else { System.out.println("error:" + "creat" + imgFolderPath + "wrong"); } } catch (Exception e) { System.out.println("Exception"); e.printStackTrace(); } } private static boolean createDirectory(String folder) { File dir = new File(folder); if (dir.exists()) { return true; } else { return dir.mkdirs(); } } }