java实现html转pdf

不推荐使用前端的方式实现html转pdf,因为前端实现分辨率不高,而且不支持分页。

java代码

package appapi;

import java.io.FileInputStream;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;

public class tomPdf{
	private final static String DEST = "E:\\test"+System.currentTimeMillis()+".pdf";	//生成pdf的路径
	private final static String SRC = "E:\\h5_test.html";	//html文件路径
	//public static final String FONT = "E:\\software/yuanyuan.ttf";	//本地字体路径(百度下载)
	public static final String FONT = "E:\\software/song.ttf";	//本地字体路径(百度下载)
	public static void main(String[] args) {
		try {
			tomPdf(SRC, DEST);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	/**
	 * HTML转换成pdf
	 * @param html html文件路径
	 * @param DEST 生成pdf的路径
	 * @throws Exception
	 */
	public static void tomPdf(String html, String DEST) throws Exception {
		ConverterProperties props = new ConverterProperties();
		DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
		defaultFontProvider.addFont(FONT);
		props.setFontProvider(defaultFontProvider);
		PdfWriter writer = new PdfWriter(DEST);
		PdfDocument pdf = new PdfDocument(writer);
		pdf.setDefaultPageSize(new PageSize(595.0F, 842.0F));
		Document document = HtmlConverter.convertToDocument(new FileInputStream(html), pdf, props);
		document.close();
		pdf.close();
		
	}
	
}

pom.xml中设置的内容


        
            com.itextpdf
            html2pdf
            2.0.2
        
        
            com.itextpdf
            font-asian
            7.1.2
        
        
            com.itextpdf
            barcodes
            7.1.2
        
        

 

你可能感兴趣的:(java)