Java实现多张图片合并保存到pdf中

Java实现多张图片合并保存到pdf中

1、依赖--maven
xml 复制代码
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.24</version>
        </dependency>
2、上代码
java 复制代码
package com.hxlinks.hxiot.controller;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.thymeleaf.expression.Lists;

import javax.imageio.ImageIO;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class PdfBoxMultipleImagesToPdf {

    public static void main(String[] args) {
        List<String> imagePaths = Arrays.asList("C:\\Users\\89131\\Desktop\\1.png", "C:\\Users\\89131\\Desktop\\2.png",
                "C:\\Users\\89131\\Desktop\\3.png", "C:\\Users\\89131\\Desktop\\4.png");
        File outputPdf = new File("D:/output.pdf");

        try {
            createPdfFromImages(imagePaths, outputPdf);
            System.out.println("PDF with images created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//
//    public static void createPdfFromImages(List<String> imagePaths, File outputFile) throws IOException {
//        try (PDDocument document = new PDDocument()) {
//            for (String imagePath : imagePaths) {
//                // Load image
//                PDImageXObject image = LosslessFactory.createFromImage(document, ImageIO.read(new File(imagePath)));
//
//                // Create a new page and add it to the document
//                PDPage page = new PDPage(PDRectangle.A4);
//                document.addPage(page);
//
//                // Get the content stream for the page
//                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
//                    // Define the position and size for the image on the page
//                    float imgWidth = image.getWidth();
//                    float imgHeight = image.getHeight();
//                    float margin = 50; // Example margin
//                    float x = (page.getMediaBox().getWidth() - imgWidth) / 2;
//                    float y = (page.getMediaBox().getHeight() - imgHeight) - margin;
//
//                    // Draw the image onto the page
//                    contentStream.drawImage(image, x, y, imgWidth, imgHeight);
//                }
//            }
//
//            // Save the final document
//            document.save(outputFile);
//        }
//    }

    public static void createPdfFromImages(List<String> imagePaths, File outputFile) throws IOException {
        try (PDDocument document = new PDDocument()) {
            float margin = 50f; // Define the margin

            for (String imagePath : imagePaths) {
                // Load image
                PDImageXObject image = LosslessFactory.createFromImage(document, ImageIO.read(new File(imagePath)));

                // Calculate scaling factor to fit image within the page minus margins, maintaining aspect ratio
                float imgWidth = image.getWidth();
                float imgHeight = image.getHeight();
                float pageWidthForImage = PDRectangle.A4.getWidth() - 2 * margin; // Subtracting total margin from width
                float pageHeightForImage = PDRectangle.A4.getHeight() - 2 * margin; // Subtracting total margin from height

                float scaleX = pageWidthForImage / imgWidth;
                float scaleY = pageHeightForImage / imgHeight;
                float scale = Math.min(scaleX, scaleY);

                // Resize the image dimensions with the scale
                imgWidth *= scale;
                imgHeight *= scale;

                // Create a new page and add it to the document
                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);

                // Get the content stream for the page
                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                    // Calculate the centered position considering the total margin around the page
                    float x = (page.getMediaBox().getWidth() - imgWidth) / 2; // Centered without adding margin again
                    float y = (page.getMediaBox().getHeight() - imgHeight) / 2; // Centered without adding margin again

                    // Draw the scaled image onto the page at the correctly centered position
                    contentStream.drawImage(image, x, y, imgWidth, imgHeight); // Apply margin here
                }
            }

            // Save the final document
            document.save(outputFile);
        }
    }
}
相关推荐
阿俊仔(摸鱼版)3 分钟前
Python 常用运维模块之Shutil 模块
linux·服务器·python·自动化·云服务器
MarsBighead4 分钟前
(二)PosrgreSQL: Python3 连接Pgvector出错排查
python·postgresql·向量数据库·pgvector
小张认为的测试17 分钟前
Liunx上Jenkins 持续集成 Java + Maven + TestNG + Allure + Rest-Assured 接口自动化项目
java·ci/cd·jenkins·maven·接口·testng
深蓝海拓25 分钟前
Pyside6(PyQT5)中的QTableView与QSqlQueryModel、QSqlTableModel的联合使用
数据库·python·qt·pyqt
无须logic ᭄33 分钟前
CrypTen项目实践
python·机器学习·密码学·同态加密
Channing Lewis1 小时前
flask常见问答题
后端·python·flask
蘑菇丁1 小时前
ansible批量生产kerberos票据,并批量分发到所有其他主机脚本
java·ide·eclipse
Channing Lewis1 小时前
如何保护 Flask API 的安全性?
后端·python·flask
水兵没月2 小时前
钉钉群机器人设置——python版本
python·机器人·钉钉