Java使用XWPFTemplate将word填充数据,并转pdf

poi-tl

poi-tl(poi template language)是基于Apache POI的Word模板引擎。纯Java组件,跨平台,代码短小精悍,通过插件机制使其具有高度扩展性。

主要处理区域有这么几个模块:

依赖

<dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.0.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

1、基本介绍

1.1、 根据文件路径、文件、文件流几种方式获取XWPFTemplate

//文件路径
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);

//文件
File wordtemplate = new File(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);

//文件流
InputStream wordtemplate = new FileInputStream(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);



1.2、生成到文件路径或者是流

//生成到文件路径
template.writeToFile(outFilePath);
template.close();


//生成到流
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();

//关闭资源
out.close();
template.close();

修改变量 为 ${var}

File inDocxFile = new File(inDocxFilePath);
Configure configure = Configure.newBuilder().buildGramer("${", "}").build();
XWPFTemplate template = XWPFTemplate.compile(inDocxFile, configure).render(map);

2、模板

2.1、文本、对象

TextRenderData、HyperLinkTextRenderData

Map<String, Object> map = new HashMap<>();
    // 1、普通字符
    map.put("word", "helloWord");

    //2、配置格式
    Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();
    map.put("author", new TextRenderData("HealerJean", style));

    //3、超链接
    map.put("website", new HyperLinkTextRenderData("website.", "http://www.baidu.com"));

    //制作模板
    XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(map);

    //开始生成新的word
    FileOutputStream outputStream = new FileOutputStream(outDocxFilePath);
    template.write(outputStream);
    outputStream.flush();

    //关闭资源
    outputStream.close();
    template.close();

2.2、图片

PictureRenderData

String imagePath = "D:/pdf/image.png";
    Map<String, Object> map = new HashMap<>();

    // 本地图片
    map.put("localPicture", new PictureRenderData(120, 120, imagePath));

    // 图片流文件
    InputStream inputStream = new FileInputStream(imagePath);
    map.put("localBytePicture", new PictureRenderData(100, 120, ".png", inputStream));

    // 网络图片
    map.put("urlPicture", new PictureRenderData(100, 100, ".png", BytePictureUtils.getUrlBufferedImage("https://raw.githubusercontent.com/HealerJean/HealerJean.github.io/master/assets/img/tctip/weixin.j跑pg")));

    // java 图片
    BufferedImage bufferImage = ImageIO.read(new FileInputStream(imagePath));
    map.put("bufferImagePicture", new PictureRenderData(100, 120, ".png", bufferImage));


    //如果希望更改语言前后缀为 ${var}
    Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
    XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);


    //开始生成新的word
    template.writeToFile(outDocxFilePath);
    template.close();

2.3、表格

MiniTableRenderData

Map<String, Object> map = new HashMap<>();

    Table table1 = new Table("11", "12", "13");
    Table table2 = new Table("21", "22", "23");
    List<Table> table = new ArrayList<>();
    table.add(table1);
    table.add(table2);

    // RowRenderData header = RowRenderData.build("one", "two", "three");
    //使用样式
    Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();
    RowRenderData header = RowRenderData.build(
        new TextRenderData("one", style), 
        new TextRenderData("two"), 
        new TextRenderData("three"));

    List<RowRenderData> tableBody = new ArrayList<>();
    for (Table item : table) {
        RowRenderData row = RowRenderData.build(
            item.getOne(), 
            item.getTwo(), 
            item.getThree());
        
        tableBody.add(row);
    }
    map.put("table", new MiniTableRenderData(header, tableBody));


    Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
    XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);
    template.writeToFile(outDocxFilePath);
    template.close();

2.4、列表模板

NumbericRenderData

Map<String, Object> map = new HashMap<>();

        map.put("unorderlist", new NumbericRenderData(
            new ArrayList<TextRenderData>()));
        map.put("orderlist", new NumbericRenderData
                (NumbericRenderData.FMT_DECIMAL, new ArrayList<TextRenderData>()));


        //如果希望更改语言前后缀为 ${var}
        Configure builder = Configure.newBuilder().buildGramer("${", "}").build();
        XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, 
                                                     builder).render(map);
        template.writeToFile(outDocxFilePath);
        template.close();

3、配置

ConfigureBuilder builder = Configure.newBuilder();
XWPFTemplate.compile("~/template.docx", builder.buid());

3.1、图片语法@修改为%

builder.addPlugin('%', new PictureRenderPolicy());

3.2、语法加前缀 为${var}

builder.buildGramer("${", "}");

3.3、模板标签设置正则表达式规则

模板标签支持中文、字母、数字、下划线的组合,比如,我们可以通过正则表达式来配置标签的规则,比如不允许中文:

builder.buildGrammerRegex("[\\w]+(\\.[\\w]+)*");

下面为我在工作中的应用:

生成word:

Map<String, Object> datas = new HashMap<String, Object>() {
{
//时间
put("year", year);
put(pNames[j] + "_" + vNames[j] + "_img_zhpf_4", new PictureRenderData(500, 300, pyhon_img_path + pNames[j] + "_" + vNames[j].replace("_", "-") + "_" + "comprehensive_score_" + element + "_4.png"));
}
};
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();
out.close();
template.close();

转pdf:

public static boolean getLicense() {
        boolean result = false;
        try {
            File directory = new File("");// 参数为空
            String courseFile = directory.getCanonicalPath();//获取项目根目录
//            File file = new File("/temp/qh_assess/java_pro/config/license.xml"); // 新建一个空白pdf文档
            File file = new File(courseFile + "/config/license.xml"); // 新建一个空白pdf文档
            InputStream is = new FileInputStream(file); // license.xml找个路径放即可。
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

license.xml

<?xml version="1.0" encoding="UTF-8" ?>
<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

这是默认生成的水印

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用iTextPDF生成pdf填充自定义数据的步骤如下: 1. 首先,获取需要生成pdf的初始模板,包含格式,但不包含数据。可以使用工具如Adobe Acrobat来编辑pdf模板,在对应区域生成文本域,为每个域设置一个唯一的名称。 2. 在Java代码中,使用iTextPDF库来对pdf进行操作。首先,需要获取PdfReader对象,将模板文件加载为PdfReader对象。可以使用以下代码: ```java PdfReader reader = new PdfReader(templatePath); // templatePath是模板pdf文件的路径 ``` 3. 接下来,使用PdfStamper对象来填充数据并生成最终的pdf文件。可以使用以下代码: ```java PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPath)); // outputPath是生成的pdf文件的路径 AcroFields fields = stamper.getAcroFields(); // 使用fields对象来填充文本域的数据 fields.setField("fieldName1", "fieldValue1"); fields.setField("fieldName2", "fieldValue2"); // 继续填充其他文本域的数据 // 最后,调用stamper的close方法来保存并关闭pdf文件 stamper.close(); ``` 4. 通过上述步骤,你可以使用iTextPDF将自定义数据填充pdf模板中,并生成最终的pdf文件。 请注意,以上代码只展示了主要的方法代码,并不是整个流程的逻辑代码。具体的实现可能会根据具体的需求和模板结构有所不同。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [java使用itextpdf生成pdf填充自定义数据](https://blog.csdn.net/qq_34244426/article/details/104833805)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

糕手慕辰

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

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

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

打赏作者

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

抵扣说明:

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

余额充值