【JAVA】pdf转图片

最近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

posted @ 2017-07-31 18:50  让我发会呆  阅读(3571)  评论(2编辑  收藏  举报