最近java項目中使用到了pdf轉圖片的需求,在此記錄一下。
1.基於GhostScript
使用此方法要求運行環境安裝GhostScript。轉換使用的命令是:gs -sDEVICE=pngalpha -o %03d.png -sDEVICE=pngalpha -r144 test.pdf
public static List<byte[]> pdf2image(String pdfFilePath) throws Exception{ File tempDir = null; try{ tempDir = Files.createTempDir(); Process proc = new ProcessBuilder("gs", "-sDEVICE=pngalpha", "-o", tempDir + File.separator + "%03d.png", "-sDEVICE=pngalpha", "-r144", pdfFilePath) .redirectErrorStream(true) .start(); ArrayList<String> output = new ArrayList<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = br.readLine()) != null) output.add(line); logger.info("執行gs命令的輸出:" + StringUtils.join(output, System.lineSeparator())); if (0 != proc.waitFor()) throw new Exception("轉換失敗"); File[] files = tempDir.listFiles(); Arrays.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { return f1.getName().compareTo(f2.getName()); } }); List<byte[]> images = new ArrayList<>(); for(File file : files) images.add(IOUtils.toByteArray(new FileInputStream(file))); return images; }finally{ if(tempDir != null) FileUtils.deleteDirectory(tempDir); } }
其中GhostScript還有很多常用的命令,有興趣的可以去看看:https://www.ghostscript.com/doc/current/Use.htm
2.基於ImageMagick
但是我項目中是希望把有多頁文件的pdf轉為一張圖片,GhostScript總是把它轉為多張圖片(我網上找了很久,沒找到轉為一張圖片的命令,如果有小伙伴們有知道的,還希望分享下),所以我又在網上找到了ImageMagick,主要是找到了可以把整個pdf轉為一張圖片的命令,
具體執行命令為:convert test.pdf -append -flatten test.png
當然需要安裝ImageMagick,
安裝命令為:yum install ImageMagick ImageMagick-devel