PDF转成图片

使用开源库Apache PDFBox将PDF转换为图片

依赖


	org.apache.pdfbox
	fontbox
	2.0.4


	org.apache.pdfbox
	pdfbox
	2.0.4
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import javax.imageio.ImageIO;

import cn.hutool.core.lang.UUID;
import com.zxzx.ssm.common.constant.SsmConstant;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

/**
 * @author admin
 */
public class PDFToImageConverter {

    /**
     * 按照页数返回图片-转成BASE64
     */
    public static List pdfToPng(File pdfFile) {
        List list = new ArrayList<>();
        try (PDDocument doc = PDDocument.load(pdfFile)) {
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                File file = new File(SsmConstant.TEMP_PIC + "/" + pdfFile.getName() + "_" + (i + 1) + ".png");
                ImageIO.write(image, "png", file);
                InputStream inputStream = Files.newInputStream(file.toPath());
                byte[] byteArray = IOUtils.toByteArray(inputStream);
                String s = Base64.getEncoder().encodeToString(byteArray);
                list.add(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 转换到同一张图片
     */
    public static String pdfToPngCollect(File file) {
        String outPicPath = SsmConstant.TEMP_PIC + UUID.fastUUID() + ".png";
        try (PDDocument doc = PDDocument.load(file)) {
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            List imageList = new ArrayList<>();
            int height = 0;
            int weight = 0;
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                height += image.getHeight();
                weight = Math.max(weight, image.getWidth());
                imageList.add(image);
            }
            BufferedImage mergedImage = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = mergedImage.createGraphics();
            int accHeight = 0;
            for (BufferedImage image : imageList) {
                g.drawImage(image, 0, accHeight, null);
                accHeight += image.getHeight();
            }
            g.dispose();
            File outputfile = new File(outPicPath);
            ImageIO.write(mergedImage, "jpg", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outPicPath;
    }

}

你可能感兴趣的:(常用工具,pdf)