itext使用html标签生成pdf文件

使用itext5通过html文本生成pdf文件


需要jar包

		
		
		    com.itextpdf
		    itextpdf
		    5.5.10
		
		
		
		    com.itextpdf
		    itext-asian
		    5.2.0
		
		
			com.itextpdf.tool
			xmlworker
			5.5.11
		
		



package com.gehouse.smartdevice.controller;


import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class Itext5HtmlToPDF {

	public static void main(String[] args) {
		new Itext5HtmlToPDF().createPdf();
	}
	
	public void createPdf() {
		try {
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
			Font font = new Font(bfChinese, 12, Font.NORMAL);
			
			Document document = new Document(PageSize.A4, 10, 10, 10, 10);
			PdfWriter mPdfWriter = PdfWriter.getInstance(document, new FileOutputStream("C://Users/miju/Desktop/htmltest.pdf"));
			document.open();
			
			document.add(new Paragraph("创建pdf文件.支持中文......", font));
			
			String s = getHtml();
			ByteArrayInputStream bin = new ByteArrayInputStream(s.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new ChinaFontProvide());
			document.close();
			mPdfWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getHtml() {
		
		StringBuffer html = new StringBuffer();
		html.append("
你好世界!hello world !
"); html.append("what are you 弄啥咧!"); html.append("

标题

"); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append(""); html.append("
序号用户名性别
1fengxing
2admin
"); return html.toString(); } /** * * 提供中文 * */ public static final class ChinaFontProvide implements FontProvider { @Override public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) { BaseFont bfChinese = null; try { bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); return FontChinese; } @Override public boolean isRegistered(String arg0) { return false; } } }


参考:http://blog.csdn.net/a1215656324/article/details/40346887


你可能感兴趣的:(itext,pdf)