springboot+itextpdf使用模板动态导出PDF

1.编辑模板

1.使用Adobe Acrobat 9 Pro软件编辑模板。
在这里插入图片描述
2.使用word设计模板并转换成pdf,使用Adobe Acrobat 9 Pro导入pdf文件,点击“表单”—>“添加或编辑域”。域的名称要记住,名称代表要插入的字段。
在这里插入图片描述

在这里插入图片描述

2.导入pom依赖

<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.13</version>
</dependency>
<!--字体集-->
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
</dependency>

3.server层代码

@Service
@Slf4j
public class PdfService {

    public  void generateTempPDF(HttpServletResponse response, FieldVo fieldVo) throws Exception {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            String fileName = "E:\\时间证书下载(2).pdf";
            //模板绝对路径--服务器
//            String fileName = "/app/file/pdf/KDDLR_Receipt_Template.pdf";
            reader = new PdfReader(fileName);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体(具体填入模板的字体在Adobe Acrobat软件中可以设置)
            BaseFont bf = BaseFont.createFont("/fonts/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);

            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data(fieldVo)); //填充模板

            //必须要调用这个,否则文档不会生成的
            ps.setFormFlattening(true);
            if(ps != null){
                ps.close();
            }
            //生成pdf路径存放的路径
            fos = response.getOutputStream();
            fos.write(bos.toByteArray());

        }catch (Exception e){
            e.printStackTrace();
            log.error("异常:{",e.getMessage()+e.getCause()+"}");
        }finally {
            if(fos!=null){
                fos.flush();
                fos.close();
            }
            if (bos != null){
                bos.close();
            }
            if(reader != null){
                reader.close();
            }
        }
    }

    /**
     * 填充模板中的数据
     */
    public void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常:{",e.getMessage()+e.getCause()+"}");
        }
    }

    /**
     * 填充数据源
     * 其中data存放的key值与pdf模板中的文本域值相对应
     */
    public Map<String, String> data(FieldVo fieldVo){
        // 构造数据 , key要与模板中的别名一一对应
        Map<String, String> paramters = new HashMap();
        paramters.put("name",fieldVo.getName());
        paramters.put("sex",fieldVo.getSex());

        return paramters;
    }
}

4.controller层代码

@RestController("/pdf")
public class PdfController {
    @Autowired
    private PdfService reportPrint;

    @GetMapping("/export")
    public void export(HttpServletResponse response, FieldVo fieldVo) {
        response.setHeader("content-disposition","attachment;fileName="+"下载时的文件名.pdf");
        try {
            reportPrint.generateTempPDF(response,fieldVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.vo类

这个是填充到模板中内容,可自行添加。

/**
 * 填充模板的内容
 */
@Data
public class FieldVo {
    private String name;
    private String sex;
}

6.字体导入

配置所需字体包,可以在本地C:\Windows\Fonts中拷贝需要使用的字体包。
在这里插入图片描述
参考文章
SpringBoot使用模板动态导出PDF使用itextpdf

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot和Vue.js的Word动态导出,可以使用Apache POI库来生成Word文档,然后在Vue.js中使用AJAX来获取动态数据,并将其填充到Word文档中。 以下是一个简单的示例: 1. 首先,创建一个Spring Boot REST API来生成Word文档。您可以使用Apache POI库来创建一个空的Word文档,并在其中添加文本和表格。 ```java @RestController public class WordController { @GetMapping("/api/word") public void generateWord(HttpServletResponse response) throws Exception { // create a blank document XWPFDocument document = new XWPFDocument(); // add some text XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("Hello, World!"); // add a table XWPFTable table = document.createTable(); // add table rows and cells // ... // set the response headers response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment; filename=\"document.docx\""); // write the document to the response stream document.write(response.getOutputStream()); document.close(); } } ``` 2. 在Vue.js中,使用AJAX来获取动态数据,并将其填充到Word文档中。您可以使用axios库来发送AJAX请求。 ```html <template> <div> <button @click="downloadWord">Download Word Document</button> </div> </template> <script> import axios from 'axios' export default { methods: { downloadWord() { axios.get('/api/word', { responseType: 'blob' }) .then(response => { // create a blob URL for the response data const url = window.URL.createObjectURL(new Blob([response.data])) // create a link element to download the file const link = document.createElement('a') link.href = url link.setAttribute('download', 'document.docx') // append the link element to the document body and click it document.body.appendChild(link) link.click() // cleanup document.body.removeChild(link) window.URL.revokeObjectURL(url) }) .catch(error => { console.error(error) }) } } } </script> ``` 3. 最后,在Vue.js中使用上面的组件。 ```html <template> <div> <word-download></word-download> </div> </template> <script> import WordDownload from './WordDownload.vue' export default { components: { WordDownload } } </script> ``` 这样,当用户点击“Download Word Document”按钮时,将触发AJAX请求来获取Word文档,并将其下载到用户的计算机上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值