PDF文件的二進制流轉圖片文件的二進制流


最近有個客戶要求將pdf轉成圖片保存在桶

首先我們來實現pdf字節流轉成img字節流

第一步:pom.xml中引入:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.20</version>
</dependency>

第二步:代碼實現:

package com.ulic.gis.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM