package com.brilliance.isc.doc.utils;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.doc.handle.impl.common.Base64ImgReplacedElementFactory;
import com.brilliance.isc.doc.handle.impl.common.SimpleTextUserAgentCallback;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

public class HtmlToPdf {
    private static final String FONT = "simhei.ttf";
    private static Logger logger = LoggerFactory.getLogger(HtmlToPdf.class);


    public static byte[] convertHtml2Pdf(String html){
        //将html 内容bos转为PDF
        try (ByteArrayOutputStream bos2OfPdf = new ByteArrayOutputStream();){
            ITextRenderer render = new ITextRenderer();
            ITextFontResolver fontResolver = render.getFontResolver();
            fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("times.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // 解析html生成pdf
            //解决图片相对路径的问题
//            render.getSharedContext().setBaseURL(LOGO_PATH);
            render.getSharedContext().setUserAgentCallback(new SimpleTextUserAgentCallback(render.getOutputDevice()));
            render.getSharedContext().setReplacedElementFactory(new Base64ImgReplacedElementFactory(new HashMap<>()));
            html = html.replaceAll("font-family:\\s*宋体", "font-family: SimSun");
            html = html.replaceAll("font-family:\\s*楷体", "font-family: KaiTi_GB2312");
            html = html.replaceAll("font-family:\\s*标楷体", "font-family: KaiTi_GB2312");
            html = html.replaceAll("font-family:\\s*新罗马体", "font-family: Times New Roman");
            html = html.replaceAll("<br\\s*>", "<br/>").replaceAll("<(/)?\\s*pre\\s*>", "<$1p>");
            //替换单独的&前，不能影响其他转义符号,可能大于小于等等也需要
            html = html.replaceAll("&(?!((quot|amp|lt|gt|nbsp);))", "&amp;");
            //更新源文本，方便接口更新
            render.setDocumentFromString(html);
            render.layout();
            render.createPDF(bos2OfPdf);
            return bos2OfPdf.toByteArray();
        }catch (Exception e){
            logger.error("HTML转换PDF发生错误:{}",e);
        }
        return null;
    }
}
