多张图片转换PDF

引入包

            <!-- PDFBox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.24</version>
        </dependency>

        <!-- iText -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.15</version>
            <type>pom</type>
        </dependency>
// 参数是文件路径 C:\Users\86158\Desktop\常用工具图标\1\2\3\4
public void imagesToPdf(String pdfFolderPath) {
        if (StringUtils.isEmpty(pdfFolderPath)) {
            return;
        }
        try {
            // pdf文件名称前缀 可以根据自己要求自定义
            List<String> pdfNameList = Arrays.asList(pdfFolderPath.split("\\\\"));            
            String pdfPrefixName = pdfNameList.get(pdfNameList.size() -4)+"-"+pdfNameList.get(pdfNameList.size() -3)
                    +"-"+pdfNameList.get(pdfNameList.size() -2)+"-"+pdfNameList.get(pdfNameList.size() -1);

            // 获取所有文件名称
            File[] files = new File(pdfFolderPath).listFiles();

            // 遍历文件
            for (File file : files) {
                // pdf文件存储路径
                String pdfPath = pdfFolderPath + "\\" + file.getName()+"\\"+ pdfPrefixName+"-"+file.getName() + ".pdf";

                // 获取文件夹中的所有图片
                List<File> imageFiles = getImageFiles(pdfFolderPath + "\\" + file.getName());
                // 创建PDF文档
                PDDocument document = new PDDocument();
                imageFiles.forEach(imageFile -> {
                    PDPage page = new PDPage(PDRectangle.A4);
                    document.addPage(page);
                    // 写入内容
                    PDImageXObject pdImage = null;
                    try {
                    // 第一个参数是,照片的原始路径
                        pdImage = PDImageXObject.createFromFile(pdfFolderPath + "\\" +file.getName()+"\\"+ imageFile.getName(), document);
                        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                            contentStream.drawImage(pdImage, 0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
                document.save(pdfPath);
                document.close();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }




    /**
     * 获取文件夹中的所有图片文件
     * 参数是照片所在文件夹路径
     * @return
     */
    private List<File> getImageFiles(String imageFolderPath) {

        File folder = new File(imageFolderPath);
        List<File> imageFiles = new ArrayList<>();

        // 定义图片文件的后缀名
        String[] imageExtensions = new String[]{"jpg"};

        // 创建一个文件名过滤器
        FilenameFilter imageFilter = (dir, name) -> {
            for (String extension : imageExtensions) {
                if (name.toLowerCase().endsWith("." + extension)) {
                    return true;
                }
            }
            return false;
        };

        // 获取文件夹中的所有文件
        File[] files = folder.listFiles(imageFilter);

        // 如果文件不为空,则添加到列表中
        if (files != null) {
            Collections.addAll(imageFiles, files);
        }

        return imageFiles;
    }






多张图片转换为一个PDF文件有多种方法: - **使用在线迅捷PDF转换器**:无需下载PDF格式转换工具,只需把文件上传到在线迅捷PDF转换器,即可一站式搞定PDF文件的格式转换以及一些常用的功能操作,如PDF文件加密等[^1]。 - **使用Python的fitz模块**:可以通过编写Python代码实现将一张图片转换PDF格式,若要处理多张图片,可多次执行相关操作并插入到同一个PDF文档中。示例代码如下: ```python import fitz # 打开一个新的PDF文档 pdf_document = fitz.open() # 假设这里有多个图片路径 image_paths = ['all_images/01.png', 'all_images/02.png'] # 替换为实际的图片路径 for image_path in image_paths: # 加载图像文件,生成图片对象 image_file = fitz.open(image_path) # 使用convert_to_pdf函数将图片文件对象转换pdf格式 image_pdf = image_file.convert_to_pdf() # 以pdf格式打开转换后的图像,生成pdf对象 pdf = fitz.open('pdf', image_pdf) # 向pdf文档中插入pdf对象 pdf_document.insert_pdf(pdf) # 关闭图片文件 image_file.close() # 将PDF文档保存至指定路径 pdf_document.save('output.pdf') # 替换为你想要保存的PDF路径 # 关闭pdf文档 pdf_document.close() print('图片转换pdf文档!') ``` [^2] - **使用手机辅助工具**:先检查图片是否都存放在相册里,将手机连接网络,在应用市场找到合适的辅助工具,然后用手机将图片合并为PDF文件,方便对不同类的图片进行分类管理[^3]。 - **使用Python的img2pdf库**:通过安装`img2pdf`库并编写Python代码实现批量合并多张图片为一个PDF文件。示例代码如下: ```python import img2pdf import os def convert2pdf(input_folder): # convert functions with open("result.pdf", "wb") as f: jpg_list = [] files = os.listdir(input_folder) jpgfiles = [f for f in files if f.endswith((".png", ".jpg", ".jpeg"))] print(jpgfiles) f.write(img2pdf.convert(jpgfiles)) if __name__ == "__main__": input_dir = "C:\\Users\\Administrator\\Desktop\\jpgs" # pictures dir convert2pdf(input_dir) print("Finished!") ``` [^4]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值