PDF檔案的二進位制流轉圖片檔案的二進位制流
阿新 • • 發佈:2020-12-27
最近有個客戶要求將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; } }