【java】doc轉pdf

市場上主流的 WORD 轉 PDF 工具備兩個:OpenOffice 和 Microsoft Office 轉
換插件,能夠經過部署這兩個工具實現 WORD 轉 PDF 功能。java

1:linux

Microsoft 提 供 了 一 個 轉 換 插 件 實 現 Office 轉 PDF 功 能 , 即
SaveAsPDFandXPS。此插件是一個 com 組件,對於 C++、C#等語言能夠直接使
用,若是是 JAVA 語言,須要經過 jacob 來調用 com 組件。
SaveAsPDFandXPS 插件要求必須有一臺 Windows 服務器做爲轉換服務器安
裝部署 Microsoft Office2007 以上的版本,而後再安裝 SaveAsPDFandXPS 插件。
最後調用 com 組件實現轉換。
官網地址:https://msdn.microsoft.com/en-us/library/dd301166(v=nav.90).aspxubuntu

2.服務器

OpenOffice 是個開源的辦公套件,提供了與 MS Word,Excel,PowerPoint 等
對應的多個軟件,它支持包括 MS Office 2007 在內的多種格式,而且可以將其導
出爲 PDF 文件。
這個方案是在 linux 服務器上安裝 openOffice 而後經過 openOffice 命令來轉換
pdf。
官方網址:http://www.openoffice.org/less

在ubuntu下:socket

  1. tar -xvzf Apache_OpenOffice_4.1.3_Linux_x86-64_install-deb_zh-CN.tar.gz   
  2. cd zh-CN/DEBS/  
  3. sudo dpkg -i *.deb  
  4. cd desktop-integration/  
  5. sudo dpkg -i openoffice4.1-debian-menus_4.1.3-9783_all.deb  

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

啓動服務,# netstat -an|more,可查看是否啓動成功(是否有8100端口的服務)測試

package openofficeTest;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.ConnectException;  
  
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;  
import com.artofsolving.jodconverter.DocumentConverter;  
import com.artofsolving.jodconverter.DocumentFormat;  
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;  
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;  
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;  
  
  
public class Word2Pdf {  
   
    public static int PORT = 8100;  public static void main(String[] args){  

     String path1 = "/tmp/1.doc";  
     String path2 = "/tmp/2.pdf";  
        try {  
            wordToPdf(path1, path2);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
 
    public static void wordToPdf(String path1, String path2)  
            throws Exception {  
        File file1 = new File(path1);  
        File file2 = new File(path2);  
        // 得到文件格式  
        DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();  
        DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf");  
        DocumentFormat docFormat = formatReg.getFormatByFileExtension("doc");  
        // stream 流的形式  
        InputStream inputStream = new FileInputStream(file1);  
        OutputStream outputStream = new FileOutputStream(file2);  
   
        /** 
         *  
         */  
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(PORT);  
        System.out.println(connection);  
        try {  
   
            connection.connect();  
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
            converter.convert(inputStream, docFormat, outputStream, pdfFormat);  
        } catch (ConnectException e) {  
            e.printStackTrace();  
        } finally {  
            if (connection != null) {  
                connection.disconnect();  
                connection = null;  
            }  
        }  
    }  
   
  
}  

 可是,通過測試,openoffice轉換的速度明顯很慢,主要是在獲取OpenOfficeConnection這塊,我目前尚未找到能明顯提高速度的方法,下面還有第三種基於libreoffice作轉換的方式。ui

前提條件:要安裝libreoffice, libreoffice-headlessspa

安裝命令:

yum install libreoffice -y

yum install libreoffice-headless -y

轉換命令:libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /tmp/ /tmp/test.doc

其中/tmp/test.doc爲測試用的doc文件,生成的pdf文件會在/tmp/下,名稱會默認和doc的名字同樣。

下面是項目中以doc文件流輸入,返回pdf文件流的方法。

public static byte[] toPDF(byte[] b, String sourceFileName) throws Exception{
        
        File tempDir = null;
        try{
            tempDir = Files.createTempDir();
            
            String canonicalPath = tempDir.getCanonicalPath();
            
            File file = new File(canonicalPath + "/" + sourceFileName);

            OutputStream os = new FileOutputStream(file);

            BufferedOutputStream bufferedOutput = new BufferedOutputStream(os);

            bufferedOutput.write(b);
            
            String command = "libreoffice";
            
            Process proc = new ProcessBuilder(command, "--headless", "--convert-to", "pdf:writer_pdf_Export", "--outdir", canonicalPath, canonicalPath + "/" + sourceFileName)
                               .redirectErrorStream(true)
                               .start(); 
            
            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                output.add(line);
            
            logger.info("執行pdf轉換命令的輸出:" + StringUtils.join(output, System.lineSeparator()));
            
            if (0 != proc.waitFor())
                throw new Exception("轉換失敗");
            
            File[] files = tempDir.listFiles();
            for (File file2 : files) {
                if (file2.getPath().endsWith(".pdf")) {
                    return IOUtils.toByteArray(new FileInputStream(file2));
                }
            }
            return null;
        }finally{
            if(tempDir != null)
                FileUtils.deleteDirectory(tempDir);
        }
    }
相關文章
相關標籤/搜索