编程语言
首页 > 编程语言> > java PDF转图片

java PDF转图片

作者:互联网

pdf转图片
创建一个maven项目
添加icepdf依赖

<!-- https://mvnrepository.com/artifact/org.icepdf.os/icepdf-core -->
<dependency>
      <groupId>org.icepdf.os</groupId>
      <artifactId>icepdf-core</artifactId>
      <version>6.2.2</version>
  </dependency>

代码实现如下:

package com.jl.java.base.upload;

/**
 * @author :heyaolei
 * @date :2021/10/8
 */
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

/**
 * PDF 转 图片
 */
public class IcePdf {
    public static void pdf2Pic(String pdfPath, String path) throws Exception {
        Document document = new Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        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 {
                //String imgName = i + ".png";
                File pdfFile =new File( pdfPath.trim());
                String imgName = pdfFile.getName();
                imgName =  imgName.substring(0,imgName.indexOf("."))+".png";
                System.out.println(imgName);
                File file = new File(path + imgName);
                ImageIO.write(rendImage, "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
    }
    public static void main(String[] args) throws Exception {
        String filePath = "D:/Users/heyaolei/Desktop/useless/20211008/pdf/电子发票.pdf";
        pdf2Pic(filePath, "D:/Users/heyaolei/Desktop/useless/20211008/pdf/");
    }
}

 

 

参考文档:https://www.jianshu.com/p/2242c0a4d348

标签:imgName,java,String,image,icepdf,import,PDF,图片
来源: https://www.cnblogs.com/zhougongjin/p/15379582.html