springboot+itextpdf按模板生成PDF文件及在线下载PDF文件 - Go语言中文社区

springboot+itextpdf按模板生成PDF文件及在线下载PDF文件


最近做项目改造,将C项目改造成Java项目,因为没有文档,从网上找了很多资料,做成了生成文件放到本地,后来才发现跑偏了,是在线生成文件下载,索性两个代码都写到了工具类中,方面以后使用。
生成本地文件和导出文件,都是流的问题,一个FileOutputStream(路径)一个BufferedOutputStream(response.getOutputStream())。
这个功能是将数据库查询到的数据插入到固定的模板中。具体操作流程如下:
首先在word文档中,设定好模板,保存为pdf格式,然后使用Adobe Acrobat软件打开,我用的是Adobe Acrobat 9 Pro版本的,
用到了文件和表单两个模块。
在文件中打开你刚才保存的模板,然后点击表单,添加或编辑域,就可以自己选定区域,就可以添加域,域名称就是你要传的值的属性名,对应不上的话就传不上的;这里需要注意设置域的长度,如果长度小于你的字段长度,会自动隐藏掉超出的部分,不会自己增长,所以要设定的长度尽量的长。
软件截图
引入依赖:

<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.13.1</version>
</dependency>

好了,贴代码:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据pdf模板生成pdf文件生成到某路径下或导出
 *
*/
public class PdfUtil {
    /**
     * 利用模板生成pdf保存到某路径下
     */
    public static void pdfOut(Map<String, Object> inputMap) {

        // 生成的新文件路径
        String path0 = "D:/ProhibitDelete";
        File f = new File(path0);

        if (!f.exists()) {
            f.mkdirs();
        }
        // 模板路径
        String templatePath = "D:/ProhibitDelete/template11.pdf";
        // 创建文件夹
        String newPdfPath = "D:/ProhibitDelete/testMould.pdf";
        File file = new File(templatePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file1 = new File(newPdfPath);
        if (!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            BaseFont bf = BaseFont.createFont("C:/Windows/Fonts/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 输出流
            out = new FileOutputStream(newPdfPath);
            // 读取pdf模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //文字类的内容处理
            Map<String, String> datemap = (Map<String, String>) inputMap.get("dateMap");
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }
            stamper.setFormFlattening(false);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException | DocumentException e) {
            System.out.println(e);
        }

    }

    /**
     * 利用模板生成pdf导出
     */
    public static void pdfExport(Map<String, Object> inputMap, HttpServletResponse response) {

        // 生成的新文件路径
        String path0 = "D:/ProhibitDelete";
        File f = new File(path0);

        if (!f.exists()) {
            f.mkdirs();
        }
        // 模板路径
        String templatePath = "D:/ProhibitDelete/template12.pdf";

        File file = new File(templatePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        OutputStream out = null;
        try {
            Map<String, String> datemap = (Map<String, String>) inputMap.get("dateMap");
            BaseFont bf = BaseFont.createFont("C:/Windows/Fonts/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 输出流
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(datemap.get("billId") + ".pdf", "UTF-8"));
            out = new BufferedOutputStream(response.getOutputStream());
            // 读取pdf模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //文字类的内容处理
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }
            stamper.setFormFlattening(false);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException | DocumentException e) {
            System.out.println(e);
        } finally {
            try {
                assert out != null;
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
} ```
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/tyc_054600/article/details/104060362
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-26 22:06:35
  • 阅读 ( 469 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢