itext

2.使用itext

依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>3.0.3</version>
</dependency>

java代码

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.layout.font.FontProvider;
​
import java.io.*;
​
public class HtmlToPdf {
    private static final String resourcesDir = System.getProperty("user.dir") + "/src/main/resources";
    public void htmlToPdf() throws Exception {
        String path = resourcesDir + "/template/template.html";
        String destPath = resourcesDir + "/template/template.pdf";
        ConverterProperties converterProperties = new ConverterProperties();
        FontProvider dfp = new DefaultFontProvider();
        //添加字体库
        dfp.addDirectory("C:/Windows/Fonts");
        converterProperties.setFontProvider(dfp);
        try (InputStream in = new FileInputStream(new File(path)); OutputStream out = new FileOutputStream(new File(destPath))){
            HtmlConverter.convertToPdf(in, out, converterProperties);
        }catch (Exception e){
            e.printStackTrace();
        }
​
    }
​
    public static void main(String[] args) throws Exception {
        new HtmlToPdf().htmlToPdf();
    }
}

注意事项:

  1. html中无需规定字体,在代码中可以导入本地的字体库或者使用特定的字体库。
posted @ 2023-10-03 21:26  布吉岛???  阅读(38)  评论(0编辑  收藏  举报