一、HTML转PDF

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.font.FontProvider;
import lombok.extern.slf4j.Slf4j;
​import java.io.*;
​@Slf4j
public class PdfUtil {​
     * @param htmlPath     
     * @param pdfPath     
     * @param fontsPath     
     * @throws Exception     
    public static void htmlToPdf(String htmlPath, String pdfPath, String fontsPath) {
        log.info("htmlFile={}, pdfFile={}, fontsPath={}", htmlPath, pdfPath, fontsPath); 
       try (InputStream in = new FileInputStream(new File(htmlPath));
        OutputStream out = new FileOutputStream(new File(pdfPath)))        
            ConverterProperties converterProperties = new ConverterProperties();
            FontProvider dfp = new DefaultFontProvider();
            FontProgram fontProgram = FontProgramFactory.createFont(fontsPath);
            dfp.addFont(fontProgram);
            converterProperties.setFontProvider(dfp);​
            HtmlConverter.convertToPdf(in, out, converterProperties);
        } catch (Exception e){
            log.info("HTML转PDF异常:{}",e, e.getMessage());
    public static void htmlToPdf(File htmlFile, File pdfFile, String fontsPath) {
        log.info("htmlFile={}, pdfFile={}, fontsPath={}", htmlFile.getPath(), pdfFile.getPath(), fontsPath);
        try (InputStream in = new FileInputStream(htmlFile);
         OutputStream out = new   FileOutputStream(pdfFile))
            ConverterProperties converterProperties = new ConverterProperties();
            FontProvider dfp = new DefaultFontProvider();
            FontProgram fontProgram = FontProgramFactory.createFont(fontsPath);
            dfp.addFont(fontProgram);            
            converterProperties.setFontProvider(dfp);
            HtmlConverter.convertToPdf(in, out, converterProperties);
        } catch (Exception e){
            log.info("HTML转PDF异常:{}",e, e.getMessage());        
    public static void main(String[] args) throws Exception {
        new PdfUtil().htmlToPdf("D://2.html", "D://2.pdf", "C:/Windows/Fonts/simsun.ttc,0");
    diony_chen
        软件工程师
        10.2k
      
粉丝