Java导出PDF文档(模板导出和自定义)

这篇具有很好参考价值的文章主要介绍了Java导出PDF文档(模板导出和自定义)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

项目场景:

需要导出PDF文档,支持模板导出和自定义文档格式。

场景分析:

PDF模板创建可使用表单域创建表单字段,引入数据填充,或者根据实际需要生成html转换成pdf。

解决方案:

PDF模板可以考虑使用PDF编辑器编辑,创建表单域,配置好相应字段

java 导出pdf,pdf,java

 文章来源地址https://www.toymoban.com/news/detail-571635.html

java 导出pdf,pdf,java

java 导出pdf,pdf,java

 

 

package com.xxx.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * ItextPdf操作工具类
 * @author lsh
 * @version 1.0
 * @date 2022/4/12 12:01
 */
public class PdfUtil {

    /**
     * 根据模板导出单个PDF文件(支持多页模板)
     * @param templateName 模板文件路径全称
     * @param fileName 目标文件名称
     * @param response 响应请求
     * @param data 数据Map
     */
    public void exportPdf(String templateName, String fileName, HttpServletResponse response, Map<String, Object> data){
        try{
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        // 设置响应头
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition","attachment;fileName=" + fileName + ".pdf");
        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;
        //PDF模板页数
        int pageNum = 10;
        try {
            // 输出到浏览器端
            out = response.getOutputStream();
            // 字节数组流,用来缓存文件流
            ByteArrayOutputStream[] baos = new ByteArrayOutputStream[pageNum];
            // 给表单生成中文字体
            BaseFont fonChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 遍历模板,给pdf表单赋值
            for (int i =0;i<pageNum;i++){
                baos[i] = new ByteArrayOutputStream();
                InputStream ins = this.getClass().getResourceAsStream(templateName);
                reader = new PdfReader(ins);
                stamper = new PdfStamper(reader,baos[i]);
                AcroFields form = stamper.getAcroFields();
                form.addSubstitutionFont(fonChinese);
                for(String key : data.keySet()){
                    if (data.get(key) != null){
                        form.setField(key, data.getOrDefault(key," ").toString());
                    }
                }
                // 表明该PDF不可修改
                stamper.setFormFlattening(true);
                stamper.close();
            }
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            for (int i=0;i<pageNum;i++){
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(baos[i].toByteArray()), i+1);
                copy.addPage(importPage);
            }
            doc.close();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据模板导出多个PDF并打包成ZIP
     * @param templateName 模板文件路径全称
     * @param fileName 目标文件名
     * @param response 响应
     * @param listData 数据实体集合
     */
    public void exportZip(String templateName, String fileName, HttpServletResponse response, List<Map<String, Object>> listData) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 设置响应头
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            if (!listData.isEmpty()) {
                for (Map<String, Object> data : listData) {
                    if (data.get("fileName") != null) {
                        fileName = data.get("fileName").toString() + ".pdf";
                    }
                    byte[] xmpMetadata = generatePdfStream(templateName, data).toByteArray();
                    //将PDF文件添加到压缩卷中
                    zipOutputStream.putNextEntry(new ZipEntry(fileName));
                    zipOutputStream.write(xmpMetadata);
                    zipOutputStream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(zipOutputStream != null){
                    zipOutputStream.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据模板生成 PDF流
     * @param templateName 模板文件名
     * @param data 数据实体
     * @return 字节流
     * @throws Exception
     */
    private static ByteArrayOutputStream generatePdfStream(String templateName, Map<String, Object> data) throws  Exception{
        InputStream ins = new ClassPathResource(templateName).getInputStream();
        PdfReader reader = new PdfReader(ins);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper ps = new PdfStamper(reader, bos);
        PdfContentByte under = ps.getUnderContent(1);
        //使用中文字体
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<>();
        fontList.add(bf);
        //取出报表模板中的所有字段
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        for (String key : data.keySet()) {
            if (data.get(key) != null) {
                fields.setField(key, data.get(key).toString());
            }
        }
        ps.setFormFlattening(true);
        ps.close();
        return bos;
    }


    /**
     *
     * @param value 文本
     * @param font 字体
     * @param horizontalAlignment 水平样式 0-left, 1-center, 2-right
     * @param verticalAlignment 垂直样式  4-top, 5-middle, 6-bottom;
     * @param colspan 列合并
     * @param rowspan 行合并
     * @param borderSide 外边框
     *  0-默认
     *  1-隐藏上边框
     *  2-隐藏下边框
     *  3-隐藏上、下边框
     *  4-隐藏左边框
     *  5-隐藏左、上边框
     *  6-隐藏左、下边框
     *  7-隐藏左、上、下边框
     *  8-隐藏右边框
     *  9-隐藏右、上边框
     *  10-隐藏右、下边框
     *  11-隐藏右、上、下边框
     *  12-隐藏左、右边框
     *  13-隐藏上、左、右边框
     *  14-隐藏下、左、右边框
     *  15-隐藏全部
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int horizontalAlignment, int verticalAlignment, int colspan, int rowspan, int borderSide) {
        PdfPCell cell = new PdfPCell();
        cell.setPhrase(new Phrase(value, font));
        //水平居中
        cell.setHorizontalAlignment(horizontalAlignment);
        if(verticalAlignment>0){
            //垂直居中
            cell.setUseAscender(true);
        }
        //垂直居中
        cell.setVerticalAlignment(verticalAlignment);
        if(colspan>0 ){
            cell.setColspan(colspan);
        }
        if(rowspan>0){
            cell.setRowspan(rowspan);
        }
        if(borderSide>0){
            cell.disableBorderSide(borderSide);
        }
        return cell;
    }

    /**
     * 无模板导出PDF
     * @param fileName 导出文件名
     * @param response  返回响应
     * @param data 要打包的数据
     */
    public static void generatePDFDoc(String fileName, HttpServletResponse response, Map<String, Object> data){
        try{
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        // 设置响应头
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition","attachment;fileName=" + fileName + ".pdf");
        OutputStream out = null;
        Document doc = new Document(PageSize.A4);
        try {
            out = response.getOutputStream();
            PdfWriter writer = PdfWriter.getInstance(doc, out);
            doc.open();
            doc = makeSinglePDF(doc,data);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭文档
            if(doc!=null){
                doc.close();
            }
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出Zip压缩文件
     * @param fileName 导出文件名
     * @param response 输出响应
     * @param listData 数据
     */
    public static void generatePDFZip(String fileName, HttpServletResponse response, List<Map<String, Object>> listData) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 设置响应头
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            if (!listData.isEmpty()) {
                for (Map<String, Object> data : listData) {
                    if (data.get("fileName") != null) {
                        fileName = data.get("fileName").toString() + ".pdf";
                    }
                    zipOutputStream.putNextEntry(new ZipEntry(fileName));
                    Document document = new Document();
                    PdfWriter writer = PdfWriter.getInstance(document, zipOutputStream);
                    writer.setCloseStream(false);
                    document.open();
                    document = makeSinglePDF(document,data);
                    document.close();
                    zipOutputStream.closeEntry();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(zipOutputStream != null){
                    zipOutputStream.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成单个PDF文档
     * @param data 数据键值对,根据实际情况修改键名称
     * @return
     */
    private static Document makeSinglePDF(Document doc,Map<String, Object> data){
        try {
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bf, 12, Font.NORMAL, BaseColor.BLACK);
            Font fontTile = new Font(bf, 14, Font.BOLD, BaseColor.BLACK);
            Paragraph paragraph1 = new Paragraph("日常值守记录表", fontTile);
            paragraph1.setAlignment(PdfPCell.ALIGN_CENTER);
            //设置行间距
            paragraph1.setLeading(15f);
            //设置段落下空白
            paragraph1.setSpacingAfter(20f);

            PdfPTable tbText = new PdfPTable(new float[] { 1f, 1.5f, 1f, 0.8f,1.6f, 3f});
            tbText.addCell(createCell("日期:", font, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_LEFT, 0,0,15));
            tbText.addCell(createCell(data.getOrDefault("coamDutyDate"," ") == null ? " " :
                            data.getOrDefault("coamDutyDate"," ").toString(), font,
                    PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_MIDDLE, 0,0,15));
            tbText.addCell(createCell("班次:", font, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_LEFT, 0,0,15));
            tbText.addCell(createCell(data.getOrDefault("coamClassName"," ") == null ? " " :
                            data.getOrDefault("coamClassName"," ").toString(), font,
                    PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_MIDDLE, 0,0,15));
            tbText.addCell(createCell("值守人员:", font, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_LEFT, 0,0,15));
            tbText.addCell(createCell(data.getOrDefault("coamPesonName"," ") == null ? " " :
                            data.getOrDefault("coamPesonName"," ").toString(), font,
                    PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_LEFT, 0,0,15));
            //增加空行
            tbText.addCell(createCell(" ",font,PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_LEFT,6,2,15));
            PdfPTable table = new PdfPTable(new float[] { 1f, 1.5f, 1f, 1.5f});
            //表头
            table.addCell(createCell("开始时间", font, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE, 0,0,0));
            table.addCell(createCell("结束时间", font, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            table.addCell(createCell("运行状态", font, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            table.addCell(createCell("备注", font, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            //动态表格
            table.addCell(createCell(data.getOrDefault("coamClassessStarttime"," ") == null ? " ":
                            data.getOrDefault("coamClassessStarttime"," ").toString(), font,
                    Element.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            table.addCell(createCell(data.getOrDefault("coamClassessEndtime"," ") == null ? " ":
                            data.getOrDefault("coamClassessEndtime"," ").toString(), font,
                    Element.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            table.addCell(createCell(data.getOrDefault("coamRunStatus"," ") == null ? " ":
                            data.getOrDefault("coamRunStatus"," ").toString(), font,
                    Element.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            table.addCell(createCell(data.getOrDefault("coamLogRemark"," ") == null ? " " :
                            data.getOrDefault("coamLogRemark"," ").toString(), font,
                    Element.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE,0,0,0));
            doc.add(paragraph1);
            doc.add(tbText);
            doc.add(table);
        }catch (Exception e){
            e.printStackTrace();
        }
        return doc;
    }

}

到了这里,关于Java导出PDF文档(模板导出和自定义)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java根据word模板生成word文档并转成PDF文件

    定义完我们的模板之后,我们要将文档保存为xml的格式 生成的xml格式看起来比较乱,没有层次感, 所以需要格式化一下 格式化 基础信息的定义 基础信息的定义只要保证我们转化成的xml文件中的${name}等格式没错误即可 表格的定义 遍历实现,表格的数据填充 在xml文件中我们的

    2024年02月09日
    浏览(49)
  • Java实现PDF导出

    需求:使用easyPOI方式导出合同word文档 Word模板和Excel模板用法基本一致,支持的标签也是一致的,仅仅支持07版本的word也是只能生成后缀是docx的文档,poi对doc支持不好所以easyPOI中就没有支持doc,我们就拿docx做导出 这里得好好说说模板中标签的用法: 下面列举下EasyPoi支持的

    2024年02月03日
    浏览(43)
  • Java实现PDF导出功能

    一、添加依赖 二、实现示例代码 如下代码中使用了 【SIMYOU.TTF】幼圆字体,根据需要可以自行下载 三、效果展示 对应目录下生成test.pdf 文件 生成效果如下所示:

    2024年02月15日
    浏览(41)
  • Java实现PDF导出/预览

            网上有很多关于PDF导出的文章,但是个人感觉实现的过于复杂,又是模板又是html的,有的还需要字体模板的支持,本片文章只是实现简单的PDF表格导出,可以实现PDF动态表格导出/预览,这类文章网上很少,就给你们整理一篇吧! 实现思路:本地创建PDF文件 --》打开

    2024年02月16日
    浏览(44)
  • java导出pdf(纯代码实现)

    java导出pdf 在项目开发中,产品的需求越来越奇葩啦,开始文件下载都是下载为excel的,做着做着需求竟然变了,要求能导出pdf。导出pdf倒也不是特别大的问题关键就是麻烦。 导出pdf我知道的一共有3中方法: 方法一:利用模板导出,但是首先编辑模板的工具不好找,现有的国

    2024年02月16日
    浏览(38)
  • Java-根据模板生成PDF

    在有些场景下我们可能需要根据指定的模板来生成 PDF,比如说合同、收据、发票等等。因为 PDF 是不可编辑的,所以用代码直接对 PDF 文件进行修改是很不方便的,这里我是通过 itext 和 Adobe Acrobat 来实现的,以下就是具体实现方法。 Adobe Acrobat 是由 Adobe 公司开发的一款 PDF (

    2024年02月04日
    浏览(50)
  • java使用poi-tl导出word及转换PDF后的合并导出pdf

    为某单位开发的一款项目申报审批系统,用户需求在申报阶段填写的信息资料能够导出PDF。且项目申报的报告正文为用户上传,所以需要合并导出。 在项目初期阶段使用的是PDF的预设模板导出,因为以前使用过,比较熟悉。所以优先选择此方法,但项目测试阶段发现问题,因

    2024年02月06日
    浏览(70)
  • Java导出PDF(itextpdf)-通俗易懂

    在java开发的过程中会遇到太多太多文档pdf导出,excle导出等业务场景,时隔三个月或半年来一次每一次遇到这样的业务场景对我都是非常痛苦的过程,本文旨在记录工具类使用方法和技术分享。 itextpdf是一个开源的Java库,用于创建和操作PDF文档。使用itextpdf,您可以创建新的

    2024年02月12日
    浏览(40)
  • Java + React导出Excel/PDF

    前言 在B/S架构中,服务端导出是一种高效的方式。它将导出的逻辑放在服务端,前端仅需发起请求即可。通过在服务端完成导出后,前端再下载文件完成整个导出过程。服务端导出具有许多优点,如数据安全、适用于大规模数据场景以及不受前端性能影响等。 本文将使用前

    2024年02月10日
    浏览(34)
  • java集成itextpdf实现通过pdf模板填充数据生成pdf

    我采用的是pdfelement 官网地址需要付费或者自行破解,也可以使用其他pdf编辑器。 将制作好的pdf模板放入项目resources/pdf目录下,如图 浏览器访问ip:port/test/pdf,其中ip为你的ip地址,port为你的端口,访问结果如下:

    2024年02月16日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包