poi_tl以模板方式生成word以及转pdf

pot_tl所需依赖

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.10.0</version>
</dependency>
模板如下:

public static void main(String[] args) {
      
        DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        Resource resource = defaultResourceLoader.getResource("classpath:template/dd.docx");
        try {

            File file = resource.getFile();
            Map<String, Object> data = genData();
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            //创建一个列表的规则
            Configure config = Configure.builder().bind("dataList", policy).build();

            String fileName = vo.getBuildName() + vo.getReportTime() + vo.getReportType();
            XWPFTemplate template = XWPFTemplate.compile(file, config).render(data);
            FileOutputStream outputStream = new FileOutputStream(new File("E:\\项目\\result_1.docx"));
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            template.write(fos);
            byte[] bytes = fos.toByteArray();
            template.write(outputStream);
            Word2PdfAsposeUtil.doc2pdf(bytes, "E:\\项目\\result_1.pdf");
            outputStream.flush();
            outputStream.close();
            fos.flush();
            fos.close();
            template.close();
            log.info("生成报表结束");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

public static Map<String, Object> genData() {
        HashMap<String, Object> data = Maps.newHashMap();
        data.put("picture", new PictureRenderData(600, 900, "E:\\项目\\cover.png"));
        data.put("reportTime", "2024/04/10");
        // 列表
        List<EdpEnergyReportVo.CollectData> dataList = getCollectData();

        data.put("dataList", dataList);

        return data;
    }
 private static List<EdpEnergyReportVo.CollectData> getCollectData() {
        List<EdpEnergyReportVo.CollectData> dataList = new ArrayList<>();
        EdpEnergyReportVo.CollectData data1 = new EdpEnergyReportVo.CollectData();
        data1.setCollectDate("2024-04-10 01:00");
        data1.setEnergyTotal(new BigDecimal("456.2"));
        data1.setOutletEnergy(new BigDecimal("456"));
        data1.setAirEnergy(new BigDecimal("235"));
        data1.setPowerEnergy(new BigDecimal("467"));
        data1.setSpecialEnergy(new BigDecimal("367"));
        data1.setWaterVolume(new BigDecimal("898"));

        EdpEnergyReportVo.CollectData data2 = new EdpEnergyReportVo.CollectData();
        data2.setCollectDate("2024-04-10 02:00");
        data2.setEnergyTotal(new BigDecimal("456.2"));
        data2.setOutletEnergy(new BigDecimal("456"));
        data2.setAirEnergy(new BigDecimal("235"));
        data2.setPowerEnergy(new BigDecimal("467"));
        data2.setSpecialEnergy(new BigDecimal("367"));
        data2.setWaterVolume(new BigDecimal("898"));
        EdpEnergyReportVo.CollectData data3 = new EdpEnergyReportVo.CollectData();
        data3.setCollectDate("2024-04-10 03:00");
        data3.setEnergyTotal(new BigDecimal("456.2"));
        data3.setOutletEnergy(new BigDecimal("456"));
        data3.setAirEnergy(new BigDecimal("235"));
        data3.setPowerEnergy(new BigDecimal("467"));
        data3.setSpecialEnergy(new BigDecimal("367"));
        data3.setWaterVolume(new BigDecimal("898"));
        EdpEnergyReportVo.CollectData data4 = new EdpEnergyReportVo.CollectData();
        data4.setCollectDate("总计");
        data4.setEnergyTotal(new BigDecimal("1456.2"));
        data4.setOutletEnergy(new BigDecimal("1456"));
        data4.setAirEnergy(new BigDecimal("1235"));
        data4.setPowerEnergy(new BigDecimal("1467"));
        data4.setSpecialEnergy(new BigDecimal("1367"));
        data4.setWaterVolume(new BigDecimal("1898"));
        dataList.add(data1);
        dataList.add(data2);
        dataList.add(data3);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);
        dataList.add(data4);

        return dataList;
    }

效果:

word 转pdf

使用aspose-words-16.8.0-jdk16.jar的方式转换

依赖:

<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>16.8.0</version>
            <scope>system</scope>
            <!--路径是aspose-words-15.8.0-jdk16包放的路径-->
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-16.8.0-jdk16.jar</systemPath>
        </dependency>

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>

jar包可以在网上找或者找我要

public class Word2PdfAsposeUtil {

    public static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("license.xml")) {
            
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            log.error("获取licence错误", e);
        }
        return result;
    }

    public static void doc2pdf(byte[] bytes, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        FileOutputStream os = null;
        try {


            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            Document document = new Document(inputStream);
            if (SystemUtils.IS_OS_LINUX) {
                //设置汉字字体,否则转换后的文档汉字会乱码。
                FontSettings settings = new FontSettings();
                settings.setFontsFolder("C:\\Windows\\Fonts", false);
                document.setFontSettings(settings);
            }
            document.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
           log.error("pdf转换错误", e);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("pdf转换错误", e);
                }
            }
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当使用Poi-tl库根据Word模板填充内容生成Word文档时,可以使用Poi-tl提供的模板语法来处理空值。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.HeaderFooterType; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordTemplateFiller { public static void main(String[] args) { try { // 加载Word模板文件 FileInputStream templateStream = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(templateStream); // 填充内容 Map<String, Object> placeholders = new HashMap<>(); placeholders.put("name", "John Doe"); placeholders.put("age", "30"); placeholders.put("address", ""); replacePlaceholders(document, placeholders); // 保存填充后的文档 FileOutputStream outputStream = new FileOutputStream("filled_template.docx"); document.write(outputStream); outputStream.close(); System.out.println("Word文档生成成功!"); } catch (IOException e) { e.printStackTrace(); } } private static void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, Object> entry : placeholders.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; if (text.contains(placeholder)) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { text = text.replace(placeholder, value.toString()); } else { text = text.replace(placeholder, ""); // 替换为空字符串 } run.setText(text, 0); } } } } } } } ``` 在上述代码中,我们首先加载Word模板文件,然后定义了一个`placeholders`的映射,其中包含了要替换的占位符和对应的值。接下来,我们调用`replacePlaceholders`方法来替换文档中的占位符。 在`replacePlaceholders`方法中,我们遍历文档中的每个段落和文本运行,通过检查文本内容中是否包含占位符来确定是否需要替换。如果找到了匹配的占位符,则根据占位符对应的值来进行替换。如果值不为空且非空字符串,则将占位符替换为对应的值;如果值为空或空字符串,则将占位符替换为空字符串。 请注意,上述代码中使用的占位符格式为`${placeholder}`,你可以根据实际情况修改为其他格式。 以上是一个基本示例,你可以根据自己的需求进行修改和扩展。同时,需要确保在项目中添加了Poi-tl的依赖库。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值