package com.ruoyi.common.utils;

import com.ruoyi.common.constant.Constants;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;


/**
 * 转换PPT为PDF工具类
 * @author lihao16
 */
public class LibreOfficeConvertUtil {

    private static final Logger log = LoggerFactory.getLogger(LibreOfficeConvertUtil.class);

    // 经过测试，dpi 为 96,100,105,120,150,200 中，105 显示效果较为清晰，体积稳定，dpi 越高图片体积越大，一般电脑显示分辨率为 96
    public static final float DEFAULT_DPI = 105;
    public static final String DEFAULT_IMAGE_FORMAT = ".png";

    /**
     *
     *@name    文档转换为pdf工具类
     *@description 相关说明 支持：xls，xlsx，ppt，pptx，txt，其中doc，docx转换与原文件有较大差异,libreOffice 默认安装路径
     *Linux：/opt/libreoffice6.0
     *Windows：C:/Program Files (x86)/LibreOffice
     *Mac：/Application/openOfficeSoft
     *@param sourceFile 需要转换的原文件
     *@param tarPdfFile 转换后的目标pdf文件
     *@return
     *@throws Exception
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static String convertToPdf(String sourceFile, String tarPdfFile,OfficeManager officeManager) throws Exception {
        log.info("convertToPdf begin sourceFile:{}",sourceFile);
        File inputFile = new File(sourceFile);
        // 判断当前文件是否为pdf
        if (inputFile.isFile() && inputFile.getName().toLowerCase().endsWith(Constants.PDF)) {
            return sourceFile;
        }
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        File outputFile = new File(tarPdfFile);
        converter.convert(inputFile, outputFile);
        // String pdfPath = outputFile.getPath();
        log.info("convertToPdf end pdfPath:{}",tarPdfFile);
        return tarPdfFile;
    }

    /**
     * pdf 转图片，每页生成一张图片
     * @param pdfPath PDF路径
     * @return pdf 页数
     */
    public static int convertToImage(String pdfPath,long timeMillis) throws Exception {
        BufferedImage imageResult;
        File pdfFile = new File(pdfPath);
        PDDocument pdDocument = PDDocument.load(pdfFile);
        // String fileName = pdfFile.getName();
        // String filePath = pdfFile.getPath();
        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);

        int pages = pdDocument.getNumberOfPages();

        int width;

        int shiftHeight = 0;
        int[] singleImgRGB;
        String pdfFileName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1);
        for (int i = 0; i < pages; i++) {
            BufferedImage image = pdfRenderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
            width = image.getWidth();
            int imageHeight = image.getHeight();
            imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);
            singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
            // 写入流中
            imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);
            // 写图片
            String imgPath = pdfPath.replace(pdfFileName, String.valueOf(timeMillis));
            ImageIO.write(imageResult, DEFAULT_IMAGE_FORMAT.replace(".", ""), new File(imgPath + "." + i + DEFAULT_IMAGE_FORMAT));
        }

        pdDocument.close();
        return pages;
    }



}
