Java使用pdfbox进行pdf和图片之间的转换

简介

pdfbox是Apache开源的一个项目,支持pdf文档操作功能。

官网地址: Apache PDFBox | A Java PDF Library
支持的功能如下图.
引入依赖

复制代码
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-app</artifactId>
            <version>2.0.19</version>
        </dependency>

pdf转换成图片

复制代码
   /**
     * 经过测试,dpi为96,100,105,120,150,200中,105显示效果较为清晰,体积稳定,dpi越高图片体积越大,一般电脑显示分辨率为96
     */
    public static final float DEFAULT_DPI = 105;

    /**
     * 默认转换的图片格式为jpg
     */
    public static final String DEFAULT_FORMAT = "jpg";


    /**
     * pdf转换成图片
     *
     * @param pdfPath    pdf文件的路径   例如: D:\\test\\test.pdf (2页)
     * @param targetPath 输出的图片路径        D:\\test\\
     * @return 抽取出来的图片路径数组         Arrays.asList( "D:\\test\\1.jpg","D:\\test\\2.jpg" )
     */
    public static List<String> pdfToManyImage(String pdfPath, String targetPath) {
        File file = new File(pdfPath);
        if (!file.exists()) {
            return null;
        }
        try {
            //加载pdf文件
            PDDocument doc = PDDocument.load(file);
            //读取pdf文件
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            List<String> stringList = new ArrayList<>(pageCount);
            String filePath = null;
            BufferedImage image;
            for (int i = 0; i < pageCount; i++) {
                //96/144/198
                // Windows native DPI
                image = renderer.renderImageWithDPI(i, DEFAULT_DPI);
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                filePath = targetPath + (i + 1) + "." + DEFAULT_FORMAT;
                //保存图片
                ImageIO.write(image, DEFAULT_FORMAT, new File(filePath));
                stringList.add(filePath);
            }
            return stringList;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

图片合成pdf

复制代码
    /**
     * 多图片合成pdf的限制后缀
     */
    private static final List IMAGE_SUFFIX = Arrays.asList("jpg", "png", "jpeg");
   /**
     * 多个图片合成一个pdf
     *
     * @param imgFolder 多图片的文件夹路径  例如:"D:\\image\\"
     * @param target    合并的图片路径          "D:\\image\\merge.pdf"
     * @throws IOException
     */
    public static void manyImageToOnePdf(String imgFolder, String target) throws IOException {
        PDDocument doc = new PDDocument();
        //创建一个空的pdf文件
        doc.save(target);
        
        PDPage page;
        PDImageXObject pdImage;
        PDPageContentStream contents;
        BufferedImage bufferedImage;
        String fileName;
        float w, h;
        String suffix;
        File tempFile;
        int index;
		
		File folder = new File(imgFolder);
        for (int i = 0; i < folder.listFiles().length; i++) {
            tempFile = folder.listFiles()[i];
            if (!tempFile.isFile()) {
                continue;
            }

            fileName = tempFile.getName();
            index = fileName.lastIndexOf(".");
            if (index == -1) {
                continue;
            }
            //获取文件的后缀
            suffix = fileName.substring(index + 1);
            //如果文件后缀不是图片格式,跳过当前循环
            if (!IMAGE_SUFFIX.contains(suffix)) {
                continue;
            }
            
            bufferedImage = ImageIO.read(folder.listFiles()[i]);
            //Retrieving the page
            pdImage = LosslessFactory.createFromImage(doc, bufferedImage);
            w = pdImage.getWidth();
            h = pdImage.getHeight();
            page = new PDPage(new PDRectangle(w, h));
            contents = new PDPageContentStream(doc, page);
            contents.drawImage(pdImage, 0, 0, w, h);
            System.out.println("Image inserted");
            contents.close();
            doc.addPage(page);
        }
        //保存pdf
        doc.save(target);
        //关闭pdf
        doc.close();
    }

多个pdf合成1个pdf

复制代码
 /**
     * pdf合并拼接
     *
     * @param files      pdf文件列表    例如:  Arrays.asList(new File("D:\\1.pdf"),new File("D:\\2.pdf"))
     * @param targetPath 合并后的文件         D:\\merge.pdf
     * @return 合并后的文件File对象
     */
    public static File manyPdfToOne(List<File> files, String targetPath) {
        try {
            PDFMergerUtility mergePdf = new PDFMergerUtility();
            for (File f : files) {
                if (f.exists() && f.isFile()) {
                    // 循环添加要合并的pdf
                    mergePdf.addSource(f);
                }
            }
            // 设置合并生成pdf文件名称
            mergePdf.setDestinationFileName(targetPath);
            // 合并pdf
            mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
            return new File(targetPath);
        } catch (Exception e) {
            return null;
        }
    }
相关推荐
badhope19 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园21 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
C++ 老炮儿的技术栈21 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl21 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
大阿明21 小时前
Spring Boot(快速上手)
java·spring boot·后端
Liu6288821 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
bearpping21 小时前
Java进阶,时间与日期,包装类,正则表达式
java
IT猿手21 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队
邵奈一21 小时前
清明纪念·时光信笺——项目运行指南
java·实战·项目
AI科技星21 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘