使用OpenOffice插件实现RTF/WORD转PDF转多张图片或者一张图片

这里我们使用的是OpenOffice插件,需要安装,还有相关的jar包 网盘地址:

https://pan.baidu.com/s/1c6HymABx3wre-d19eB1c-w      密码: n1cd
安装OpenOffice完成后

Windows 命令进入安装目录 + 启动服务

cd C:\Program Files\OpenOffice.org 3\program 
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
转化包 Maven Pom配置
 <!-- 手动注入包FileToImgUtil转化包 -->
        <dependency>
            <groupId>org.icepdf</groupId>
            <artifactId>icepdf-core</artifactId>
        </dependency>

 

1.RTF或者Word生成PDF文档的方法

我注释掉的部分是启动每次都访问都自动启动关闭OpenOffice,需要可以解开注释。

/**
     * @Description: rtf/word 生成pdf文档
     * @Param: inputFile 要读取的文件 outputFile 输出的pdf文件
     * @return: String pdf文件名称
     * @Author: 王飞焱
     * @Date: 2018/11/8
     */
    public String docToPdf(File inputFile, File outputFile) {
        // 启动服务
        /*
         * String OpenOffice_HOME = "C:/Program  Files  (x86)/OpenOffice  4";// 这里是OpenOffice的安装目录
         * if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){ OpenOffice_HOME+="/"; }
         */
        Process pro = null;
        OpenOfficeConnection connection = null;
        // 启动OpenOffice的服务
        /*
         * String command = OpenOffice_HOME +
         * "program/soffice.exe  -headless  -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
         */
        // connect to an OpenOffice.org instance running on port 8100
        try {
            /* pro = Runtime.getRuntime().exec(command); */
            connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            
            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            System.out.println(inputFile + "=" + outputFile);
            
            converter.convert(inputFile, outputFile);
        }
        catch (Exception ex) {
            ex.printStackTrace();
            logger.info("\n  程序出错了:", ex);
        }
        finally {
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
            /* pro.destroy(); */
        }
        logger.info("生成文件:" + outputFile.getName());
        return outputFile.getName();
    }

2.将pdf转换成多张图片(JPG)

/**
     * 将pdf转换成图片
     *
     * @param pdfPath
     * @param imgDirPath
     * @return 返回转换后图片的名字
     * @throws Exception
     */
    private List<String> pdf2Imgs(String pdfPath, String imgDirPath, String fileName)
        throws Exception {
        Document document = new Document();
        document.setFile(pdfPath);
        float scale = 2f;// 放大倍数
        float rotation = 0f;// 旋转角度
        List<String> imgNames = new ArrayList<String>();
        int pageNum = document.getNumberOfPages();
        File imgDir = new File(imgDirPath);
        if (!imgDir.exists()) {
            imgDir.mkdirs();
        }
        for (int i = 0; i < pageNum; i++) {
            BufferedImage image = (BufferedImage)document
                .getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;
            try {
                String filePath = imgDirPath + File.separator + fileName + i + ".jpg";
                File file = new File(filePath);
                ImageIO.write(rendImage, "jpg", file);
                imgNames.add(FilenameUtils.getName(filePath));
            }
            catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            image.flush();
        }
        document.dispose();
        return imgNames;
    }

3.PDF多页转换成一张图片

/**
    * @Description: PDF多页转换成一张图片
    * @Param:  pdfFile PDF绝对路径,outpath 输出的图片路径
    * @Author: 王飞焱
    * @Date: 2018/11/13
    */
    public void pdf2multiImage(String pdfFile, String outpath) throws IOException, PDFException, PDFSecurityException {
            InputStream is = new FileInputStream(pdfFile);
            List<BufferedImage> piclist = new ArrayList<BufferedImage>();
            Document document = new Document();
            document.setFile(pdfFile);
            float scale = 2.5f; // 缩放比例
            float rotation = 0f; // 旋转角度
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage)document
                    .getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
                piclist.add(image);
            }
            document.dispose();
            yPic(piclist, outpath);
            is.close();
    }
/* 纵向处理图片 */
    public void yPic(List<BufferedImage> piclist, String outPath) throws IOException {
        if (piclist == null || piclist.size() <= 0) {
            System.out.println("图片数组为空!");
            return;
        }
        int height = 0, // 总高度
            width = 0, // 总宽度
            _height = 0, // 临时的高度 , 或保存偏移高度
            __height = 0, // 临时的高度,主要保存每个高度
            picNum = piclist.size();// 图片的数量
        File fileImg = null; // 保存读取出的图片
        int[] heightArray = new int[picNum]; // 保存每个文件的高度
        BufferedImage buffer = null; // 保存图片流
        List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
        int[] _imgRGB; // 保存一张图片中的RGB数据
        for (int i = 0; i < picNum; i++) {
            buffer = piclist.get(i);
            heightArray[i] = _height = buffer.getHeight();// 图片高度
            if (i == 0) {
                width = buffer.getWidth();// 图片宽度
            }
            height += _height; // 获取总高度
            _imgRGB = new int[width * _height];// 从图片中读取RGB
            _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
            imgRGB.add(_imgRGB);
        }
        _height = 0; // 设置偏移高度为0
        // 生成新图片
        BufferedImage imageResult = new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < picNum; i++) {
            __height = heightArray[i];
            if (i != 0)
                _height += __height; // 计算偏移高度
            imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
        }
        File outFile = new File(outPath);
        ImageIO.write(imageResult, "jpg", outFile);// 写图片
    }

我把整个类贴出来

package com.ys.gassys.utils;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

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 org.apache.commons.io.FilenameUtils;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import javax.imageio.ImageIO;

/**
 * Created with IntelliJ IDEA. Description:openOffice 生成pdf
 *
 * @author wangfeiyan Date: 14:04 Time: 2018/118/8
 */
public class OfficeToPDF {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    /**
     * @Description: rtf/word 生成pdf文档
     * @Param: inputFile 要读取的文件 outputFile 输出的pdf文件
     * @return: String pdf文件名称
     * @Author: 王飞焱
     * @Date: 2018/11/8
     */
    public String docToPdf(File inputFile, File outputFile) {
        // 启动服务
        /*
         * String OpenOffice_HOME = "C:/Program  Files  (x86)/OpenOffice  4";// 这里是OpenOffice的安装目录
         * if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){ OpenOffice_HOME+="/"; }
         */
        Process pro = null;
        OpenOfficeConnection connection = null;
        // 启动OpenOffice的服务
        /*
         * String command = OpenOffice_HOME +
         * "program/soffice.exe  -headless  -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
         */
        // connect to an OpenOffice.org instance running on port 8100
        try {
            /* pro = Runtime.getRuntime().exec(command); */
            connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            
            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            System.out.println(inputFile + "=" + outputFile);
            
            converter.convert(inputFile, outputFile);
        }
        catch (Exception ex) {
            ex.printStackTrace();
            logger.info("\n  程序出错了:", ex);
        }
        finally {
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
            /* pro.destroy(); */
        }
        logger.info("生成文件:" + outputFile.getName());
        return outputFile.getName();
    }
    
    // 生产pdf线程
    static class TestThread extends Thread {
        private File inputFile;
        
        private File outputFile;
        
        public void run() {
            OfficeToPDF t = new OfficeToPDF();
            t.docToPdf(inputFile, outputFile);
            System.out.println(outputFile.getName() + "文件已生成");
        }
        
        public void setInputFile(File inputFile) {
            this.inputFile = inputFile;
        }
        
        public void setOutputFile(File outputFile) {
            this.outputFile = outputFile;
        }
    }
    
    /**
     * 将pdf转换成图片
     *
     * @param pdfPath
     * @param imgDirPath
     * @return 返回转换后图片的名字
     * @throws Exception
     */
    private List<String> pdf2Imgs(String pdfPath, String imgDirPath, String fileName)
        throws Exception {
        Document document = new Document();
        document.setFile(pdfPath);
        float scale = 2f;// 放大倍数
        float rotation = 0f;// 旋转角度
        List<String> imgNames = new ArrayList<String>();
        int pageNum = document.getNumberOfPages();
        File imgDir = new File(imgDirPath);
        if (!imgDir.exists()) {
            imgDir.mkdirs();
        }
        for (int i = 0; i < pageNum; i++) {
            BufferedImage image = (BufferedImage)document
                .getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;
            try {
                String filePath = imgDirPath + File.separator + fileName + i + ".jpg";
                File file = new File(filePath);
                ImageIO.write(rendImage, "jpg", file);
                imgNames.add(FilenameUtils.getName(filePath));
            }
            catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            image.flush();
        }
        document.dispose();
        return imgNames;
    }
    
    public static void main(String[] args) {
        // // String docPath = "d:/94_storage安装.doc";
        // String docPath = "d:/公司通讯录.xlsx";
        // String pdfPath = "d:/pdf/";
        // doc2Imags(docPath, pdfPath, "公司通讯录");
        OfficeToPDF officeToPDF = new OfficeToPDF();
        officeToPDF.docToPdf(new File("D:\\blob.rtf"), new File("D:\\test\\test1.pdf"));
//        officeToPDF.pdf2multiImage("D:\\test\\test1.pdf","D:\\test\\test1.jpg");
//        try {
//            officeToPDF.pdf2Imgs("D:\\test\\test1.pdf", "D:\\test\\", "test");
//        }
//        catch (Exception e) {
//            e.printStackTrace();
//        }
        
    }

    /**
    * @Description: PDF多页转换成一张图片
    * @Param:  pdfFile PDF绝对路径,outpath 输出的图片路径
    * @Author: 王飞焱
    * @Date: 2018/11/13
    */
    public void pdf2multiImage(String pdfFile, String outpath) throws IOException, PDFException, PDFSecurityException {
            InputStream is = new FileInputStream(pdfFile);
            List<BufferedImage> piclist = new ArrayList<BufferedImage>();
            Document document = new Document();
            document.setFile(pdfFile);
            float scale = 2.5f; // 缩放比例
            float rotation = 0f; // 旋转角度
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage)document
                    .getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
                piclist.add(image);
            }
            document.dispose();
            yPic(piclist, outpath);
            is.close();
    }
    
    /* 纵向处理图片 */
    public void yPic(List<BufferedImage> piclist, String outPath) throws IOException {
        if (piclist == null || piclist.size() <= 0) {
            System.out.println("图片数组为空!");
            return;
        }
        int height = 0, // 总高度
            width = 0, // 总宽度
            _height = 0, // 临时的高度 , 或保存偏移高度
            __height = 0, // 临时的高度,主要保存每个高度
            picNum = piclist.size();// 图片的数量
        File fileImg = null; // 保存读取出的图片
        int[] heightArray = new int[picNum]; // 保存每个文件的高度
        BufferedImage buffer = null; // 保存图片流
        List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
        int[] _imgRGB; // 保存一张图片中的RGB数据
        for (int i = 0; i < picNum; i++) {
            buffer = piclist.get(i);
            heightArray[i] = _height = buffer.getHeight();// 图片高度
            if (i == 0) {
                width = buffer.getWidth();// 图片宽度
            }
            height += _height; // 获取总高度
            _imgRGB = new int[width * _height];// 从图片中读取RGB
            _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
            imgRGB.add(_imgRGB);
        }
        _height = 0; // 设置偏移高度为0
        // 生成新图片
        BufferedImage imageResult = new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < picNum; i++) {
            __height = heightArray[i];
            if (i != 0)
                _height += __height; // 计算偏移高度
            imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
        }
        File outFile = new File(outPath);
        ImageIO.write(imageResult, "jpg", outFile);// 写图片
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值