java 模板转 PDF

本文介绍了如何使用iText库和FreeMarker模板引擎将HTML转换为PDF。首先,通过引入相关依赖,然后创建HTML模板,接着定义一个实体类来填充模板数据,最后编写转换工具类实现HTML到PDF的转换。文中提供的代码示例详细展示了整个过程,并成功生成了PDF文件。
摘要由CSDN通过智能技术生成

首先思路是把html转成pdf,如果是用word转的话首先需要把word转成html,然后再将html转成word,下面附上word转html的地址Word转HTML——免费在线Word转网页

1.首先第一步我们需要导入的maven坐标

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.11</version>
</dependency>
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.11</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf</artifactId>
    <version>9.0.9</version>
</dependency>

2.第二步需要一个HTML模板

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <meta name="generator" content="Aspose.Words for .NET 15.1.0.0" />
    <title></title></head><body><div><p style="margin:0pt">
        <span style="color:#333333; font-family:sans-serif; font-size:8pt; font-style:normal; text-transform:none">&#xa0;
        </span></p><p style="margin:0pt; text-align:center">
        <span style="color:#333333; font-family:宋体; font-size:18pt; font-style:normal; text-transform:none">
            全国大赛</span></p><p style="margin:0pt">
        <span style="font-family:宋体; font-size:14pt; font-style:normal; font-weight:normal; text-decoration:underline; text-transform:none">比赛海报</span>
        <span style="font-family:sans-serif; font-size:14pt; font-style:normal; font-weight:normal; text-decoration:underline; text-transform:none">:</span>
        <span style=" font-size:14pt; font-style:normal; font-weight:normal; text-decoration:underline; text-transform:none"><img src="${gua.name}#pic_center" alt="" /></span></p><p style="margin:0pt">
        <span style="font-family:宋体; font-size:14pt; font-style:normal; text-decoration:underline; text-transform:none">地点:</span>
        <span style="font-family:宋体; font-size:14pt; font-style:normal; text-decoration:underline; text-transform:none">${gua.add} </span></p>
        <p style="margin:0pt"><span style="font-family:宋体; font-size:14pt; font-style:normal; text-decoration:underline; text-transform:none">主持人:</span>
        <span style="font-family:宋体; font-size:14pt; font-style:normal; text-decoration:underline; text-transform:none">${gua.cname} </span></p>
        <p style="margin:0pt"><span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">year:</span>
        <span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">${gua.year} </span></p>
    <p style="margin:0pt"><span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">month:</span>
        <span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">${gua.month} </span></p>
    <p style="margin:0pt"><span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">day:</span>
        <span style="font-family:sans-serif; font-size:14pt; font-style:normal; text-decoration:none; text-transform:none">${gua.day} </span></p>
        <p style="margin:0pt; orphans:0; text-align:justify; widows:0"><span style="font-family:Calibri; font-size:10pt">&#xa0;</span></p>
        <p style="margin:0pt; orphans:0; text-align:justify; widows:0"><span style="font-family:Calibri; font-size:12pt">&#xa0;</span></p></div>
        <div class="cnzz" style="display: none;">
</div></body></html>

 文件名是以.ftl结尾的

3.第三步需要一个实体类用来填充模板上的动态数据

package com.hzcxdy.enforce.business.controller.clouddiscuss;

import lombok.Data;
@Data
public class Guarantee {
    //姓名
    private String name;
    //地点
    private String add;
    //主持人
    private String cname;
    //年
    private String year;
    //月
    private String month;
    //日
    private String day;
}

 

4.第四步就是转换的工具类了

package com.hzcxdy.enforce.business.controller.clouddiscuss;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class ParseHtml {
    public static final String HTML = "X:\\XXX\\test.ftl";//HTML模板路径
    public static final String DEST = "X:\\XXX\\hero.pdf";//输出pdf文件路径
    public static final String path = "X:\\XXX";//HTML模板路径不包含文件
    public static final String ftlName = "test.ftl";//HTML模板文件名

    public void createPdf(String file){
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,new ByteArrayInputStream(getHtmlString().getBytes()), Charset.forName("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException("html转换成pdf时发生异常");
        }finally {
            document.close();
        }
    }

    public String getHtmlString(){
        //填充模板变量
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        Guarantee gua = new Guarantee();
        int year = calendar.get(Calendar.YEAR);
        gua.setYear(String.valueOf(year));
        int month = calendar.get(Calendar.MONTH) + 1;
        gua.setMonth(String.valueOf(month));
        int day = calendar.get(Calendar.DATE);
        gua.setDay(String.valueOf(day));
        gua.setAdd("湘北高中");
        gua.setCname("樱木花道");
        gua.setName("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fatt2.citysbs." +
                "com%2Fhangzhou%2Fsns01%2Fforum%2F2010%2F10%2F28-11%2Fmiddle_20101028_948d2" +
                "a1897aced0d191d7WIoyS8kparS.jpg&refer=http%3A%2F%2Fatt2.citysbs.com&app=2002&" +
                "size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636337699&t=0aa199327c83afe3027cfa0ac3959e5a");
        Map<String, Object> map = new HashMap<>();//构建模板所需数据
        map.put("gua", gua);

        //模板转换输出转换好的html
        Writer writer = null;
        String htmlContent = "";
        try {
            //创建freeMarker配置实例
            Configuration configuration = new Configuration(Configuration.getVersion());
            // 获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(path));
            //设置模板编码格式
            configuration.setDefaultEncoding("UTF-8");
            configuration.setNumberFormat("#.#######");
            //加载模版文件
            Template template = configuration.getTemplate(ftlName);
            writer = new StringWriter();
            //替换模板
            template.process(map, writer);
            //获取内容
            htmlContent = writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("模板转换失败");
        } finally {
            try {
                if (null != writer) {
                    writer.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return htmlContent;
    }

public static void main(String[] args){
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new ParseHtml().createPdf(DEST);
}
}

下面附上运行生成的pdf文件

这个方法也是花了一天的时间才总结出来的,亲测有效,各位童鞋多多支持点赞欢迎转发!!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值