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);
    }

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页