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

发布于:2024-09-19 ⋅ 阅读:(6) ⋅ 点赞:(0)
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();
    }
}

引包的话引入这个

        <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>   用的是这个