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>   用的是这个
相关推荐
都叫我大帅哥1 小时前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
Dcs6 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
fouryears_234178 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes