Java实现PDF文件转换为图片文件

    近期项目中有一个业务场景,需要把PDF文件转换为png格式的图片,然后在图片上实现电子签名操作,以下是pdf转图片的代码实现;

/***
 * PDF文件转图片
 * @param filePath
 * @throws IOException
 * @throws PDFException
 * @throws PDFSecurityException
 * @throws InterruptedException
 */
public static String pdf2Image(String filePath) throws IOException, PDFException, PDFSecurityException, InterruptedException {
   if (filePath.isEmpty()){
       System.err.println("PDF转图片:传入的pdf路径为空!");
       return null;
   }
    Document document = new Document();
    document.setFile(filePath);
    float scale = 2.0f;//缩放比例
    float rotation = 0f;//旋转角度

    for (int i = 0; i < document.getNumberOfPages(); i++) {
        BufferedImage image = (BufferedImage)
                document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
        RenderedImage rendImage = image;
        try {
           
            File file = new File("输出的图片文件路径");
            ImageIO.write(rendImage, "png", file);
            return file.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        image.flush();
    }
    document.dispose();
    return null;
}

猜你喜欢

转载自blog.csdn.net/qq_38114563/article/details/81383078
今日推荐