java之pdf文件转image文件

目录

pom文件

工具类

测试代码


pom文件

<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.28</version>
</dependency>
<!--hutool工具-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.19</version>
</dependency>

工具类

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @描述:
 * @Date: 2023/6/3 15:05
 * @Description: // PC002
 * @Author: Duys
 **/
@Slf4j
public class PdfToImageUtil {

    /**
     * dpi越大转换后越清晰,相对转换速度越慢
     */
    private static final Integer DPI = 100;

    /**
     * 转换后的图片类型
     */
    private static final String IMG_TYPE = "jpg";

    /**
     * PDF转图片
     *
     * @param fileContent PDF文件的二进制流
     * @return 图片文件的二进制流
     */
    public static List<byte[]> pdfToImage(byte[] fileContent) throws IOException {
        List<byte[]> result = new ArrayList<>();
        try (PDDocument document = PDDocument.load(fileContent)) {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); ++i) {
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, IMG_TYPE, out);
                result.add(out.toByteArray());
            }
        }
        return result;
    }

    /**
     * PDF转图片
     *
     * @param fileContent PDF文件的二进制流
     * @return 图片文件的二进制流
     */
    public static byte[] pdfToImage2(byte[] fileContent) throws IOException {
        byte[] result = null;
        try (PDDocument document = PDDocument.load(fileContent)) {
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage bufferedImage = renderer.renderImageWithDPI(0, DPI);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, IMG_TYPE, out);
            result = out.toByteArray();
        }
        return result;
    }

    /**
     * @param imageBytes: 二进制数据
     * @param savePath:   保存的路径
     * @param imageName:  报告名称
     * @描述:
     **/
    public static Boolean saveImage(byte[] imageBytes, String savePath, String imageName) throws IOException {
        try {
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
            File directory = new File(savePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            File outputFile = new File(directory, imageName);
            return ImageIO.write(image, "jpg", outputFile);
        } catch (Exception e) {
            log.error("保存图片报错", e);
            return false;
        }
    }

    public static String createDateDir(String basePath) throws Exception {

        String dayStr = DateUtil.format(DateUtil.date(Calendar.getInstance()), "yyyy-MM-dd");
        String[] dayArr = dayStr.split("-");

        String year = dayArr[0];
        String month = dayArr[1];
        String day = dayArr[2];

        String yearDir = basePath + File.separator + year;

        File yearFile = new File(yearDir);
        if (!yearFile.exists()) {
            yearFile.mkdirs();
        }

        String monthDir = yearDir + File.separator + month;
        File monthFile = new File(monthDir);
        if (!monthFile.exists()) {
            monthFile.mkdirs();
        }

        String dayDir = monthDir + File.separator + day;
        File dayFile = new File(dayDir);
        if (!dayFile.exists()) {
            dayFile.mkdirs();
        }
        //2020\10\15\
        return year + File.separator + month + File.separator + day + File.separator;
    }
    
}

测试代码

public static void main(String[] args) throws IOException {

    byte[] pdfBytes = HttpUtil.downloadBytes("http://127.0.0.1:8080/static/123.pdf");
    byte[] imgBytes = PdfToImageUtil.pdfToImage2(pdfBytes);

    String savePath = "D:\\jfapp\\pdf";
    String imageName = "12121313.jpg";

    try {
        //saveImage(imgBytes, savePath, imageName);
        String path = createDateDir(savePath.concat("/pdf"));
        PdfToImageUtil.saveImage(imgBytes, savePath.concat("\\pdf\\").concat(path), "123.jpg");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java使用com.lowagie.text.pdf插件编写的PDF报表工具类,支持动态报表创建,使用简单,附件中包含了测试类和生成的报表文件。附件中的代码需要修改相关的保存路径后可以直接使用。创建一张报表例子: private JsFileExportResult createRowReport() { String condition = "开始时间:2018-02-02 14:00:30 结束时间:2018-02-06 16:00:30"; PDFGridReport pdfReport = new PDFGridReport("报表创建测试", GridReportTestModel.getModels()); pdfReport.addCondition(condition); pdfReport.header("字段名称1", "item1", 0, 0).width(160); pdfReport.header("字段名称3", "item3", 0, 2).getCell().backgroundColor(Color.ORANGE); pdfReport.header("字段名称4", "item4", 0, 3); pdfReport.header("字段名称5", "item5", 0, 4); pdfReport.header("字段名称2", "item2", 0, 1); pdfReport.header("值", "value", 0, 5).alignH(HAlign.ALIGN_CENTER).getCell().alignH(HAlign.ALIGN_RIGHT); pdfReport.header("时间", "time", 0, 6); pdfReport.header("图片", "image", 0, 7).width(60).alignH(HAlign.ALIGN_CENTER).getCell() .alignH(HAlign.ALIGN_CENTER).alignV(VAlign.ALIGN_MIDDLE); // 横向打印 pdfReport.getPageSetting().setPrintHorizontal(); pdfReport.group("item1").childGroup("item2"); pdfReport.setCellFormat(new PDFCellValueFormat() { @Override public String format(String fieldName, String oriValue) { if ("value".equals(fieldName)) { return String.format("%.2f", Double.parseDouble(oriValue)).toString(); } else { return oriValue; } } }); JsFileExportResult fileResult = pdfReport.createReport(); return fileResult; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值