package com.fdkankan.ucenter.util;

import com.aspose.cells.*;
import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.springframework.core.io.ClassPathResource;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class TestForExcel2PDF {

    public static void excelToPdf(String xlsxPath,String pdfPath) {
        excel2pdf(xlsxPath, pdfPath+".sy");
        replaceStr(pdfPath+".sy",pdfPath,"Evaluation Only. Created with Aspose.Cells for Java.Copyright 2003 - 2022 Aspose Pty Ltd.");
    }

    private static void replaceStr(String src, String dest, String replaceStr) {
        try {
            List<String> resu = new ArrayList<>();
            PdfReader reader = new PdfReader(src);
            //获取指定文字的坐标(就是上一步生成的pdf水印)
            getKeyWords(reader,replaceStr,resu);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
            for (int i = 1; i <= resu.size(); i++) {
                String xy = resu.get(i - 1);
                PdfContentByte canvas = stamper.getOverContent(i);
                canvas.saveState();
                //设置颜色
                canvas.setColorFill(BaseColor.WHITE);
                //解析坐标
                double x = Double.valueOf(xy.split("--")[0]);
                double y = Double.valueOf(xy.split("--")[1]) - 10;
                //后面2个参数分别是宽高
                canvas.rectangle(x, y, 450, 100);
                canvas.fill();
                canvas.restoreState();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定文字的坐标
     */
    public static void getKeyWords(PdfReader pdfReader, String replaceStr,List<String> resu ) {
        try {
            int pageNum = pdfReader.getNumberOfPages();
            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(
                    pdfReader);
            for (int i = 1; i <= pageNum; i++) {
                pdfReaderContentParser.processContent(i, new RenderListener() {
                    @Override
                    public void renderText(TextRenderInfo textRenderInfo) {
                        String text = textRenderInfo.getText(); // 整页内容
                        if (null != text && text.contains(replaceStr)) {
                            Rectangle2D.Float boundingRectange = textRenderInfo
                                    .getBaseline().getBoundingRectange();
                            String xy = boundingRectange.x + "--" + boundingRectange.y;
                            resu.add(xy);
                        }
                    }
                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                    }
                    @Override
                    public void endTextBlock() {
                    }
                    @Override
                    public void beginTextBlock() {
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取license 去除水印
     * @return
     */
    public static void getLicense() {
        try {
            ClassPathResource classPathResource = new ClassPathResource("/com.aspose.cells.lic_2999.xml");
            InputStream license = classPathResource.getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(license);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excel 转为pdf 输出。
     *
     * @param sourceFilePath  excel文件
     * @param desFilePathd  pad 输出文件目录
     */
    public static void excel2pdf(String sourceFilePath, String desFilePathd ){
        getLicense();
        try {
            Workbook wb = new Workbook(sourceFilePath);// 原始excel路径
//            IndividualFontConfigs configs = new IndividualFontConfigs();
//            configs.setFontFolder("/usr/share/fonts/chinese", true);
//            LoadOptions loadOptions  = new LoadOptions();
//            loadOptions.setFontConfigs(configs);

            FileOutputStream fileOS = new FileOutputStream(desFilePathd);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);


            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时，在PDF中会拆断并分页。此处等比缩放。
//            autoDraw(wb,autoDrawSheets);

            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("完毕");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置打印的sheet 自动拉伸比例
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb,int[] page){
        if(null!=page&&page.length>0){
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }


    /**
     * 隐藏workbook中不需要的sheet页。
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb,int[] page){
        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if(null==page||page.length==0){
            wb.getWorksheets().get(0).setVisible(true);
        }else{
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    public static void crackAspose(String JarPath, String outPath) throws Exception {
        // 这个是得到反编译的池
        ClassPool pool = ClassPool.getDefault();

        // 取得需要反编译的jar文件，设定路径
        pool.insertClassPath(JarPath);

        CtClass cc_License = pool.get("com.aspose.cells.License");

        CtMethod method_isLicenseSet = cc_License.getDeclaredMethod("isLicenseSet");
        method_isLicenseSet.setBody("return true;");

        CtClass cc_License2 = pool.get("com.aspose.cells.License");
        CtMethod method_setLicense = cc_License2.getDeclaredMethod("setLicense");
        method_setLicense.setBody("{    a = new com.aspose.cells.License();\n" +
                "    com.aspose.cells.zbiw.a();}");

        CtMethod method_k = cc_License.getDeclaredMethod("k");
        method_k.setBody("return new java.util.Date(Long.MAX_VALUE);");

        cc_License.writeFile(outPath);
    }

    public static void main(String[] args) throws Exception{
        crackAspose("D:\\sale\\aspose-cells-20.7.jar","D:\\sale");
    }

}


