最近java项目中使用到了pdf转图片的需求,在此记录一下。java
1.基于GhostScriptapp
使用此方法要求运行环境安装GhostScript。转换使用的命令是:gs -sDEVICE=pngalpha -o %03d.png -sDEVICE=pngalpha -r144 test.pdfui
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.htmspa
2.基于ImageMagick3d
可是我项目中是但愿把有多页文件的pdf转为一张图片,GhostScript老是把它转为多张图片(我网上找了好久,没找到转为一张图片的命令,若是有小伙伴们有知道的,还但愿分享下),因此我又在网上找到了ImageMagick,主要是找到了能够把整个pdf转为一张图片的命令,code
具体执行命令为:convert test.pdf -append -flatten test.pnghtm
固然须要安装ImageMagick,blog
安装命令为:yum install ImageMagick ImageMagick-devel图片