通过poi,jar包制作模板动态的生成word文档。支持转换成pdf格式文档

本文介绍如何使用Java和相关库动态生成Word文档,并将其转换为PDF格式。支持模板填充及图片插入等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过poi,jar包制作模板动态的生成word文档。支持转换成pdf格式文档

//    用于动态的导出word文档
    // https://mvnrepository.com/artifact/cn.afterturn/easypoi-annotation
    compile group: 'cn.afterturn', name: 'easypoi-annotation', version: '4.2.0'
// https://mvnrepository.com/artifact/cn.afterturn/easypoi-base
    compile group: 'cn.afterturn', name: 'easypoi-base', version: '4.2.0'
// https://mvnrepository.com/artifact/cn.afterturn/easypoi-web
    compile group: 'cn.afterturn', name: 'easypoi-web', version: '4.2.0'
    //用于导出生成pdf
    // https://mvnrepository.com/artifact/com.itextpdf/itextpdf
    compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13.2'
//    中文字体
// https://mvnrepository.com/artifact/com.itextpdf/itext-asian
    compile group: 'com.itextpdf', name: 'itext-asian', version: '5.2.0'

使用之前我们先导入poi、jar包

以下为通过模板动态的生成word格式文档

/**
     * 导出word格式报告
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.POST, value = "/deriveWord")
    public void GenerateWord(HttpServletRequest request,
                      HttpServletResponse response) throws Exception {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("id", 5);
            map.put("sykt", "test课题");
            ImageEntity img = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img", img);
            ImageEntity img2 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img2", img2);
            ImageEntity img3 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img3", img3);
            ImageEntity img4 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img4", img4);
            List<Map<String,Object>> student = new ArrayList();
            Map<String,Object> m = new HashMap();
            m.put("name", "徐江涛");
            m.put("chinese", 88.5);
            m.put("math", 95);
            Map<String,Object> m2 = new HashMap();
            m2.put("name", "考试成绩");
            m2.put("chinese", 82.5);
            m2.put("math", 93);
            student.add(m);
            student.add(m2);
            map.put("student", student);
            XWPFDocument word07 = WordExportUtil.exportWord07("templates/Hello word.docx", map);
            OutputStream outputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.docx");
            word07.write(outputStream);
            outputStream.flush();
            outputStream.close();
            renderResult(response, "word模板生成成功");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        renderResult(response, "word模板生成失败");
    }

生成word转pdf文件

@RequestMapping(method = RequestMethod.POST, value = "/GenerateWordConvertPdf")
    public void GenerateWordConvertPdf(HttpServletRequest request,
                            HttpServletResponse response) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("id", 5);
            map.put("sykt", "test课题");
            ImageEntity img = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img", img);
            ImageEntity img2 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img2", img2);
            ImageEntity img3 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img3", img3);
            ImageEntity img4 = new ImageEntity("C:\\Users\\Administrator\\Desktop\\tx.jpg", 100, 100);
            map.put("img4", img4);
            List<Map<String,Object>> student = new ArrayList();
            Map<String,Object> m = new HashMap();
            m.put("name", "徐江涛");
            m.put("chinese", 88.5);
            m.put("math", 95);
            Map<String,Object> m2 = new HashMap();
            m2.put("name", "考试成绩");
            m2.put("chinese", 82.5);
            m2.put("math", 93);
            student.add(m);
            student.add(m2);
            map.put("student", student);
            XWPFDocument word07 = WordExportUtil.exportWord07("templates/Hello word.docx", map);
            OutputStream outputStream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.docx");
            word07.write(outputStream);
            outputStream.flush();
            outputStream.close();
            PDFUtil.WordConvertPdf("C:\\Users\\Administrator\\Desktop\\test.docx","C:\\Users\\Administrator\\Desktop\\test.pdf");
            renderResult(response, "pdf模板生成成功");
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        renderResult(response, "pdf模板生成失败");

    }

通过模板生成pdf文件

/**
     * 导出pdf格式报告
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.POST, value = "/derivePdf")
    public void GeneratePdf(HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        try {
            //key为pdf模板的form表单的名字,value为需要填充的值
            data.put("pxsj", "2018-10-8至2020-5-23");
            data.put("xm", "徐江涛");
            data.put("rq", "2020-1-15");
            PDFUtil.generatePDF(pdfTemplatePath,
                    generatePdfPath, data);
            renderResult(response, "pdf模板生成成功");
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        renderResult(response, "pdf模板生成失败");

    }

word装pdf静态方法和生成pdf文件静态方法如下

/**
     * @param templatePdfPath 模板pdf路径
     * @param generatePdfPath 生成pdf路径
     * @param data            数据
     */
    public static String generatePDF(String templatePdfPath, String generatePdfPath, Map<String, String> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            File file = new File(generatePdfPath);
            if (file.exists())
            {
                file.delete();
            }
            PdfReader reader = new PdfReader(templatePdfPath);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data);
            /* 必须要调用这个,否则文档不会生成的  如果为false那么生成的PDF文件还能编辑,一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();
            fos = new FileOutputStream(generatePdfPath);
            fos.write(bos.toByteArray());
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void WordConvertPdf(String sourcePath,String targetPath){
        Document document = new Document();
        document.loadFromFile(sourcePath);

//        //创建一个参数
//        ToPdfParameterList toPdf = new ToPdfParameterList();
//
//        //设置密码
//        String password = "abc123";
//        toPdf.getPdfSecurity().encrypt(password, password, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit);

        //保存文档.
        document.saveToFile(targetPath);

    }

用到的pdfutil工具类如下

package com.mosukj.util;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.AcroFields.Item;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.spire.doc.Document;

public class PDFUtil {


    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if (formFields.containsKey(key)) {
                String value = data.get(key);
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        Iterator<String> itemsKey = formFields.keySet().iterator();
        while (itemsKey.hasNext()) {
            String itemKey = itemsKey.next();
            if (!keys.contains(itemKey)) {
                fields.setField(itemKey, " ");
            }
        }
    }

    /**
     * @param templatePdfPath 模板pdf路径
     * @param generatePdfPath 生成pdf路径
     * @param data            数据
     */
    public static String generatePDF(String templatePdfPath, String generatePdfPath, Map<String, String> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            File file = new File(generatePdfPath);
            if (file.exists())
            {
                file.delete();
            }
            PdfReader reader = new PdfReader(templatePdfPath);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data);
            /* 必须要调用这个,否则文档不会生成的  如果为false那么生成的PDF文件还能编辑,一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();
            fos = new FileOutputStream(generatePdfPath);
            fos.write(bos.toByteArray());
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void WordConvertPdf(String sourcePath,String targetPath){
        Document document = new Document();
        document.loadFromFile(sourcePath);

//        //创建一个参数
//        ToPdfParameterList toPdf = new ToPdfParameterList();
//
//        //设置密码
//        String password = "abc123";
//        toPdf.getPdfSecurity().encrypt(password, password, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit);

        //保存文档.
        document.saveToFile(targetPath);

    }

    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        //key为pdf模板的form表单的名字,value为需要填充的值
        data.put("pxsj", "2018-10-8至2020-5-23");
        data.put("xm", "徐江涛");
        data.put("rq", "2020-1-15");

        generatePDF("templates/templates.pdf",
                "C:\\Users\\Administrator\\Desktop\\filled.pdf", data);
    }
}

需要用到的jar包,请前往我的资源下载。

第二种word转pdf(无水印)

本地jar包下载(网盘)

工具包
链接:https://pan.baidu.com/s/1uF9CZMXD_xHzG53ORhdMRg
提取码:d4pg
复制这段内容后打开百度网盘手机App,操作更方便哦

工具方法

public static String docPdf(String inPath, String outPath)   {

        if (!isWordLicense()) {
            return null;
        }

        try {
            String path = outPath.substring(0, outPath.lastIndexOf(File.separator));
            File file = null;
            file = new File(path);
            if (!file.exists()) {//创建文件夹
                file.mkdirs();
            }
            file = new File(outPath);// 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            com.aspose.words.Document doc = new com.aspose.words.Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
        } catch (Exception e) {
            e.printStackTrace();
        }
        // EPUB, XPS, SWF 相互转换
        return outPath;
    }


    /**
     * @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记
     */
    public static boolean isWordLicense() {
        boolean result = false;
        try {
            // InputStream inputStream = new
            // FileInputStream("D:\\Workspaces\\TestFilters\\lib\\license.xml");
            // 避免文件遗漏
            String licensexml = "<License>\n" + "<Data>\n" + "<Products>\n"
                    + "<Product>Aspose.Total for Java</Product>\n" + "<Product>Aspose.Words for Java</Product>\n"
                    + "</Products>\n" + "<EditionType>Enterprise</EditionType>\n"
                    + "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
                    + "<LicenseExpiry>20991231</LicenseExpiry>\n"
                    + "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" + "</Data>\n"
                    + "<Signature>\n"
                    + "sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=\n"
                    + "</Signature>\n" + "</License>";
            InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

需要用的模板如下
在这里插入图片描述
在这里插入图片描述
导出如图:
在这里插入图片描述

pdf模板如下
在这里插入图片描述
需要使用adboe旗下的pdf文件管理软件新建文本域,代码中通过文本域动态得生成pdf文档

如有不对得地方,请告知。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

languageStudents

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值