package com.malk.mcli.utils;

import com.itextpdf.text.pdf.BaseFont;
import com.malk.server.common.FilePath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 引用了配置文件, 访问对象必须通过 @Autowired 进行注入, 否则识别到为空 [配置文件说明参考Setting]
 */
@Slf4j
@Component
public class UtilVendor {

    @Autowired
    private FilePath filePath;

    /**
     * 网页转存为PDF文件: http://www.lrfun.com/html/technology/java/2019/0509/137.html
     */
    public void urlToPdf(String url, String outputFileName) {
        try {
            String outputFile = filePath.getPath().getFile() + "/" + outputFileName;
            java.io.File targetFile = new java.io.File(outputFile);
            // 创建父级文件路径
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            log.info("PDF 存储路径, {}", outputFile);
            OutputStream os = new FileOutputStream(outputFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(filePath.getSource().getFonts(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //Linux
            renderer.layout();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e); // 记录错误日志
        }
    }
}
