Java如何将图片适配居中放置PDF中间

java 复制代码
package com.junfun.pms.controller.excelImport;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.junfun.seafar.common.entity.ServiceResponse;
import io.swagger.annotations.Api;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("test")
@Api(value = "ImageUploadController", tags = "截图导入接口")
public class ImageUploadController {

    @PostMapping("/upload-image")
    public ServiceResponse<String> handleFileUpload(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        ServiceResponse<String> response = new ServiceResponse<>();

        // 将图片保存到 D:\tu\ 目录下
        String filePath = "D:\\tu\\" + file.getOriginalFilename();

        // 生成 PDF 文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        String pdfFileName = fileName.substring(0, fileName.lastIndexOf('.')) + ".pdf";
        String pdfFilePath = "D:\\tu\\" + pdfFileName;

        try {
//            File file1 = new File(filePath);
//            //拷贝文件
//            file.transferTo(file1);

            // 将图片保存到临时文件
            File tempImageFile = new File("D:\\tu\\" + fileName);
            file.transferTo(tempImageFile);
            // 创建 PDF 文件
            createPdfFromImage(tempImageFile, pdfFilePath);
            // 删除临时图片文件
            tempImageFile.delete();

            response.setSucess("上传成功");
        } catch (Exception e) {
            response.setError("上传失败");
        }

        return response;
    }

    private void createPdfFromImage(File imageFile, String pdfFilePath) throws DocumentException, IOException {
        // 创建 PDF 文档
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));

        // 打开文档
        document.open();

        // 加载图片
        Image img = Image.getInstance(imageFile.getAbsolutePath());

        // 获取 PDF 页面的宽度和高度
        float pageWidth = document.getPageSize().getWidth();
        float pageHeight = document.getPageSize().getHeight();

        // 计算图片的原始宽度和高度
        float imgWidth = img.getScaledWidth();
        float imgHeight = img.getScaledHeight();

        // 计算缩放因子,确保图片不超出页面宽度
        float scaleFactor = pageWidth / imgWidth;

        // 如果图片的高度超过页面高度,重新计算缩放因子
        if ((imgHeight * scaleFactor) > pageHeight) {
            scaleFactor = pageHeight / imgHeight;
        }

        // 根据缩放因子调整图片大小
        img.scaleAbsolute((float)(imgWidth * scaleFactor), (float)(imgHeight * scaleFactor));

        // 计算图片在页面上的水平居中位置
        float posX = (pageWidth - img.getScaledWidth()) / 2;
        float posY = (pageHeight - img.getScaledHeight()) / 2;

        // 将图片添加到 PDF 文档
        img.setAbsolutePosition(posX, posY);
        document.add(img);

        // 关闭文档
        document.close();
    }
}

引包的话引入这个

XML 复制代码
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.15</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.12</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.9</version>
        </dependency>   用的是这个
相关推荐
LUCIAZZZ7 分钟前
SkyWalking快速入门
java·后端·spring·spring cloud·微服务·springboot·skywalking
EPSDA10 分钟前
Linux线程池
linux·运维·服务器·开发语言·c++
虾球xz10 分钟前
游戏引擎学习第116天
java·学习·游戏引擎
大胖丫28 分钟前
vue 学习-vite api.js
开发语言·前端·javascript
遇见很ok30 分钟前
js中 ES6 新特性详解
开发语言·javascript·es6
没有晚不了安38 分钟前
1.13作业
开发语言·python
布谷歌42 分钟前
Oops! 更改field的数据类型,影响到rabbitmq消费了...(有关于Java序列化)
java·开发语言·分布式·rabbitmq·java-rabbitmq
PXM的算法星球44 分钟前
java(spring boot)实现向deepseek/GPT等模型的api发送请求/多轮对话(附源码)
java·gpt·microsoft
被程序耽误的胡先生1 小时前
java中 kafka简单应用
java·开发语言·kafka
刀客1231 小时前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python