java HTML转PDF实现

前言

本文主要利用java itext解析HTML语句,输出为PDF文件。

1.POM依赖

<dependency>
    <groupId>com.itextpdf.toolgroupId>
    <artifactId>xmlworkerartifactId>
    <version>5.5.1version>
dependency>


<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itext-asianartifactId>
    <version>5.2.0version>
dependency>

<dependency>
    <groupId>org.xhtmlrenderergroupId>
    <artifactId>flying-saucer-pdf-itext5artifactId>
    <version>9.0.3version>
dependency>

2 html转pdf

字体样式类

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.pdf.BaseFont;

public class MyFontProvider implements FontProvider {
	private BaseColor bc;
	private String fontname;
	private String encoding;
	private boolean embedded;
	private boolean cached;
	private float size;
	private int style;
	private BaseFont baseFont;

	public MyFontProvider() {
	}

	public BaseColor getBc() {
		return bc;
	}

	public void setBc(BaseColor bc) {
		this.bc = bc;
	}

	public String getFontname() {
		return fontname;
	}

	public void setFontname(String fontname) {
		this.fontname = fontname;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public boolean isEmbedded() {
		return embedded;
	}

	public void setEmbedded(boolean embedded) {
		this.embedded = embedded;
	}

	public boolean isCached() {
		return cached;
	}

	public void setCached(boolean cached) {
		this.cached = cached;
	}

	public float getSize() {
		return size;
	}

	public void setSize(float size) {
		this.size = size;
	}

	public int getStyle() {
		return style;
	}

	public void setStyle(int style) {
		this.style = style;
	}

	public BaseFont getBaseFont() {
		return baseFont;
	}

	public void setBaseFont(BaseFont baseFont) {
		this.baseFont = baseFont;
	}

	public MyFontProvider(BaseColor bc, String fontname, String encoding, boolean embedded, boolean cached, float size,
			int style, BaseFont baseFont) {
		super();
		this.bc = bc;
		this.fontname = fontname;
		this.encoding = encoding;
		this.embedded = embedded;
		this.cached = cached;
		this.size = size;
		this.style = style;
		this.baseFont = baseFont;
	}

	public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) {
		Font font = null;
		if (baseFont == null) {
			font = new Font();
		} else {
			font = new Font(baseFont);
		}
		font.setColor(arg5);
		font.setFamily(fontname);
		font.setSize(size);
		font.setStyle(arg4);
		return font;
	}

	public boolean isRegistered(String arg0) {
		// TODO Auto-generated method stub
		return true;
	}

}

主方法类

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

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFilesImpl;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.HTML;
import com.itextpdf.tool.xml.html.TagProcessorFactory;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

public class Html2pdf {

	public static void htmlTopdf(String html, File file) throws Exception {
		try {
			// step 1
			Document document = new Document();
			BaseFont bfChinese;
			bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
			MyFontProvider myFontProvider = new MyFontProvider(BaseColor.BLACK, "", "", false, false, 16, 1, bfChinese);
			// step 2
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
			// step 3
			document.open();

			final TagProcessorFactory tagProcessorFactory = Tags.getHtmlTagProcessorFactory();
			tagProcessorFactory.removeProcessor(HTML.Tag.IMG);

			final CssFilesImpl cssFiles = new CssFilesImpl();
			cssFiles.add(XMLWorkerHelper.getInstance().getDefaultCSS());
			final StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
			final HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(myFontProvider));
			hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(tagProcessorFactory);
			final HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
			final Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);

			final XMLWorker worker = new XMLWorker(pipeline, true);

			final Charset charset = Charset.forName("UTF-8");
			final XMLParser xmlParser = new XMLParser(true, worker, charset);

			ByteArrayInputStream bais = new ByteArrayInputStream(html.getBytes("UTF-8"));
			xmlParser.parse(bais, charset);

			// step 5
			document.close();
			bais.close();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public static void main(String[] args) {
		String content = "

哈哈

"
; File file = new File("d:/pdf2.pdf"); try { htmlTopdf(content, file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

你可能感兴趣的:(java,java,html)