java生成PDF

不废话,直接上代码:

依赖jar包

<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.12</version>
</dependency>
<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.23</version>
</dependency>
PdfUtils类:

package com.brank.practice.brankyang.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangbo
 * @version 1.0
 * Created 2019/2/22 17:45
 **/
public class PdfUtils {
    private static final String FONT = "/sim-hei.ttf";//黑体字
    private static final String HTML = "/test.html";//模板html文件位置
    private static final String PDF="target/result.pdf";//目标pdf文件
    private static Configuration freemarkerCfg = null;
    static {
        freemarkerCfg =new Configuration();
        //freemarker的模板目录
        try {
            freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        Map<String,String> data=new HashMap<String, String>();
        StringBuffer message=new StringBuffer();
        message.append("输入你想写的文字");
        data.put("message",message.toString());//
        String content=freeMarkerRender(data,HTML);//替换html中的参数
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDF));
        document.open();
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(FONT);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);
        document.close();
    }
    private static String freeMarkerRender(Map<String,String> data, String htmlTmp){
        Writer out = new StringWriter();
        try {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(htmlTmp);
            template.setEncoding("UTF-8");
            // 合并数据模型与模板
            template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
}
PathUtil类:

package com.brank.practice.brankyang.utils;

import java.io.File;

/**
 * @author yangbo
 * @version 1.0
 * Created 2019/2/22 16:26
 **/
public class PathUtil {
    public static String getCurrentPath() {

        Class<?> caller = getCaller();
        if (caller == null) {
            caller = PathUtil.class;
        }

        return getCurrentPath(caller);
    }


    private static Class<?> getCaller() {
        StackTraceElement[] stack = (new Throwable()).getStackTrace();
        if (stack.length < 3) {
            return PathUtil.class;
        }
        String className = stack[2].getClassName();
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前路径
     * @param cls
     * @return
     */
    public static String getCurrentPath(Class<?> cls) {
        String path = cls.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.replaceFirst("file:/", "");
        path = path.replaceAll("!/", "");
        if (path.lastIndexOf(File.separator) >= 0) {
            path = path.substring(0, path.lastIndexOf(File.separator));
        }
        if ("/".equalsIgnoreCase(path.substring(0, 1))) {
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.contains("window")) {
                path = path.substring(1);
            }
        }
        return path;
    }
}

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <style>
        body{
            font-family:SimHei;
        }
        .blue{
            color: black;
        }
        .pos{
            position:absolute;
            left:100px;
            top:150px
        }
    </style>
</head>
<body>
      <center><H1>文件标题</H1></center>
      <br/>
      <div class="blue pos">
          <font size="6">你想说点啥吗: </font>${message}
      </div>
      <br/>
      <div>文件结尾。</div>

</body>
</html>

文件存放位置截图:

java生成PDF

生成文件位置:

java生成PDF

效果图:

java生成PDF

sim-hei.ttf文件见我的附件