Java实现pdf转图片的工具类(三种方法实现PDF转图片的案例)【亲测可用】
作者:mmseoamin日期:2023-12-20

提示:有些时候我们需要在项目中展示PDF,所以我们可以将PDF转为图片,然后已图片的方式展示,效果很好。Java使用各种技术将pdf转换成图片格式,并且内容不失帧。清晰可见,该工具类也是开发中常用到的工具类。其中包括单页pdf转换成一张图片、多页pdf转换成多页图片、。 并且本人亲自使用过的。

文章目录

  • 前言
  • 一、使用开源库Apache PDFBox将PDF转换为图片
    • 1、引入依赖库
    • 2、实现pdf转换图片工具类(多页pdf会生成多页的图片,后缀会生成图片的位置序号)
    • 3、按照固定页数来将pdf转换成图片的工具类(自由选择pdf转换图片的页数)
    • 二、使用PDF Box将多页的pdf转换一张长图片的方法
      • 1、引入PDF Box需要的依赖
      • 2、编写将多页PDF转换多张图片的工具类
      • 三、使用文件流整个pdf转换成图片 (生成图片,并将生成的图片路径返回)
      • 总结

        前言

        提示:生成图片以后需要将文件流关闭,不然删除文件会删除失败

        很多人不知道怎么将pdf的文件转换成图片格式的,而且网上有很例子是跑不通的,同是也是方便自己在用到该需求的时候能够快速度地写出来,所以整理了几种pdf转换成图片的方法工具类,


        提示:以下是本篇文章正文内容,下面案例可供参考

        一、使用开源库Apache PDFBox将PDF转换为图片

        1、引入依赖库

        		
        			org.apache.pdfbox
        			fontbox
        			2.0.9
        		
        		
        		
        			org.apache.pdfbox
        			pdfbox
        			2.0.9
        		
        		
        		
        			commons-logging
        			commons-logging
        			1.2
        		
        

        2、实现pdf转换图片工具类(多页pdf会生成多页的图片,后缀会生成图片的位置序号)

        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;
        public class Pdf2Png {
            /**
             * 使用pdfbox将整个pdf转换成图片
             *
             * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
             * @param filename    PDF文件名不带后缀名
             * @param type        图片类型 png 和jpg
             */
            public static void pdf2png(String fileAddress, String filename, String type) {
                long startTime = System.currentTimeMillis();
                // 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接
                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++) {
                        // dpi为144,越高越清晰,转换越慢
                        BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                        // 将图片写出到该路径下
                        ImageIO.write(image, type, new File(fileAddress + "\\" + filename + "_" + (i + 1) + "." + type));
                    }
                    long endTime = System.currentTimeMillis();
                	System.out.println("共耗时:" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
            public static void main(String[] args) {
                pdf2png("C:\\Users\\user\\Desktop\\test", "测试", "png");
            }
        }
        
        使用Apache PDFBox将PDF转换为图片成功
        

        在这里插入图片描述

        3、按照固定页数来将pdf转换成图片的工具类(自由选择pdf转换图片的页数)

        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;
        public class Pdf2Png {
            /**
             * 自由确定起始页和终止页
              * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
             * @param filename    PDF文件名不带后缀名
             * @param indexOfStart 开始页  开始转换的页码,从0开始
             * @param indexOfEnd 结束页  停止转换的页码,-1为全部
             * @param type        图片类型 png 和jpg
             */
            public static void pdf2png(String fileAddress,String filename,int indexOfStart,int indexOfEnd,String type) {
                long startTime = System.currentTimeMillis();
                 // 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接
                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++) {
                    // dpi为144,越高越清晰,转换越慢
                        BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                         // 将图片写出到该路径下
                        ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("共耗时:" + ((endTime - startTime) / 1000.0) + "秒"); // 转换用时
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            public static void main(String[] args) {
                pdf2png("C:\\Users\\user\\Desktop\\test", "思泰得流式检测报告-00420299-任蛆小-RA202302100117",2,3, "png");
            }
        }
        
        自由页数转换成功
        

        在这里插入图片描述

        二、使用PDF Box将多页的pdf转换一张长图片的方法

        1、引入PDF Box需要的依赖

        
            net.sf.cssbox
            pdf2dom
            1.7
        
        
            org.apache.pdfbox
            pdfbox
            2.0.12
        
        
            org.apache.pdfbox
            pdfbox-tools
            2.0.12
        
        

        2、编写将多页PDF转换多张图片的工具类

        import com.lowagie.text.pdf.PdfReader;
        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;
        public class Pdf2Png {
            /***
             * PDF文件转PNG图片,全部页数
             * @param pdfFilePath pdf完整路径:C:\\Users\\user\\Desktop\\test\\1234.pdf
             * @param dpi dpi越大转换后越清晰,相对转换速度越慢
             */
            public static void pdf2Image(String pdfFilePath, int dpi) {
                long startTime = System.currentTimeMillis();
                File file = new File(pdfFilePath);
                PDDocument pdDocument;
                try {
                    String imgPdfPath = file.getParent();
                    int dot = file.getName().lastIndexOf('.');
                    // 获取图片文件名
                    String imagePdfName = file.getName().substring(0, dot);
                    pdDocument = PDDocument.load(file);
                    PDFRenderer renderer = new PDFRenderer(pdDocument);
                    /* dpi越大转换后越清晰,相对转换速度越慢 */
                    PdfReader reader = new PdfReader(pdfFilePath);
                    int pages = reader.getNumberOfPages();
                    StringBuffer imgFilePath;
                    for (int i = 0; i < pages; i++) {
                        String imgFilePathPrefix = imgPdfPath + File.separator + imagePdfName;
                        imgFilePath = new StringBuffer();
                        imgFilePath.append(imgFilePathPrefix);
                        imgFilePath.append("_");
                        imgFilePath.append((i + 1));
                        imgFilePath.append(".png");
                        File dstFile = new File(imgFilePath.toString());
                        BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                        ImageIO.write(image, "png", dstFile);
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("共耗时:" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        

        三、使用文件流整个pdf转换成图片 (生成图片,并将生成的图片路径返回)

        import org.apache.pdfbox.pdmodel.PDDocument;
        import org.apache.pdfbox.rendering.PDFRenderer;
        import javax.imageio.ImageIO;
        import java.awt.image.BufferedImage;
        import java.io.*;
        import java.util.*;
        public class Pdf2Png {
            /**
             * 使用文件流整个pdf转换成图片
             * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
             * @param filename    PDF文件名不带后缀名
             * @param type        图片类型 png 、jpg
             */
            public static List> pdfToImage(String fileAddress, String filename, String type) {
                long startTime = System.currentTimeMillis();
                List> list = new ArrayList<>();
                Map resultMap = null;
                PDDocument pdDocument = null;
                String fileName = null;
                String imgPath = null;
                try {
                    // 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接
                    File FilePath = new File(fileAddress + "\\" + filename + ".pdf");
                    // 文件流
                    FileInputStream inputStream = new FileInputStream(FilePath);
                    int dpi = 296;
                    pdDocument = PDDocument.load(inputStream);
                    PDFRenderer renderer = new PDFRenderer(pdDocument);
                    int pageCount = pdDocument.getNumberOfPages();
                    /* dpi越大转换后越清晰,相对转换速度越慢 */
                    for (int i = 0; i < pageCount; i++) {
                        resultMap = new HashMap<>();
                        fileName = filename + "_" + (i + 1) + "." + type;
                        imgPath = fileAddress + "\\" + fileName;
                        BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                        ImageIO.write(image, type, new File(imgPath));
                        resultMap.put("fileName", fileName);
                        resultMap.put("filePath", imgPath); // 图片路径
                        list.add(resultMap);
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("共耗时:" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        // 这里需要关闭PDDocument,不然如果想要删除pdf文件时会提示文件正在使用,无法删除的情况
                        pdDocument.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return list;
            }
            public static void main(String[] args) throws FileNotFoundException {
                pdfToImage("C:\\Users\\user\\Desktop\\test", "测试", "png");
            }
        }
        

        总结

        以上好几种pdf转图片的方法,该方法可直接拿过去用,或者按照自己的逻辑进行修改使用。文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面就来一起学习学习吧!!!