package com.jeeplus.common.utils;

import java.awt.image.BufferedImage;
import java.io.*;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jeeplus.common.config.Global;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;

/**
 * office转化为pdf
 * pdf转化为swf文件
 * @author Administrator
 *
 */
public class Office2PdfUtil {
    private static Logger logger = LoggerFactory.getLogger(Office2PdfUtil.class);

    //openoffice软件的安装路径
    private static String openOfficePath = "C:\\Program Files (x86)\\OpenOffice 4";
    private static String openOfficeAddr = Global.getOpenOfficeAddr();
    private static int openOfficePort = Global.getOpenOfficePort();

    private static DefaultDocumentFormatRegistry DefaultDocumentFormatRegistry = new DefaultDocumentFormatRegistry();

    public static ByteArrayOutputStream officeStream2PDF(InputStream inputStream,String fileName) {
        logger.info("开始转换PDF文件，文件名：{}",fileName);
        final long start = System.currentTimeMillis();
        OpenOfficeConnection connection = null;
        try {
            connection = new SocketOpenOfficeConnection(openOfficeAddr, openOfficePort);
            connection.connect();

            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            converter.convert(inputStream,DefaultDocumentFormatRegistry.getFormatByFileExtension(FilenameUtils.getExtension(fileName)),
                    outputStream,DefaultDocumentFormatRegistry.getFormatByFileExtension("pdf"));
            long end = System.currentTimeMillis();
            logger.info("转换PDF文件成功：文件名：{},耗时：{}ms",fileName,end-start);
            return outputStream;
        } catch (IOException e) {
            logger.error("待签章文件转换PDF格式异常",e);
        } finally {
            if (connection!=null&&connection.isConnected()){
                // close the connection
                connection.disconnect();
            }
        }
        return null;
    }

    public static void officeStream2PDF(InputStream inputStream,OutputStream outputStream,String fileName) {
        logger.info("开始转换PDF文件，文件名：{}",fileName);
        final long start = System.currentTimeMillis();
        String OpenOffice_HOME = openOfficePath;
        // 假如从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
            OpenOffice_HOME += "/";
        }
        Process pro = null;
        OpenOfficeConnection connection = null;
        try {
            // 启动OpenOffice的服务
            String command = OpenOffice_HOME
                    + "program/soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;StarOffice.ServiceManager\" -nofirststartwizard";
            pro = Runtime.getRuntime().exec(command);
            // connect to an OpenOffice.org instance running on port 8100
            connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            String type = "pdf";
            String extension = FilenameUtils.getExtension(fileName);
            if("xlsx".equalsIgnoreCase(extension)||"xls".equalsIgnoreCase(extension)){
                type = "html";
            }
            converter.convert(inputStream,DefaultDocumentFormatRegistry.getFormatByFileExtension(extension),
                    outputStream,DefaultDocumentFormatRegistry.getFormatByFileExtension(type));
            long end = System.currentTimeMillis();
            logger.info("转换PDF文件成功：文件名：{},耗时：{}ms",fileName,end-start);
        } catch (IOException e) {
            logger.error("待签章文件转换PDF格式异常",e);
        } finally {
            if (connection!=null&&connection.isConnected()){
                connection.disconnect();
            }
            if (pro!=null) {
                // 封闭OpenOffice服务的进程
                pro.destroy();
            }
        }
    }

    public static final float DEFAULT_DPI=105;
    /**pdf转图片
     * @param pdfName
     */
    public static ByteArrayOutputStream pdfToImage(InputStream inputStream,String pdfName){
        logger.info("开始转换图片，文件名：{}",pdfName);
        final long start = System.currentTimeMillis();
        ByteArrayOutputStream outputStream = null;
        try{
            if(pdfName==null||"".equals(pdfName)||!pdfName.endsWith(".pdf"))
                return null;
            //图像合并使用参数
            int width = 0; // 总宽度
            int[] singleImgRGB; // 保存一张图片中的RGB数据
            int shiftHeight = 0;
            BufferedImage imageResult = null;//保存每张图片的像素值
            //利用PdfBox生成图像
            PDDocument pdDocument = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            //循环每个页码
            for(int i=0,len=pdDocument.getNumberOfPages(); i<len; i++){
                BufferedImage image=renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
                int imageHeight=image.getHeight();
                int imageWidth=image.getWidth();
                if(i==0){//计算高度和偏移量
                    width=imageWidth;//使用第一张图片宽度;
                    //保存每页图片的像素值
                    imageResult= new BufferedImage(width, imageHeight*len, BufferedImage.TYPE_INT_RGB);
                }else{
                    shiftHeight += imageHeight; // 计算偏移高度
                }
                singleImgRGB= image.getRGB(0, 0, width, imageHeight, null, 0, width);
                imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
            }
            pdDocument.close();
//            String imageName = pdfName.replace(".pdf", "_"+DEFAULT_DPI+".jpg");
//            File outFile = new File(imageName);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(imageResult, "jpg", outputStream);// 写图片
            long end = System.currentTimeMillis();
            logger.info("转换图片成功，文件名：{},耗时：{}ms",pdfName,end-start);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream;
    }

    public static String convertPdfFileName(String pdfName){
        if(pdfName==null||"".equals(pdfName)||!pdfName.endsWith(".pdf"))
            return null;
        String imageName = pdfName.replace(".pdf", ".jpg");
        return  imageName;
    }
    public static void main(String []args) throws Exception {
//        String sourcePath = "C:\\Users\\ssrh\\Desktop\\testExe.xlsx";
//        String destFile = "C:\\Users\\ssrh\\Desktop\\userTest4.pdf";
//        File file = new File(sourcePath);
//        System.out.println(file.exists());
//        ByteArrayOutputStream outputStream = Office2PdfUtil.officeStream2PDF(new FileInputStream(file), "testExe.xlsx");
//        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
//        fileOutputStream.write(outputStream.toByteArray());
        String fileName = "C:\\Users\\ssrh\\Desktop\\userTest7.pdf";
        System.out.println(FilenameUtils.removeExtension(fileName)+"-----------------"+fileName);
        ByteArrayOutputStream outputStream = pdfToImage(new FileInputStream(fileName), fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(convertPdfFileName(fileName));
        fileOutputStream.write(outputStream.toByteArray());
    }
}