freemarker+itext生成PDF

<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>2.0.8</version>
		</dependency>
		<dependency>
			<groupId>org.xhtmlrenderer</groupId>
			<artifactId>core-renderer</artifactId>
			<version>R8</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.21</version>
		</dependency>
	</dependencies>

 以上是依赖包

HtmlToPdf.java

package org.yzr.pdf.html2pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class HtmltoPDF {
	private static String logopath = "car.jpg";

	@Test
	public void htmlToPdf() throws Exception {
		String prefix = "temp";
		String suffix = ".pdf";
		File file = File.createTempFile(prefix, suffix);
		OutputStream os = null;
		os = new FileOutputStream(file);
		ITextRenderer renderer = new ITextRenderer();
		ITextFontResolver fontResolver = renderer.getFontResolver();
		fontResolver.addFont(HtmltoPDF.class.getClassLoader().getResource("SIMSUN.TTC").toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		Map<String, Object> dataModel = new HashMap<String, Object>();
		dataModel.put("username", "张三");
		renderer.setDocumentFromString(FreeMarkerHelper.getContract("test", dataModel));
		renderer.layout();
		renderer.createPDF(os);
		os.close();
		addWater(file);
	}

	/**
	 * @param file
	 * 
	 *            addWater添加水印
	 * 
	 * @throws Exception
	 *             void
	 * @exception
	 */
	public void addWater(File file) throws Exception {
		try {
			PdfReader reader = new PdfReader(file.getAbsolutePath());
			PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("F:/test.pdf"));
			Image image = Image.getInstance(HtmltoPDF.class.getResource("/") + logopath);
			// 图片位置
			image.setAbsolutePosition(1, 1);
			int total = reader.getNumberOfPages();
			for (int i = 1; i <= total; i++) {
				PdfContentByte under = stamp.getUnderContent(i);
				under.addImage(image);
			}
			stamp.close();// 关闭
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

FreeMakerHelper.java

/*
 * 描述:〈描述〉
 * 创建人:yizhaorong
 * 创建时间:2014-10-28
 */
package org.yzr.pdf.html2pdf;

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

/**
 * 用于生成手机端合同模板
 */
public class FreeMarkerHelper {
	/**
	 * 后缀为html
	 */
	private static final String HTML = ".html";

	/**
	 * 
	 * generateContract生成合同
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 *             String
	 * @exception
	 */
	public static String getContract(String code, Map<String, Object> dataModel) throws Exception {
		Writer out = null;
		StringReader reader = null;
		try {
			out = new StringWriter();
			Configuration cfg = new Configuration(new Version(2, 3, 21));
			cfg.setDefaultEncoding("UTF-8");
			cfg.setClassForTemplateLoading(FreeMarkerHelper.class, "/templete");
			Template template = cfg.getTemplate(code + HTML);
			template.process(dataModel, out);
			reader = new StringReader(out.toString());
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		BufferedReader br = new BufferedReader(reader);
		StringBuilder content = new StringBuilder();
		String str = null;
		while ((str = br.readLine()) != null) {
			content.append(str);
		}
		return content.toString();
	}
}

 

你可能感兴趣的:(freemarker+itext生成PDF)