package cn.iocoder.yudao.framework.pdf;


import cn.iocoder.yudao.framework.velocity.VelocityHelper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.velocity.VelocityContext;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * 代码生成的引擎，用于具体生成代码
 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现
 *
 * 考虑到 Java 模板引擎的框架非常多，Freemarker、Velocity、Thymeleaf 等等，所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象
 *
 * @author 捷道源码
 */
public class PDFHelper {

    public static final String DEST = "C:/Users/Administrator/Desktop/td.pdf";

    public void createPdf() throws Exception{
        FileOutputStream outputStream = new FileOutputStream(DEST);
        //设置打印后pdf的格式
        Document document = new Document(PageSize.A4,60.5f,60.5f,33f,33f);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);// outputStream可以自己指定位置或者是HttpServletResponse得到的输出流
        pdfWriter.setTagged();
        document.open();
        //取得velocity的上下文
        //往vm中写入信息
        //写入自己要插入的信息，
        Map<String, Object> param = new HashMap<>();
        param.put("billLadingNo","TD20220719E");
        param.put("orderNo","CNG20220701N");
        param.put("consigneeName","张三");
        param.put("plNo","CNG20220701N-01");
        param.put("consigneePhone","+13289227288");
        param.put("consignorPhone","+8615677282285");
        param.put("consignorName","李四");
        param.put("deliveryDate","2022-07-01");
//        Writer writer = VelocityHelper.getWriterByTemplate("yudao-server/src/main/resources/templates/billLading.html", null, param, null);
        Writer writer = VelocityHelper.getWriterByTemplate("yudao-server/src/main/resources/templates/test01.html", null, param, null);
//        Writer writer = VelocityHelper.getWriterByTemplate("classpath:/templates/billLading.vm", null, param, null);
        System.out.println("转换的文本内容为===============" + writer.toString());
        //输出转输入流
        InputStream in = new ByteArrayInputStream(writer.toString().getBytes(Charset.defaultCharset()));

        //去找velocity并交给itext生成pdf
        XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, in, StandardCharsets.UTF_8);
        in.close();
        document.close();
    }

    public static void main(String[] args) throws Exception {
        new PDFHelper().createPdf();
    }
}
