springboot itextpdf 形式导出pdf

  1. 先看效果(这里只设置了软件版本和 完成情况的勾选框)
    在这里插入图片描述
  2. 导入pom依赖
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>
<!--itextpdf-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.10</version>
</dependency>
  1. 功能实现
package com.example.demotest.controller;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@RestController
public class PdfController {

    /**
     * 导出pdf
     *
     * @param response
     * @return
     * @author shaolin
     */
    @PostMapping(value = {"/exportpdf"})
    public String exportPdf(HttpServletResponse response) throws IOException {
        // 指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String filename = "pdf/计算机编号.pdf";
 
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            os = response.getOutputStream();
            // 2 读入pdf表单
            Path path = Paths.get("pdf", "计算机编号.pdf");
            String pathing = path.toAbsolutePath().toString();
            // 输出文件路径
            reader = new PdfReader(pathing);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单

            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//            BaseFont bf = BaseFont.createFont("SimSun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("deptName", "测试部门");
            data.put("version", "1");

            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            // 多选框设置,  name是名称, value 是导出值
            ps.setFormFlattening(true);
            form.setField("test", "On", true);

//            -----------------------------pdf 添加图片----------------------------------
//            通过域名获取所在页和坐标,左下角为起点
            System.out.println("pdf 添加图片");
//            String imgpath = "e:/美女.png";
//            int pageNo = form.getFieldPositions("img").get(0).page;
//            Rectangle signRect = form.getFieldPositions("img").get(0).position;
//            float x = signRect.getLeft();
//            float y = signRect.getBottom();
//            // 读图片
//            Image image = Image.getInstance(imgpath);
//            // 获取操作的页面
//            PdfContentByte under = ps.getOverContent(pageNo);
//            // 根据域的大小缩放图片
//            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//            // 添加图片
//            image.setAbsolutePosition(x, y);
//            under.addImage(image);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
  1. 对应项目路径截图
    在这里插入图片描述

  2. 模板设置,这里使用的是adobe2024版

在这里插入图片描述

4.1 对于数字和文字的设置为文本域
在这里插入图片描述
4.2 双击截图里的文本域,出现下图所示,名称,这个名称就是你的字段名称
在这里插入图片描述
如果要显示中文,在外观这里设置宋体, 不然导出pdf 文字不显示
在这里插入图片描述

  1. 单选框功能实现
    5.1 选择复选框
    在这里插入图片描述
    5.2 设置字段名,以及字段值和展示的形式(例如框内是对勾,还是个黑点,等等)

在这里插入图片描述
在这里插入图片描述
对应代码里的(这里要设为true才行,不然框里也不显示对勾)
form.setField(“test”, “On”, true);

Spring Boot导出PDF文件可以使用第三方库,比如iText或Apache PDFBox。以下是使用iText进行PDF导出的示例代码: 首先,需要将iText库添加到项目的依赖中。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> ``` 接下来,创建一个用于导出PDF的控制器,在该控制器中定义一个处理请求的方法。在方法中使用iText库来生成PDF文件。 ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; @Controller public class PdfController { @GetMapping("/exportpdf") public void exportPdf(HttpServletResponse response) throws IOException, DocumentException { response.setContentType(MediaType.APPLICATION_PDF_VALUE); response.setHeader("Content-Disposition", "attachment; filename=example.pdf"); Document document = new Document(); OutputStream outputStream = response.getOutputStream(); PdfWriter.getInstance(document, outputStream); document.open(); document.add(new Paragraph("Hello, World!")); document.close(); outputStream.close(); } } ``` 在上述代码中,我们使用`@GetMapping`注解来处理GET请求,并指定了导出PDF的URL为`/exportpdf`。在`exportPdf`方法中,我们首先设置响应的内容类型为PDF,然后设置响应头部的Content-Disposition,指定文件名为example.pdf。 接下来,创建一个`Document`实例,并使用`PdfWriter`将文档写入输出流中。在文档中添加内容,这里我们添加了一个简单的段落"Hello, World!"。最后关闭文档和输出流。 当访问`/exportpdf`URL时,将会下载一个名为example.pdfPDF文件,其中包含"Hello, World!"的内容。 这只是一个简单的示例,你可以根据实际需求来生成更复杂的PDF文件。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值