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中设置的内容

<!--将html转换成pdf-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>barcodes</artifactId>
            <version>7.1.2</version>
        </dependency>
        

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页