现在的位置: 首页 > 综合 > 正文

使用freemaker和itext从html模板生成pdf文件

2013年10月16日 ⁄ 综合 ⁄ 共 2264字 ⁄ 字号 评论关闭

   这里主要需要生成一个合同的pdf文档,拿到的合同格式是word文档,为了便于处理,我们用DW将其内容手动转为html。

   所以接下来的问题主要就是如何从一个html的合同模板变成一个pdf文件。

   首先我们定义好freemaker的util方法,使其易于调用

public class TemplateUtils {

	private static FreeMarkerConfigurer templateEngine = new FreeMarkerConfigurer();

	static {
		try {
			templateEngine.setConfiguration(templateEngine.createConfiguration());
			TemplateLoader loader = new FileTemplateLoader(new ClassPathResource("template").getFile());
			templateEngine.getConfiguration().setTemplateLoader(loader);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}

	public static String generateTemplateContent(String templateName, Map map) {
		try {
			Template t = templateEngine
					.getConfiguration().getTemplate(templateName);
			return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}

    调用时只需要传入模板文件名和一个参数的map就行了

String content = TemplateUtils.generateTemplateContent(
				"contractTemplate.ftl", map);

    其次,定义html转pdf 的util类

public class Html2Pdf {

	public static void print2Pdf(String templateHtml, String outputPath)
			throws IOException {
		File src = new File(templateHtml);
		if (!src.exists()) {
			throw new IllegalArgumentException("Can not find source html file."
					+ templateHtml);
		}
		String url = null;
		OutputStream os = null;
		ITextRenderer renderer = null;
		Document doc = new Document();
		// try {
		// PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
		// new File(outputPath)));
		// doc.open();
		// BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
		// BaseFont.NOT_EMBEDDED);
		// Font font = new Font(bf, 12, Font.NORMAL);
		// doc.add(new Paragraph(FileUtils.readFileToString(new File(
		// templateHtml)), font));
		// doc.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		try {
			url = src.toURI().toURL().toString();
			os = new FileOutputStream(outputPath);
//			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
//					"UniGB-UCS2-H", false);
			renderer = new ITextRenderer();
			ITextFontResolver fontResolver = renderer.getFontResolver();
			fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			renderer.setDocument(url);
			renderer.layout();
			renderer.createPDF(os);
			os.close();
		} catch (Exception e) {
			throw new IOException(e);
		}

	}

}

    这里我们用了fontResolver添加了中文的字体,这样pdf就能识别中文并转换了。 

    但是,这时候还没完,转换的中文问题还是没有解决,我们必须在html文档中加入这样一句标识所有body中的字体为simsun这种字体。

<style type="text/css" mce_bogus="1">body {font-family: SimSun;}</style>

   

抱歉!评论已关闭.