记录Html转pdf实例工具类

package com.lcw.one.util.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.lcw.one.util.utils.string.UUID;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 网页转PDF工具类
 */
public class PdfUtils {

    private String fontPath;

    public PdfUtils(String fontPath) {
        this.fontPath = fontPath;
    }

    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     *
     * @param html
     * @throws Exception
     */
    public File html2pdf(String html) throws Exception {
        // 生成PDF临时文件目录
        String filePath = FileUtils.getTempDirectoryPath() + UUID.randomUUID10() + ".pdf";
        File pdfFile = new File(filePath);


        OutputStream os = new FileOutputStream(pdfFile);
        ITextRenderer renderer = new ITextRenderer();
        installFont(renderer);        // 初始化字体

        renderer.setDocumentFromString(html);

        renderer.layout();
        renderer.createPDF(os);
        os.close();
        os.close();

        return pdfFile;
    }

    /**
     * 初始化字体
     * @param renderer
     * @throws DocumentException
     * @throws IOException
     */
    private void installFont(ITextRenderer renderer) throws DocumentException, IOException {
        String fontFolderPath = this.fontPath + FileUtils.FILE_SEPARATOR + "font" + FileUtils.FILE_SEPARATOR;

        //  解决中文支持
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(fontFolderPath + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontResolver.addFont(fontFolderPath + "Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    }

    public static String getCurrentOperatingSystem() {
        String os = System.getProperty("os.name").toLowerCase();
        System.out.println("---------当前操作系统是-----------" + os);
        return os;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值