Java通過openoffice將下載的文件轉成pdf供前端預覽

一、下載安裝openoffice

1、進入openoffice官網http://www.openoffice.org/download/index.html下載最新版RPM安裝包Apache_OpenOffice_4.1.6_Linux_x86-64_install-rpm_zh-CN.tar.gz

2、解壓下載的文件

tar zxxvf Apache_OpenOffice_4.1.6_Linux_x86-64_install-rpm_zh-CN.tar.gz

3、進入zh-CN/RPMS目錄

cd zh-CN/RPMS

4、安裝所有rpm文件

rpm -ivh *.rpm

5、進入desktop-integration目錄

desktop-integration

6、安裝openoffice4.1.6-redhat-menus-4.1.6-9790.noarch.rpm,不同版本該文件名可能不同

rpm -ivh openoffice4.1.6-redhat-menus-4.1.6-9790.noarch.rpm

可能會出現如下問題:

file /usr/bin/soffice from install of openoffice4.1.6-redhat-menus-4.1.6-9790.noarch conflicts with file from package libreoffice-core-1:4.3.7.2-5.el7.x86_64
意思是:包libreoffice-core-1:4.3.7.2-5.el7.x86_64衝突,執行以下命令卸載該包,然後再執行一次上面的安裝命令即可。

yum -y remove libreoffice-core-1:4.3.7.2-5.el7.x86_64

7、啓動openoffice服務,完成安裝後,默認安裝到 /opt/openoffice4 目錄下,進入該目錄下的program目錄,執行命令進行後臺啓動

nohup soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &

可通過 ps ef|grep openoffice 查看 進程是否啓動。

二、編寫Java代碼

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

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;

@Component
public class DocConverter {
	
	private static final Logger log = LoggerFactory.getLogger(DocConverter.class);
    
    @Value("${ccf.jodconverter.port}")
    private String port;
    
    @Value("${ccf.doc.dir}")
    private String docDir;
    
    @Value("${ccf.pdf.dir}")
    private String pdfDir;
    
	@Value("${ccf.doc.request.url}")
	private String docRequestUrl;
	
	@Value("${ccf.doc.download.url.reg}")
	private String reg;
	
	public DocResponse officeToPdf(String url) {
		if(StringUtils.isEmpty(url)) {
			return DocResponse.fail(505, "文檔地址不能爲空!");
		}
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(url);
		if(!matcher.matches()) {
			return DocResponse.fail(504, "文檔格式不支持,暫只支持[pdf、doc、docx、ppt、pptx、xls、xlsx]!");
		}
		String fileName = DigestUtils.md5DigestAsHex(url.getBytes());
		File pdfFile = new File(pdfDir+File.separator+fileName+".pdf");
		if(pdfFile.exists()) {
			return DocResponse.success(docRequestUrl+pdfFile.getName());
		}
		DocResponse downloadResponse = downloadByNIO(url);
		if(downloadResponse.getCode() != 0) {
			return downloadResponse;
		}
		DocResponse response = doc2pdf(downloadResponse.getMessage());
		
		return response;
	}
	
    
	private DocResponse downloadByNIO(String url) {
		 
		 String suffixName = url.substring(url.lastIndexOf("."), url.length());
		 //將下載地址轉換唯一的字符串
		 String fileName = DigestUtils.md5DigestAsHex(url.getBytes())+suffixName;
		 File file = new File(docDir+File.separator+fileName);
		 if(!file.exists()) {
			 long start = System.currentTimeMillis();
			 log.info("***開始下載文件:{}***",url);
		        try (InputStream ins = new URL(url).openStream()) {
		            Path target = Paths.get(docDir,fileName);
		            Files.createDirectories(target.getParent());
		            Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
		        } catch(FileNotFoundException e) {
		        	log.error("***文件不存在,無法下載:{}",url);
		        	return DocResponse.fail(404, "文件不存在,無法預覽:"+url);
		        }catch (IOException e) {
		            e.printStackTrace();
		            log.error("***文件下載失敗:{}***",url);
		            return DocResponse.fail(500, "件下載失敗:"+url);
		        }finally {
					log.info("***文件下載完成,耗時:{} ms***",(System.currentTimeMillis()-start));
				}
		 }
	     return DocResponse.success(docDir+File.separator+fileName);
	 }
      
    /** 
     * 轉爲PDF 
     *  
     * @param file 
     */  
    private DocResponse doc2pdf(String fileString) {
        String fileName = fileString.substring(fileString.lastIndexOf(File.separator), fileString.lastIndexOf("."));  
        File docFile = new File(fileString); 
        File pdfFile = new File(pdfDir+fileName + ".pdf");
        if (docFile.exists()) {  
            if (!pdfFile.exists()) {
            	long start = System.currentTimeMillis();
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(Integer.valueOf(port));  
                try {  
                    connection.connect();  
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
                    converter.convert(docFile, pdfFile);  

                    log.info("***轉換成功,PDF輸出:{},總耗時:{}***",pdfFile.getPath(),System.currentTimeMillis()-start);
                } catch (java.net.ConnectException e) {  
                    e.printStackTrace();  
                    log.error("****轉換器異常,openoffice服務未啓動!****");
                    return DocResponse.fail(501, "轉換器異常,openoffice服務未啓動!");
                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {  
                    e.printStackTrace();  
                    log.error("***轉換器異常,讀取轉換文件[{}]失敗!***",fileString);
                    return DocResponse.fail(502, "轉換器異常,讀取轉換文件["+fileString+"]失敗!");
                } catch (Exception e) {  
                    e.printStackTrace();  
                    log.error("***轉換器發生未知異常!***");
                    return DocResponse.fail(503, "轉換器發生未知異常!");
                }finally {
                    // close the connection  
                    connection.disconnect();  
				}
            } else {  
            	log.info("***對應pdf文件[{}]已存在***",pdfFile.getPath());
            }  
        } else {  
        	log.error("***文檔[{}]不存在,無法轉換!***",fileString);
        	return DocResponse.fail(404, "文檔不存在,無法轉換!");
        }  
        return DocResponse.success(docRequestUrl+pdfFile.getName());
    }  

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章