PDFBox的介紹
PDFBox是一個用于創(chuàng)建和處理PDF文檔的Java庫。它可以使用Java代碼創(chuàng)建、讀取、修改和提取PDF文檔中的內容。
PDFBox的功能:
Extract Text - 使用PDFBox,您可以從PDF文件中提取Unicode文本。
Split & Merge - 使用PDFBox,您可以將單個PDF文件分成多個文件,并將它們合并為一個文件。
Fill Forms - 使用PDFBox,您可以在文檔中填寫表單數據。
Print - 使用PDFBox,您可以使用標準Java打印API打印PDF文件。
Save as Image - 使用PDFBox,您可以將PDF保存為圖像文件,如PNG或JPEG。
Create PDFs - 使用PDFBox,您可以通過創(chuàng)建Java程序創(chuàng)建新的PDF文件,還可以包含圖像和字體。
Signing - 使用PDFBox,您可以將數字簽名添加到PDF文件。
Springboot集成PDFBox
本項目除了引入pdfbox的依賴之外,還引入了解決圖像問題的其他依賴。
例如:jai-imageio-jpeg2000
和jai-imageio-core
是為了解決在轉換圖像時報錯:Cannot read JPEG2000 image: Java Advanced Imaging (JAI) Image I/O Tools are not installed
jbig2-imageio
依賴引入是為了解決使用pdfbox2.0將PDF轉換為圖片時后臺報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. 實現需求
單個或者批量提取pdf的首頁作為封面,或者可以實現提取指定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);
// 設置頁數(首頁從0開始)、每英寸點數、圖片類型
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(每英寸點數),可以理解為生成圖片的清晰度,值越高生成質量越高
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í)行結果
1.單本pdf提取封面2.批量提取pdf封面
二、將pdf內容全部轉換為圖像
1. 實現需求
將pdf中所有的頁轉換為圖片
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);
// 設置頁數(首頁從0開始)、每英寸點數、圖片類型
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列表對象按順序寫入指定目錄的圖片文件中
@Override
public void pickupPdfToImage(File pdfFile) {
//要渲染的DPI(每英寸點數),可以理解為生成圖片的清晰度,值越高生成質量越高
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í)行結果
4.注意事項
由于pdf的提取是將pdf文件加載到堆內存中進行操作,因此在提取過程中容易導致堆內存溢出Java heap space
,簡單來說就是在創(chuàng)建新的對象時, 堆內存中的空間不足以存放新創(chuàng)建的對象,導致此種問題的發(fā)生。
解決方案如下:
1.優(yōu)化項目代碼
根據報錯信息定位到內存消耗較大的代碼,然后對其進行重構或者優(yōu)化算法。如果是在生產環(huán)境,務必要在內存消耗過大的代碼出增加日志信息輸出,否則容易像我定位一晚上才找到問題所在
2.提升Java heap size
增加堆內存空間設置,此種方式容易操作??梢暂^快解決當前問題,但是總體來說還是需要找到項目代碼中的問題才是最優(yōu)解,畢竟內存總是有限的
根據自己的硬件配置進行分配對空間,例如8G內存配置的內存參數:文章來源:http://www.zghlxwxcb.cn/news/detail-498284.html
-Xms4096m
-Xmx4096m
關于pdfbox比較好的學習文檔:
https://iowiki.com/pdfbox/pdfbox_overview.html文章來源地址http://www.zghlxwxcb.cn/news/detail-498284.html
到了這里,關于Springboot使用pdfbox提取PDF圖片的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!