项目demo:https://download.csdn.net/download/my_blankness/10579624
1、velocity获得html页面
2、填充html页面的字段数据
3、itext将html转换成pdf
simsun.tcc为字体,自行网上下载
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itext.demo</groupId>
<artifactId>ITextPdfDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ITextPdfDemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<logback.version>1.1.7</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/kernel -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-core -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-core</artifactId>
<version>9.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf-itext5 -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
debt-listing-apply.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>挂牌申请书</title>
<style>
@page {
size: 8.5in 11in;
@bottom-right {
content: counter(page);
}
}
*{margin:0;padding:0;}
body{font-family:'SimSun';font-size:10.5pt;}/*宋五*/
li{list-style:none;}
h1{font-size:15.75pt;}/*黑三*/
h2{font-size:12pt;}/*宋小四*/
p{line-height:2;}
.pull-right{float:right;}
.pull-left{float:left;}
.clearfix:after{clear:both;content:'';display:block;}
.text-center{text-align:center;}
.text-right{text-align:right;}
.text-indent{text-indent:2em;}
.page-mark{page-break-after:always;}
.table{border-collapse:collapse; margin:0 auto; width:520pt;width:100%;table-layout:fixed;}
.table td{border:0.75pt solid #000;padding:0 5.03pt;font-weight:normal;line-height:20.8pt;word-break: break-word;}
.table th{background-color:#fff;line-height:20.8pt;}
td.bor,span.bor{border-bottom:1px solid #000;padding:0 10px;}
.seal-leaguer{position:absolute;right:50px;top:-45px;}
.apply-type li{width:50%;}
.apply-type span{display:inline-block;width:14px;height:14px;vertical-align:text-bottom;background:url(/data/App/jgoms.cfaoe.local/purple.png) no-repeat;margin-right:5px;}
.apply-type .checked span{background-position:0 -14px;}
</style>
</head>
<body>
<div style="padding:20px;" class="clearfix">
<h1 class="text-center">债务融资计划挂牌交易申请书</h1><br /><br />
<table style="width:100%;table-layout:fixed;">
<col style="width:15%" />
<col style="width:15%" />
<col style="width:20%" />
<col style="width:15%" />
<col style="width:15%" />
<col style="width:20%" />
<tbody>
<tr>
<td colspan="2">申请机构(主承销商):</td>
<td align="center" colspan="4" class="bor">$!{companyName}</td>
</tr>
<tr>
<td colspan="6"><br/></td>
</tr>
<tr>
<td>会员编号:</td>
<td align="center" colspan="2" class="bor">$!{userCode}</td>
<td>申请书编号:</td>
<td align="center" colspan="2" class="bor">$!{projectCode}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
PdfUtils.java
package com.itextpdf.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.logging.log4j.core.util.FileUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
public class PdfUtils {
public static final void htmlToPdf(String htmlContent, String filePath) throws Exception {
FileUtils.mkdir(new File(filePath).getParentFile(), true);
try (OutputStream fileStream = new FileOutputStream(filePath)) {
ITextRenderer textRenderer = new ITextRenderer();
ITextFontResolver fontResolver = textRenderer.getFontResolver();
String agreementBody = htmlContent;
agreementBody = agreementBody.replace(" ", " ");
agreementBody = agreementBody.replace("–", "–");
agreementBody = agreementBody.replace("—", "—");
agreementBody = agreementBody.replace("‘", "‘"); // left single quotation mark
agreementBody = agreementBody.replace("’", "’"); // right single quotation mark
agreementBody = agreementBody.replace("‚", "‚"); // single low-9 quotation mark
agreementBody = agreementBody.replace("“", "“"); // left double quotation mark
agreementBody = agreementBody.replace("”", "”"); // right double quotation mark
agreementBody = agreementBody.replace("„", "„"); // double low-9 quotation mark
agreementBody = agreementBody.replace("′", "′"); // minutes
agreementBody = agreementBody.replace("″", "″"); // seconds
agreementBody = agreementBody.replace("‹", "‹"); // single left angle quotation
agreementBody = agreementBody.replace("›", "›"); // single right angle quotation
agreementBody = agreementBody.replace("‾", "‾"); // overline
fontResolver.addFont("/fonts/simsun.ttc", com.itextpdf.kernel.pdf.PdfName.IdentityH.getValue(), false);
textRenderer.setDocumentFromString(agreementBody, null);
textRenderer.layout();
textRenderer.createPDF(fileStream, true);
}
}
}
ITextPdf.java
package com.itextpdf.demo;
import java.io.File;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class ITextPdf {
public String generateContract() throws Exception {
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "class");
//设置velocity资源加载方式为file时的处理类
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//实例化一个VelocityEngine对象
VelocityEngine velocityEngine=new VelocityEngine(properties);
String vm = "template/debt-listing-apply.html";
//设置生成pdf文件所在的文件夹位置,若没有,则自动生成
File destPathFile = new File("C:/PdfTest/templates/");
if (!destPathFile.exists()) {
destPathFile.mkdirs();
}
//目标文件,即生成的pdf文件的路径,文件名称自己取
String destFilePath = destPathFile + File.separator + "templatePdf.pdf";
VelocityContext context = new VelocityContext();
context.put("companyName", "黎明制造业");
context.put("userCode", "1110000111555555");
context.put("projectCode", "159848787861513");
StringWriter stringWriter = new StringWriter();
velocityEngine.mergeTemplate(vm, "UTF-8", context, stringWriter);
PdfUtils.htmlToPdf(stringWriter.toString(), destFilePath);
return destFilePath;
}
}
TestDemo.java
package com.itextpdf.test;
import org.junit.Test;
import com.itextpdf.demo.ITextPdf;
public class TestDemo {
@Test
public void MyTest(){
ITextPdf pdf = new ITextPdf();
try {
String destFilePath = pdf.generateContract();
System.out.println(destFilePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
html页面的浏览器显示效果
生成pdf的展示效果