Springboot使用pdfbox提取PDF圖片的代碼示例
PDFBox的介紹
PDFBox是一個用于創(chuàng)建和處理PDF文檔的Java庫。它可以使用Java代碼創(chuàng)建、讀取、修改和提取PDF文檔中的內(nèi)容。
PDFBox的功能:
Extract Text - 使用PDFBox,您可以從PDF文件中提取Unicode文本。
Split & Merge - 使用PDFBox,您可以將單個PDF文件分成多個文件,并將它們合并為一個文件。
Fill Forms - 使用PDFBox,您可以在文檔中填寫表單數(shù)據(jù)。
Print - 使用PDFBox,您可以使用標準Java打印API打印PDF文件。
Save as Image - 使用PDFBox,您可以將PDF保存為圖像文件,如PNG或JPEG。
Create PDFs - 使用PDFBox,您可以通過創(chuàng)建Java程序創(chuàng)建新的PDF文件,還可以包含圖像和字體。
Signing - 使用PDFBox,您可以將數(shù)字簽名添加到PDF文件。
Springboot集成PDFBox
本項目除了引入pdfbox的依賴之外,還引入了解決圖像問題的其他依賴。
例如:jai-imageio-jpeg2000
和jai-imageio-core
是為了解決在轉(zhuǎn)換圖像時報錯:Cannot read JPEG2000 image: Java Advanced Imaging (JAI) Image I/O Tools are not installed
jbig2-imageio
依賴引入是為了解決使用pdfbox2.0將PDF轉(zhuǎn)換為圖片時后臺報Cannot read JBIG2 image: jbig2-imageio is not installed
錯誤
<!-- pdf提取封面依賴--> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.22</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-tools</artifactId> <version>2.0.22</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>jbig2-imageio</artifactId> <version>3.0.2</version> </dependency> <!-- 解決提取pdf "Cannot read JPEG2000 image"封面失敗問題 --> <dependency> <groupId>com.github.jai-imageio</groupId> <artifactId>jai-imageio-core</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com.github.jai-imageio</groupId> <artifactId>jai-imageio-jpeg2000</artifactId> <version>1.3.0</version> </dependency>
一、提取pdf首頁為圖像
1. 實現(xiàn)需求
單個或者批量提取pdf的首頁作為封面,或者可以實現(xiàn)提取指定pdf頁為圖像
2. 項目代碼
核心工具類方法:PdfUtils.getPdfFirstImage
package com.zhouquan.utils; import lombok.extern.slf4j.Slf4j; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; /** * @author ZhouQuan * @desciption pdf工具類 * @date 2023/6/17 9:52 */ @Slf4j public class PdfUtils { /** * 提取pdf首頁作為封面 * * @param pdfFile * @param dpi the DPI (dots per inch) to render at * @return */ public static BufferedImage getPdfFirstImage(File pdfFile, float dpi) { long startTime = System.currentTimeMillis(); if (!pdfFile.isFile() || !pdfFile.exists()) { return null; } try (PDDocument document = PDDocument.load(pdfFile)) { PDFRenderer pdfRenderer = new PDFRenderer(document); // 設置頁數(shù)(首頁從0開始)、每英寸點數(shù)、圖片類型 BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, dpi, ImageType.RGB); log.info("提取耗時:{}ms", System.currentTimeMillis() - startTime); return bufferedImage; } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); return null; } } }
service方法類,負責將讀取的pdf的bufferedImage對象寫入指定的圖片對象中
package com.zhouquan.service.impl; import com.zhouquan.service.PdfService; import com.zhouquan.utils.PdfUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.pdfbox.tools.imageio.ImageIOUtil; import org.springframework.stereotype.Service; import java.awt.image.BufferedImage; import java.io.File; /** * @author ZhouQuan * @desciption pdf提取相關類 * @date 2023/6/17 9:40 */ @Slf4j @Service public class PdfServiceImpl implements PdfService { /** * 提取封面的存放路徑 */ private static String coverPath = "D:/pdf_test/cover"; /** * 提取封面的文件后綴 */ private static final String coverExt = "png"; /** * pdf 提取封面 * * @param pdfFile pdf文件 */ @Override public void pickupCover(File pdfFile) { //要渲染的DPI(每英寸點數(shù)),可以理解為生成圖片的清晰度,值越高生成質(zhì)量越高 int dpi = 300; try { //提取封面工具類 BufferedImage bufferedImage = PdfUtils.getPdfFirstImage(pdfFile, dpi); //獲取pdf文件名 String fileName = FilenameUtils.getBaseName(pdfFile.getName()); String currentCoverPath = coverPath + "/" + fileName + "." + coverExt; // 創(chuàng)建圖片文件對象 FileUtils.createParentDirectories(new File(currentCoverPath)); // 將圖片寫入到圖片對象中 ImageIOUtil.writeImage(bufferedImage, currentCoverPath, dpi); byte[] coverByte = PdfUtils.bufferedImageToByteArray(bufferedImage); log.info("提取封面大小為: {}MB", String.format("%.2f", coverByte.length / 1024 / 1024.0)); } catch (Exception e) { log.error(e.getMessage()); } } }
測試類
package com.zhouquan; import com.zhouquan.service.PdfService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.io.File; @SpringBootTest public class PdfTests { @Resource public PdfService pdfService; /** * 提取單個文件封面 */ @Test public void pickupCover() { String pdfFilePath = "D:/pdf_test/pdf/三體三部曲-劉慈欣.pdf"; pdfService.pickupCover(new File(pdfFilePath), 0); } /** * 批量單個文件封面 */ @Test public void batchPickupCover() { String pdfFilePath = "E:/開發(fā)項目/h化工出版社/opt"; File[] files = new File(pdfFilePath).listFiles(); if (files != null && files.length > 0) { for (File file : files) { pdfService.pickupCover(file, 0); } } } }
3. 執(zhí)行結(jié)果
1.單本pdf提取封面
2.批量提取pdf封面
二、將pdf內(nèi)容全部轉(zhuǎn)換為圖像
1. 實現(xiàn)需求
將pdf中所有的頁轉(zhuǎn)換為圖片
2. 項目代碼
核心工具類方法:PdfUtils.getPdfAllImage
/** * 加載讀取pdf并返回所有的BufferedImage對象 * * @param pdfFile pdf文件對象 * @param dpi the DPI (dots per inch) to render at * @return */ public static List<BufferedImage> getPdfAllImage(File pdfFile, float dpi) { if (!pdfFile.isFile() || !pdfFile.exists()) { return null; } //創(chuàng)建PDFDocument對象并加載PDF文件 try (PDDocument document = PDDocument.load(pdfFile)) { //創(chuàng)建一個PDFRenderer對象并將PDDocument對象傳遞給它 PDFRenderer pdfRenderer = new PDFRenderer(document); List<BufferedImage> bufferedImages = new ArrayList<>(); BufferedImage bufferedImage; for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) { System.out.println("pageIndex:" + pageIndex); // 設置頁數(shù)(首頁從0開始)、每英寸點數(shù)、圖片類型 bufferedImage = pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB); bufferedImages.add(bufferedImage); } return bufferedImages; } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); return null; } }
service方法類,負責將讀取的pdf的bufferedImage列表對象按順序?qū)懭胫付夸浀膱D片文件中
@Override public void pickupPdfToImage(File pdfFile) { //要渲染的DPI(每英寸點數(shù)),可以理解為生成圖片的清晰度,值越高生成質(zhì)量越高 int dpi = 100; try { //提取封面工具類 List<BufferedImage> pdfAllImage = PdfUtils.getPdfAllImage(pdfFile, dpi); log.info("共提取到{}頁",pdfAllImage.size()); String fileName = FilenameUtils.getBaseName(pdfFile.getName()); String currentCoverPath; for (int i = 0; i < pdfAllImage.size(); i++) { currentCoverPath = coverPath + "/" + fileName + " 第" + i + "頁" + "." + coverExt; // 創(chuàng)建圖片文件對象 FileUtils.createParentDirectories(new File(currentCoverPath)); // 將圖片寫入到圖片對象中 ImageIOUtil.writeImage(pdfAllImage.get(i), currentCoverPath, dpi); } } catch (Exception e) { log.error(e.getMessage()); } }
測試類
/** * 批量提取文件封面 */ @Test public void pickupPdfToImage() { String pdfFilePath = "D:/pdf_test/pdf/三體三部曲-劉慈欣.pdf"; pdfService.pickupPdfToImage(new File(pdfFilePath)); }
3. 執(zhí)行結(jié)果
4.注意事項
由于pdf的提取是將pdf文件加載到堆內(nèi)存中進行操作,因此在提取過程中容易導致堆內(nèi)存溢出Java heap space
,簡單來說就是在創(chuàng)建新的對象時, 堆內(nèi)存中的空間不足以存放新創(chuàng)建的對象,導致此種問題的發(fā)生。
解決方案如下:
1.優(yōu)化項目代碼
根據(jù)報錯信息定位到內(nèi)存消耗較大的代碼,然后對其進行重構或者優(yōu)化算法。如果是在生產(chǎn)環(huán)境,務必要在內(nèi)存消耗過大的代碼出增加日志信息輸出,否則容易像我定位一晚上才找到問題所在
2.提升Java heap size
增加堆內(nèi)存空間設置,此種方式容易操作。可以較快解決當前問題,但是總體來說還是需要找到項目代碼中的問題才是最優(yōu)解,畢竟內(nèi)存總是有限的
根據(jù)自己的硬件配置進行分配對空間,例如8G內(nèi)存配置的內(nèi)存參數(shù):
-Xms4096m
-Xmx4096m
關于pdfbox比較好的學習文檔:
https://iowiki.com/pdfbox/pdfbox_overview.html
以上就是Springboot使用pdfbox提取PDF圖片的代碼示例的詳細內(nèi)容,更多關于Springboot pdfbox提取圖片的資料請關注腳本之家其它相關文章!
相關文章
java HttpURLConnection 發(fā)送文件和字符串信息
這篇文章主要介紹了java HttpURLConnection 發(fā)送文件和字符串信息的相關資料,需要的朋友可以參考下2017-06-06Java關鍵字instanceof用法及實現(xiàn)策略
instanceof 運算符是用來在運行時判斷對象是否是指定類及其父類的一個實例。這篇文章主要介紹了Java關鍵字instanceof用法解析,需要的朋友可以參考下2020-08-08IDEA?Ui設計器JFormDesigner?永久激活插件+注冊機(親測一直在用)
這篇文章主要介紹了IDEA?Ui設計器JFormDesigner?永久激活----插件+注冊機?自己一直在用的版本和注冊機,非常不錯,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下2022-08-08java如何實現(xiàn)嵌套對象轉(zhuǎn)大map(扁平化)
這篇文章主要介紹了java如何實現(xiàn)嵌套對象轉(zhuǎn)大map(扁平化),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10SpringBoot整合PageHelper分頁無效的常見原因分析
這篇文章主要介紹了SpringBoot整合PageHelper分頁無效的常見原因分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08