package com.eitc.common.utils;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;

/**
 * PdfUtil
 *
 * @author mtx
 * @date: 2024/06/04 10:07
 */
@Slf4j
public class PdfUtil {

    /**
     * HTML 转 PDF
     *
     * @param content html内容
     */
    public static void html2Pdf(String content, HttpServletResponse response) {
        try {
            PdfWriter pdfWriter = new PdfWriter(response.getOutputStream());
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            //设置为A4大小
            pdfDocument.setDefaultPageSize(PageSize.A4);

            ConverterProperties properties = new ConverterProperties();
            properties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            properties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, pdfDocument, properties);

            pdfWriter.close();
            pdfDocument.close();
        } catch (Exception e) {
            log.error("生成 PDF 失败,", e);
        }
    }
}