package com.ruoyi.hywz.utils;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

/**
 * @author: lanyanhua
 * @date: 2021/3/26 10:32 上午
 * @Description:
 */
public class ExcelUtil {


    /**
     * 转pdf
     *
     * @param wb           excel
     * @param outputStream 输出流
     */
    public static void toPdf(XSSFWorkbook wb, OutputStream outputStream) throws Exception {
        // 最后输出
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        long old = System.currentTimeMillis();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        com.aspose.cells.Workbook we = new com.aspose.cells.Workbook(is);
        //隐藏workbook中不需要的sheet页。
        printSheetPage(we, new int[]{0});
        //转pdf
        PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//        pdfSaveOptions.setOnePagePerSheet(true);
//        pdfSaveOptions.isImageFitToPage(true);
        pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
        //写入 outputStream
        we.save(outputStream, pdfSaveOptions);
        long now = System.currentTimeMillis();
        System.out.println("Excel 转 Pdf 共耗时：" + ((now - old) / 1000.0) + "秒");
        is.close();
        os.close();
        wb.close();
    }

    /**
     * 获取license 去除水印
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void printSheetPage(com.aspose.cells.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 byte[] toByteArray(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int n = 0;
		while (-1 != (n = inputStream.read(buffer))){
			outputStream.write(buffer,0,n);
		}
		return outputStream.toByteArray();
	}



}
