PDF文件转为缩略图

工作需求在浏览器预览office文件

最后确定的方案是:

1、首先使用Jacob调取WPS将office文件转为PDF(可以做到兼容office 2003、office 2007的文件);

2、通过如下代码(本人用的spring boot)将PDF文件转为图片(包括首页缩略图、全部所有页缩略图)

3、在预览页面展示首页缩略图,详情页会使用pdf.js获取PDF文件流,将每一页使用画布canvas画到页面上(会在下一篇文章)。

package officeutil.web.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * PDF文件转为缩略图
 * 
 * @author leo.li
 *
 */
@Component("pdf2ImageUtil")
public class Pdf2ImageUtil {

    @Value("${pdf.path}")
    private String pdf_path;
    @Value("${picture.path}")
    private String picture_path;

    // 经过测试,dpi为96,100,105,120,150,200中,105显示效果较为清晰,体积稳定,dpi越高图片体积越大
    // 一般电脑显示分辨率为96
    public static final float DEFAULT_DPI = 105;

    /**
     * 转换PDF文件的某页为图片
     * 
     * @param pdfPath
     */
    public boolean pdfToImage(String pdfFileName, String projectId) {
        try {
            if (pdfFileName == null || "".equals(pdfFileName) || !pdfFileName.endsWith(".pdf"))
                return false;

            String pdfPath = String.format(pdf_path + "/%s/%s", projectId, pdfFileName);
            String picturePath = String.format(picture_path + "/%s/%s", projectId,
                    Tool.getFileNameWithoutSuffix(pdfPath) + ".jpg");
            File picFile = new File(picturePath);
            if (!picFile.getParentFile().exists()) { // 判断文件父目录是否存在
                picFile.getParentFile().mkdir();
            }

            // 利用PdfBox生成图像
            PDDocument pdDocument = PDDocument.load(new File(pdfPath));
            PDFRenderer renderer = new PDFRenderer(pdDocument);

            // 构造图片
            BufferedImage img_temp = renderer.renderImageWithDPI(0, DEFAULT_DPI, ImageType.RGB);
            // 设置图片格式
            Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("jpg");
            // 将文件写出
            ImageWriter writer = (ImageWriter) it.next();
            ImageOutputStream imageout = ImageIO.createImageOutputStream(new FileOutputStream(picturePath));
            writer.setOutput(imageout);
            writer.write(new IIOImage(img_temp, null, null));
            img_temp.flush();
            imageout.flush();
            imageout.close();
            pdDocument.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 全部PDF文件转为图片
     * 
     * @param pdfPath
     */
    @SuppressWarnings("unused")
    private void pdfToImage2(String pdfPath) {
        try {
            if (pdfPath == null || "".equals(pdfPath) || !pdfPath.endsWith(".pdf"))
                return;
            // 图像合并使用参数
            int width = 0; // 总宽度
            int[] singleImgRGB; // 保存一张图片中的RGB数据
            int shiftHeight = 0;
            BufferedImage imageResult = null;// 保存每张图片的像素值
            // 利用PdfBox生成图像
            PDDocument pdDocument = PDDocument.load(new File(pdfPath));
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            // 循环每个页码
            for (int i = 0, len = pdDocument.getNumberOfPages(); i < len; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
                int imageHeight = image.getHeight();
                int imageWidth = image.getWidth();
                if (i == 0) {// 计算高度和偏移量
                    width = imageWidth;// 使用第一张图片宽度;
                    // 保存每页图片的像素值
                    imageResult = new BufferedImage(width, imageHeight * len, BufferedImage.TYPE_INT_RGB);
                } else {
                    shiftHeight += imageHeight; // 计算偏移高度
                }
                singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
                imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
                break;
            }
            pdDocument.close();
            File outFile = new File(pdfPath.replace(".pdf", "_" + DEFAULT_DPI + ".jpg"));
            ImageIO.write(imageResult, "jpg", outFile);// 写图片
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值