java PDF转图片

依赖(我用的版本是6.2.2):

<dependency>
    <groupId>org.icepdf.os</groupId>
    <artifactId>icepdf-core</artifactId>
</dependency>

 

    /**
     * 创建人: Tany
     * @param pdfFile
     * @param dirName
     * @param imgName
     * @param scale    缩放比
     * @param rotation 旋转,只有以下值有效:0.0f、90.0f、180.0f、270.0f
     * @return
     */
    public static List<JsonRet> pdfToImages(String pdfFile, String dirName, String imgName, float rotation, float scale) {
        Document document = new Document();
        try {
            document.setFile(pdfFile);
            if (document.getNumberOfPages() <= 0) {
                return new ArrayList<>();
            }
            List<JsonRet> result = new ArrayList<>(document.getNumberOfPages());
            JsonRet path = getPath(dirName);
            Stream.iterate(0, i -> i + 1).limit(document.getNumberOfPages()).forEach(i -> {
                try {
                    BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
                    RenderedImage rendImage = image;
                    String fileName = imgName + i + DEFAULT_SUFFIX;
                    File file = new File(path.get("realPath") + "/" + fileName);
                    ImageIO.write(rendImage, "PNG", file);
                    image.flush();
                    result.add(JsonRet.create("path", path.get("path") + "/" + fileName).set("realPath", path.get("realPath") + "/" + fileName));
                } catch (Exception e) {
                    throw new RuntimeException("PDF转图片第" + i + "页出错啦!", e);
                }
            });
            return result;
        } catch (Exception e) {
            logger.error("PDF转图片出错啦!", e);
            throw new RuntimeException("PDF转图片出错啦!", e);
        } finally {
            document.dispose();
        }
    }

    /**
     * 生成保存图片的文件夹路径
     *
     * @param folder
     * @return
     */
    public static JsonRet getPath(String folder) {
        Calendar currentDate = Calendar.getInstance();
        int year = currentDate.get(Calendar.YEAR);
        int month = currentDate.get(Calendar.MONTH) + 1;
        int day = currentDate.get(Calendar.DAY_OF_MONTH);
        String path = PropKit.get("baseUploadPath") + "/pdf/" + (StringUtils.isNotBlank(folder) ? (folder + "/") : "") + year + "/" + month + "/" + day;
        String realPath = PathKit.getWebRootPath() + "/" + path;
        File file = new File(realPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("生成图片文件夹失败:" + path);
            }
        }
        return JsonRet.ok("path", path).set("realPath", realPath);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值