JAVA中pdf转图⽚的⼏种⽅法(⼆)JAVA基于PDF box将PDF转为图⽚(转⾃阿⾥云社区)1.引⽤:fontbox-2.0.16.jar、pdfbox-app-2.0.16.jar 版本⼀定要正确,否则代码会有问题。
main函数:package ;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;import org.apache.pdfbox.rendering.ImageType;import org.apache.pdfbox.rendering.PDFRenderer;import org.apache.pdfbox.tools.PDFBox;import .PdfUtil;@SuppressWarnings("unused")public class Test {//经过测试,dpi为96,100,105,120,150,200中,105显⽰效果较为清晰,体积稳定,dpi越⾼图⽚体积越⼤,⼀般电脑显⽰分辨率为96public static final float DEFAULT_DPI = 105;//默认转换的图⽚格式为jpgpublic static final String DEFAULT_FORMAT = "jpg";public static void main(String[] args) throws Exception {pdfToImage("/media/kevin/FileData/JavaCode/pdfboxTest/企业信息化建设论⽂.pdf","/media/kevin/FileData/JavaCode/pdfboxTest/img/7.jpg",5); } 实现函数:/*** pdf转图⽚** @param pdfPath PDF路径* @imgPath img路径* @page_end 要转换的页码,也可以定义开始页码和结束页码,我这⾥只需要⼀页,根据需求⾃⾏添加*/public static void pdfToImage(String pdfPath, String imgPath,int page_end) {try {//图像合并使⽤参数// 总宽度int width = 0;// 保存⼀张图⽚中的RGB数据int[] singleImgRGB;int shiftHeight = 0;//保存每张图⽚的像素值BufferedImage imageResult = null;//利⽤PdfBox⽣成图像PDDocument pdDocument = PDDocument.load(new File(pdfPath));PDFRenderer renderer = new PDFRenderer(pdDocument);//循环每个页码for (int i = 0, len = pdDocument.getNumberOfPages(); i < len; i++) {if (i==page_end) {BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);int imageHeight = image.getHeight();int imageWidth = image.getWidth();//计算⾼度和偏移量//使⽤第⼀张图⽚宽度;width = imageWidth;//保存每页图⽚的像素值imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);//这⾥有⾼度,可以将imageHeight*len,我这⾥值提取⼀页所以不需要singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);// 写⼊流中imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); //合并pdf if(i==23){ imageResult1 = imageResult; }else { imageResult = merge(imageResult1, imageResult); }}else if(i>page_end) { continue; } } pdDocument.close();// 写图⽚ImageIO.write(imageResult, DEFAULT_FORMAT, new File(imgPath));} catch (Exception e) { e.printStackTrace(); } //OVER }相关的(版本必须⼀致)jar:<!--pdf转图⽚--><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>3.0.0-alpha2</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>3.0.0-alpha2</version></dependency>注意: 根据3.0迁移指南,PDDocument.load⽅法已替换为Loader⽅法:对于加载PDF,PDDocument.load已被Loader⽅法替换。