java freemarker html 模板生成pdf

1.带页眉页脚及list列表

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
    <title>Title</title>
    <style>
		@page{size:297mm 210mm;
		    /* 页眉 
			@top-center {content: element(header); }
			*/
			/* 页脚加页码 样例: 1/8
			@bottom-center {
				content:counter(page) "  /  " counter(pages);
				font-family: Arial Unicode MS;
			}
			*/
		}
        body{
            font-family:"STFangsong";
            font-size:18px;
			line-height: 26px;
        }
		p{ text-indent:2em;}
		td{line-height:26px;}
		/* 页眉样式 
		div.header {
		    font-size: 13px;
			display: block;
			text-align: right;
			border-bottom: solid 1px black;
			position: running(header);
		}
		*/
		
    </style>
</head>
<body>
<table>
	<tr>
		<td style="width:30%"><div align="center"><img src="logo.png"></img></div></td>
		<td align="center"><div class="STYLE1" align="center">测试生成pdf</div></td>
	</tr>
</table>
<table width="100%"  border="0">
	<tr>
		<td>字段0:${field0}</td>		
	</tr>
	<tr>
		<td>字段2:${field2}</td>		
	</tr>
	<tr>
		<td>字段4:${field4}</td>		
	</tr>
	<tr>
		<td>字段5:${field5}</td>		
	</tr>
</table>
<hr style="height:1px; border:1; border-top:1px solid;" ></hr>
<table width="100%" border="0" style="table-layout: fixed;">
  <tr>
    <td width="18%"><div align="center">字段0</div></td>
    <td width="25%"><div align="center">字段1</div></td>
    <td width="12%"><div align="center">字段2</div></td>
	<td width="15%"><div align="center">字段3</div></td>
	<td width="10%"><div align="center">字段4</div></td>
    <td width="20%"><div align="center">字段5</div></td>
  </tr>
  <#list mylist as item>
  <tr>
    <td>${item.field0}</td>    
    <td>${item.field1}</td>	
	<td><div align="right">${item.field2}</div></td>
	<td><div align="center">${item.field3}</div></td>
    <td>${item.field4}</td>
    <td><div align="left">${item.field5}</div></td>
  </tr>
  </#list>
</table>
</body>
</html>

2.java 代码

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPageEvent;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import freemarker.template.Configuration;
import freemarker.template.Template;

public static String getHtmlString(Template template, Map<String, Object> data) {
	Writer out = new StringWriter();
	try {
		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;
}

public static Template getHtmlTemplate(String htmlDir, String htmlName) throws Exception {
	File templateFile = new File(htmlDir);
	if (!templateFile.exists()) {
		return null;
	}
	Configuration freemarkerCfg = new Configuration();
	freemarkerCfg.setDirectoryForTemplateLoading(templateFile);
	Template template = freemarkerCfg.getTemplate(htmlName);
	template.setEncoding("UTF-8");
	return template;
}


public static void xxwDzd() throws Exception{
	Map<String, Object> data = new HashMap<String, Object>();
	data.put("field0", "adfasdf");
	data.put("field1", "asdfasdf");
	data.put("field2", "asdfasdf");
	data.put("field3", "asdfasdf");
	data.put("field4", "asdfasdf");
	data.put("field5", "asdfasdf");
	
	List<Map<String, String>> mylist = new LinkedList<Map<String, String>>();
	data.put("mylist", mylist);
	Map<String, String> item = new HashMap<String, String>();
	item.put("field0", "123123");
	item.put("field1", "123123");
	item.put("field2", "123123");
	item.put("field3", "123123");
	item.put("field4", "123123");
	item.put("field5", "123123");
	mylist.add(item);
	
	item = new HashMap<String, String>();
	item.put("field0", "123123");
	item.put("field1", "123123");
	item.put("field2", "123123");
	item.put("field3", "123123");
	item.put("field4", "123123");
	item.put("field5", "123123");
	mylist.add(item);
	
	item = new HashMap<String, String>();
	item.put("field0", "123123");
	item.put("field1", "123123");
	item.put("field2", "123123");
	item.put("field3", "123123");
	item.put("field4", "123123");
	item.put("field5", "123123");
	mylist.add(item);
	
	// 模板地址
	String tempFile = "D:\\temp\\pdf\\template\\"; 

	Template temple = getHtmlTemplate(tempFile, "aaa.html");
	String content = getHtmlString(temple, data);
	System.out.println(content);
	// 生成ITextRenderer
	ITextRenderer render = new ITextRenderer();
	ITextFontResolver fontResolver = render.getFontResolver();
	String fontPath = "D:\\temp\\pdf\\template\\hwfs.ttf";
	fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	try {
		String srcPdfPath = tempFile + "\\0001.pdf";
		createPdf(content, fontPath, "D:/temp/pdf/template/", srcPdfPath);
		System.out.println("生成文件地址:"+srcPdfPath);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您可以使用一些开源库和工具来实现Java根据HTML模板生成PDF的功能。以下是一种可能的实现方式: 1. 使用Thymeleaf或FreeMarker模板引擎,将HTML模板与数据进行合并,生成最终的HTML文件。 2. 使用Flying Saucer(也称为XHTMLRenderer)库,将生成HTML文件转换为PDF。Flying Saucer是一个基于Java的渲染引擎,可以将XHTML/CSS转换为PDF。 以下是一个简单的示例代码,演示了如何使用Flying Saucer库将HTML转换为PDF: ```java import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.FileOutputStream; import java.io.OutputStream; public class HtmlToPdfConverter { public static void convertHtmlToPdf(String htmlFilePath, String pdfFilePath) throws Exception { String url = new File(htmlFilePath).toURI().toURL().toString(); OutputStream outputStream = new FileOutputStream(pdfFilePath); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); renderer.layout(); renderer.createPDF(outputStream); outputStream.close(); } public static void main(String[] args) { try { convertHtmlToPdf("path/to/input.html", "path/to/output.pdf"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,`convertHtmlToPdf`方法接受HTML文件的路径和要生成PDF文件的路径作为参数。它使用ITextRenderer类来加载HTML文件并将其转换为PDF。 请注意,这只是一个简单的示例,您可能需要根据您的具体需求进行更多的定制和调整。 希望这可以帮助到您!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值