码迷,mamicode.com
首页 > 编程语言 > 详细

java pdf转图片

时间:2017-07-31 20:10:29      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:com   cep   output   file   pdf转图片   .so   pat   exception   new   

最近项目中使用到了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

java pdf转图片

标签:com   cep   output   file   pdf转图片   .so   pat   exception   new   

原文地址:http://www.cnblogs.com/yxy-ngu/p/7264938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!