您的位置:首页 > 其它

将PDF转换为图片(支持PDF含有多页内容)

2017-03-15 17:40 411 查看
/***

* @param source 源文件
* @param target 目标文件
* @param n 缩放系数
*/
private static void changePdfToImg(String source,String target,int n) {

        try {

            File file = new File(source);

            RandomAccessFile raf = new RandomAccessFile(file, "r");

            FileChannel channel = raf.getChannel();

            MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

            PDFFile pdffile = new PDFFile(buf);

            BufferedImage tag = new BufferedImage(595 * 2, 842 * 2 * pdffile.getNumPages(), BufferedImage.TYPE_INT_RGB);

            for (int i = 1; i <= pdffile.getNumPages(); i++) {

                PDFPage page = pdffile.getPage(i);

                java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox()  

                        .getWidth(), (int) page.getBBox().getHeight()); 

                java.awt.Image img = page.getImage((int)rect.getWidth()* n, (int)rect.getHeight() * n, rect,

                null,

                true,

                true

                );

                tag.getGraphics().drawImage(img, 0, (i-1)*rect.height*n, rect.width * n, rect.height * n, null);

            }

            FileOutputStream out = new FileOutputStream(target);

            ImageIO.write(tag, "jpg", out);

            out.close();
       channel.close();
       raf.close();
       buf.clear();

        } catch(FileNotFoundException e) {

            e.printStackTrace();

        } catch(IOException e) {

            e.printStackTrace();

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: