Springboot使用pdfbox提取PDF圖片的代碼示例
PDFBox的介紹
PDFBox是一個(gè)用于創(chuàng)建和處理PDF文檔的Java庫(kù)。它可以使用Java代碼創(chuàng)建、讀取、修改和提取PDF文檔中的內(nèi)容。
PDFBox的功能:
Extract Text - 使用PDFBox,您可以從PDF文件中提取Unicode文本。
Split & Merge - 使用PDFBox,您可以將單個(gè)PDF文件分成多個(gè)文件,并將它們合并為一個(gè)文件。
Fill Forms - 使用PDFBox,您可以在文檔中填寫(xiě)表單數(shù)據(jù)。
Print - 使用PDFBox,您可以使用標(biāo)準(zhǔn)Java打印API打印PDF文件。
Save as Image - 使用PDFBox,您可以將PDF保存為圖像文件,如PNG或JPEG。
Create PDFs - 使用PDFBox,您可以通過(guò)創(chuàng)建Java程序創(chuàng)建新的PDF文件,還可以包含圖像和字體。
Signing - 使用PDFBox,您可以將數(shù)字簽名添加到PDF文件。
Springboot集成PDFBox
本項(xiàng)目除了引入pdfbox的依賴之外,還引入了解決圖像問(wèn)題的其他依賴。
例如:jai-imageio-jpeg2000和jai-imageio-core是為了解決在轉(zhuǎn)換圖像時(shí)報(bào)錯(cuò):Cannot read JPEG2000 image: Java Advanced Imaging (JAI) Image I/O Tools are not installed
jbig2-imageio依賴引入是為了解決使用pdfbox2.0將PDF轉(zhuǎn)換為圖片時(shí)后臺(tái)報(bào)Cannot read JBIG2 image: jbig2-imageio is not installed錯(cuò)誤
<!-- 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"封面失敗問(wèn)題 -->
<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首頁(yè)為圖像
1. 實(shí)現(xiàn)需求
單個(gè)或者批量提取pdf的首頁(yè)作為封面,或者可以實(shí)現(xiàn)提取指定pdf頁(yè)為圖像
2. 項(xiàng)目代碼
核心工具類(lèi)方法: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工具類(lèi)
* @date 2023/6/17 9:52
*/
@Slf4j
public class PdfUtils {
/**
* 提取pdf首頁(yè)作為封面
*
* @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è)置頁(yè)數(shù)(首頁(yè)從0開(kāi)始)、每英寸點(diǎn)數(shù)、圖片類(lèi)型
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, dpi, ImageType.RGB);
log.info("提取耗時(shí):{}ms", System.currentTimeMillis() - startTime);
return bufferedImage;
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return null;
}
}
}service方法類(lèi),負(fù)責(zé)將讀取的pdf的bufferedImage對(duì)象寫(xiě)入指定的圖片對(duì)象中
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提取相關(guān)類(lèi)
* @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(每英寸點(diǎn)數(shù)),可以理解為生成圖片的清晰度,值越高生成質(zhì)量越高
int dpi = 300;
try {
//提取封面工具類(lèi)
BufferedImage bufferedImage = PdfUtils.getPdfFirstImage(pdfFile, dpi);
//獲取pdf文件名
String fileName = FilenameUtils.getBaseName(pdfFile.getName());
String currentCoverPath = coverPath + "/" + fileName + "." + coverExt;
// 創(chuàng)建圖片文件對(duì)象
FileUtils.createParentDirectories(new File(currentCoverPath));
// 將圖片寫(xiě)入到圖片對(duì)象中
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());
}
}
}測(cè)試類(lèi)
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;
/**
* 提取單個(gè)文件封面
*/
@Test
public void pickupCover() {
String pdfFilePath = "D:/pdf_test/pdf/三體三部曲-劉慈欣.pdf";
pdfService.pickupCover(new File(pdfFilePath), 0);
}
/**
* 批量單個(gè)文件封面
*/
@Test
public void batchPickupCover() {
String pdfFilePath = "E:/開(kāi)發(fā)項(xiàng)目/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. 實(shí)現(xiàn)需求
將pdf中所有的頁(yè)轉(zhuǎn)換為圖片
2. 項(xiàng)目代碼
核心工具類(lèi)方法:PdfUtils.getPdfAllImage
/**
* 加載讀取pdf并返回所有的BufferedImage對(duì)象
*
* @param pdfFile pdf文件對(duì)象
* @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對(duì)象并加載PDF文件
try (PDDocument document = PDDocument.load(pdfFile)) {
//創(chuàng)建一個(gè)PDFRenderer對(duì)象并將PDDocument對(duì)象傳遞給它
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è)置頁(yè)數(shù)(首頁(yè)從0開(kāi)始)、每英寸點(diǎn)數(shù)、圖片類(lèi)型
bufferedImage = pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB);
bufferedImages.add(bufferedImage);
}
return bufferedImages;
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return null;
}
}service方法類(lèi),負(fù)責(zé)將讀取的pdf的bufferedImage列表對(duì)象按順序?qū)懭胫付夸浀膱D片文件中
@Override
public void pickupPdfToImage(File pdfFile) {
//要渲染的DPI(每英寸點(diǎn)數(shù)),可以理解為生成圖片的清晰度,值越高生成質(zhì)量越高
int dpi = 100;
try {
//提取封面工具類(lèi)
List<BufferedImage> pdfAllImage = PdfUtils.getPdfAllImage(pdfFile, dpi);
log.info("共提取到{}頁(yè)",pdfAllImage.size());
String fileName = FilenameUtils.getBaseName(pdfFile.getName());
String currentCoverPath;
for (int i = 0; i < pdfAllImage.size(); i++) {
currentCoverPath = coverPath + "/" + fileName + " 第" + i + "頁(yè)" + "." + coverExt;
// 創(chuàng)建圖片文件對(duì)象
FileUtils.createParentDirectories(new File(currentCoverPath));
// 將圖片寫(xiě)入到圖片對(duì)象中
ImageIOUtil.writeImage(pdfAllImage.get(i), currentCoverPath, dpi);
}
} catch (Exception e) {
log.error(e.getMessage());
}
}測(cè)試類(lèi)
/**
* 批量提取文件封面
*/
@Test
public void pickupPdfToImage() {
String pdfFilePath = "D:/pdf_test/pdf/三體三部曲-劉慈欣.pdf";
pdfService.pickupPdfToImage(new File(pdfFilePath));
}3. 執(zhí)行結(jié)果

4.注意事項(xiàng)
由于pdf的提取是將pdf文件加載到堆內(nèi)存中進(jìn)行操作,因此在提取過(guò)程中容易導(dǎo)致堆內(nèi)存溢出Java heap space,簡(jiǎn)單來(lái)說(shuō)就是在創(chuàng)建新的對(duì)象時(shí), 堆內(nèi)存中的空間不足以存放新創(chuàng)建的對(duì)象,導(dǎo)致此種問(wèn)題的發(fā)生。
解決方案如下:
1.優(yōu)化項(xiàng)目代碼
根據(jù)報(bào)錯(cuò)信息定位到內(nèi)存消耗較大的代碼,然后對(duì)其進(jìn)行重構(gòu)或者優(yōu)化算法。如果是在生產(chǎn)環(huán)境,務(wù)必要在內(nèi)存消耗過(guò)大的代碼出增加日志信息輸出,否則容易像我定位一晚上才找到問(wèn)題所在
2.提升Java heap size
增加堆內(nèi)存空間設(shè)置,此種方式容易操作??梢暂^快解決當(dāng)前問(wèn)題,但是總體來(lái)說(shuō)還是需要找到項(xiàng)目代碼中的問(wèn)題才是最優(yōu)解,畢竟內(nèi)存總是有限的
根據(jù)自己的硬件配置進(jìn)行分配對(duì)空間,例如8G內(nèi)存配置的內(nèi)存參數(shù):
-Xms4096m
-Xmx4096m
關(guān)于pdfbox比較好的學(xué)習(xí)文檔:
https://iowiki.com/pdfbox/pdfbox_overview.html
以上就是Springboot使用pdfbox提取PDF圖片的代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Springboot pdfbox提取圖片的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Activiti開(kāi)發(fā)環(huán)境的配置
本篇文章主要內(nèi)容介紹了Activiti開(kāi)發(fā)環(huán)境的配置,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
java HttpURLConnection 發(fā)送文件和字符串信息
這篇文章主要介紹了java HttpURLConnection 發(fā)送文件和字符串信息的相關(guān)資料,需要的朋友可以參考下2017-06-06
Java關(guān)鍵字instanceof用法及實(shí)現(xiàn)策略
instanceof 運(yùn)算符是用來(lái)在運(yùn)行時(shí)判斷對(duì)象是否是指定類(lèi)及其父類(lèi)的一個(gè)實(shí)例。這篇文章主要介紹了Java關(guān)鍵字instanceof用法解析,需要的朋友可以參考下2020-08-08
IDEA?Ui設(shè)計(jì)器JFormDesigner?永久激活插件+注冊(cè)機(jī)(親測(cè)一直在用)
這篇文章主要介紹了IDEA?Ui設(shè)計(jì)器JFormDesigner?永久激活----插件+注冊(cè)機(jī)?自己一直在用的版本和注冊(cè)機(jī),非常不錯(cuò),本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
java如何實(shí)現(xiàn)嵌套對(duì)象轉(zhuǎn)大map(扁平化)
這篇文章主要介紹了java如何實(shí)現(xiàn)嵌套對(duì)象轉(zhuǎn)大map(扁平化),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
SpringBoot整合PageHelper分頁(yè)無(wú)效的常見(jiàn)原因分析
這篇文章主要介紹了SpringBoot整合PageHelper分頁(yè)無(wú)效的常見(jiàn)原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08

