一、引入依赖
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox-tools</artifactId><version>2.0.24</version></dependency>
二、每页进行转换
1、代码示例
package com.xiaobai.pdf2img;import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.Test;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;/*** @Author 王天文* @Date 2025/1/2 21:51* @Description: pdf文件转图片*/
public class Pdf2ImgTest {@Testpublic void pdf2Img() {// pdf文件路径String pdfPath = "D:\\temp\\信息报送流程.pdf";// 图片目录String imgDir = "D:\\temp\\img\\";// 加载pdf文件try(PDDocument pdDocument = PDDocument.load(new File(pdfPath))) {PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {// 渲染图像BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 500);File imageFile = new File(imgDir + "page-" + (i + 1) + ".png");// 保存为png格式ImageIO.write(bufferedImage, "PNG", imageFile);}} catch (IOException e) {e.printStackTrace();}}
}
2、说明
org.apache.pdfbox.rendering.PDFRenderer#renderImageWithDPI(int, float) 根据指定的DPI将pdf页面渲染成图像。DPI值越大,渲染越清晰,转换速度越慢。
三、pdf文件转换成长图
1、实现思路
根据pdf文件路径加载文件,对pdf文件的每页进行图像渲染,根据所有图像的高度计算长图片的高度,获取到所有图像的最大宽度即为长图片的宽度,使用java.awt.Graphics2D将所有图像渲染到长图片上。
2、代码示例
package com.xiaobai.pdf2img;import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.Test;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;/*** @Author 王天文* @Date 2025/1/2 22:23* @Description: pdf文件转换成长图*/
public class Pdf2MergeImgTest {@Testpublic void pdf2Img() {// pdf文件路径String pdfPath = "D:\\temp\\信息报送流程.pdf";// 图片目录String imgPath = "D:\\temp\\img\\mergeImg.png";// 长图片高度int totalHeight = 0;// 长图片宽度int maxWidth = 0;// 加载pdf文件try(PDDocument document = PDDocument.load(new File(pdfPath))) {PDFRenderer pdfRenderer = new PDFRenderer(document);BufferedImage[] bufferedImages = new BufferedImage[document.getNumberOfPages()];// pdf文件的每页转换成BufferedImagefor (int i = 0; i < document.getNumberOfPages(); i++) {// 根据dpi渲染图片BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 500);bufferedImages[i] = bufferedImage;// 高度totalHeight += bufferedImage.getHeight();// 宽度if (maxWidth < bufferedImage.getWidth()) {maxWidth = bufferedImage.getWidth();}}/*合并图片*/BufferedImage mergeImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g = mergeImage.createGraphics();int currentHeight = 0;for (BufferedImage bufferedImage : bufferedImages) {g.drawImage(bufferedImage, 0, currentHeight, null);currentHeight += bufferedImage.getHeight();}// 保存长图片ImageIO.write(mergeImage, "PNG", new File(imgPath));} catch (Exception e) {e.printStackTrace();}}
}