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;
        }
    }
相关推荐
小羊没烦恼!13 小时前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里13 小时前
java中的继承和多态的区别
java
小羊没烦恼!13 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕13 小时前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码13 小时前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖13 小时前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时14 小时前
01-06-A-JVM排查实战详解
java·jvm
伞伞悦读14 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
vipxieliang14 小时前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot
C语言小火车15 小时前
C/C++ 为什么需要编译器?
开发语言·c++