Java实现图片保存到pdf的某个位置

Java实现图片保存到pdf的某个位置

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


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.awt.geom.Point2D;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Base64;

@Controller
public class PdfApiController {

    @PostMapping("/api/save-image-to-pdf")
    public ResponseEntity<String> saveImageToPdf(@RequestBody JsonNode jsonNode) {
        try {
            // 解析前端传来的JSON数据
            int pageNumber = jsonNode.get("pageNumber").asInt();
            Point2D.Float position = new Point2D.Float(jsonNode.get("imagePosition").get("x").floatValue(), jsonNode.get("imagePosition").get("y").floatValue());
            String base64Image = jsonNode.get("base64Image").toString();

            // 将Base64编码的图片转换为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64Image.split(",")[1]);

            // 假设有一个默认的PDF文件路径
            File originalPdf = new File("D:\\templateFilePath\\测试.pdf");
            File tempPdf = File.createTempFile("temp", ".pdf");

            // 使用iText处理PDF
            insertImageIntoPdf(originalPdf, tempPdf, pageNumber, position, imageBytes);

            // 下载处理后的PDF到D盘
            downloadPdf(tempPdf, "modified_pdf_page_" + pageNumber + ".pdf");

            return ResponseEntity.ok("图片已成功添加到PDF并保存到D盘。");
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("处理PDF时出错。");
        }
    }

    private void insertImageIntoPdf(File originalPdf, File tempPdf, int pageNumber, Point2D.Float position, byte[] imageBytes) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(new FileInputStream(originalPdf));
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(tempPdf));
        PdfContentByte canvas = stamper.getOverContent(pageNumber);

        Image img = Image.getInstance(imageBytes);
        img.setAbsolutePosition(position.x, position.y);
        img.scaleToFit(100, 100); // 示例:调整图片大小,根据需要调整
        canvas.addImage(img);

        stamper.close();
        reader.close();
    }

    private void downloadPdf(File tempPdf, String fileName) throws IOException {
        Path sourcePath = tempPdf.toPath();
        Path targetDir = Paths.get("D:/");
        Path targetPath = targetDir.resolve(System.currentTimeMillis() + ".pdf");

        // 检查目标文件是否已存在,根据需求决定是否覆盖或提示错误
        if (Files.exists(targetPath)) {
            // 这里可以根据实际情况选择抛出异常、覆盖文件或修改文件名
            throw new IOException("目标文件已存在:" + targetPath);
            // 或者
            // Files.delete(targetPath); // 如果决定覆盖,则先删除原有文件
        }

        // 确保目标目录存在
        Files.createDirectories(targetDir);

        // 执行移动操作
        Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); // REPLACE_EXISTING 用于允许覆盖已存在的文件
    }

}
3、jsonNode参数,根据需要调整
json 复制代码
{
    "pageNumber":2,//pdf页码数
    "base64Image":"data:image/png;base64,i...................",//base64
    "imagePosition":{//在pdf中的坐标,左下角为(0,0)
        "x":100,
        "y":0
    },
    "imageSize":{//在pdf中的图片大小
        "width":100,
        "height":100
    }
}
相关推荐
VBA633722 分钟前
VBA之Word应用第三章第十一节:Document对象的事件
开发语言
hweiyu0024 分钟前
Maven 私库
java·maven
wjs202432 分钟前
SOAP Header 元素
开发语言
Super Rookie32 分钟前
Spring Boot 企业项目技术选型
java·spring boot·后端
写不出来就跑路37 分钟前
Spring Security架构与实战全解析
java·spring·架构
无限远的弧光灯1 小时前
c语言学习_函数递归
c语言·开发语言·学习
趣多多代言人1 小时前
从零开始手写嵌入式实时操作系统
开发语言·arm开发·单片机·嵌入式硬件·面试·职场和发展·嵌入式
胖大和尚1 小时前
C++项目学习计划
开发语言·c++·学习
开开心心_Every1 小时前
全能视频处理工具介绍说明
开发语言·人工智能·django·pdf·flask·c#·音视频
ZeroNews内网穿透1 小时前
服装零售企业跨区域运营难题破解方案
java·大数据·运维·服务器·数据库·tcp/ip·零售