一、导入依赖
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
二、代码实现
package com.example.pdf_box_to_images.contorller;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @author Wss8752@qq.com
* @version 1.0
* @date 2021/10/15 下午4:19
*/
public class PdfToImages {
//可*确定起始页和终止页
public static void pdf2png(String fileAddress, String filename, int indexOfStart, int indexOfEnd) {
// 将pdf装图片 并且自定义图片得格式大小
File file = new File(fileAddress + "/" + filename + ".pdf");
try {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = indexOfStart; i < indexOfEnd; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
ImageIO.write(image, "PNG", new File(fileAddress + "/images/" + filename + "_" + (i + 1) + ".png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
//转换全部的pdf
public static void pdf2png(String fileAddress, String filename) {
// 将pdf装图片 并且自定义图片得格式大小
File file = new File(fileAddress + "/" + filename + ".pdf");
try {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 250); // Windows native DPI
// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
ImageIO.write(image, "PNG", new File(fileAddress + "/images/" + filename + "_" + (i + 1) + ".png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileAddress = "/home/kv/IdeaProjects/MarkVeriousTests2/PdfBoxToImages/src/main/resources";
String filename = "Safety, Efficacy, and Pharmacokinetics of Almo";
int indexOfStart = 0;//开始转换的页码
int indexOfEnd = -1;//停止转换的页码,-1为全部
if (indexOfEnd == -1) {
pdf2png(fileAddress, filename);
} else {
pdf2png(fileAddress, filename, indexOfStart, indexOfEnd);
}
}
}