java doc轉pdf

來源:互聯網
上載者:User

標籤:filename   rto   amp   pen   sof   預設   java   white   builder   

市場上主流的 WORD 轉 PDF 工具有兩個:OpenOffice 和 Microsoft Office 轉
換外掛程式,可以通過部署這兩個工具實現 WORD 轉 PDF 功能。

1:

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).aspx

2.

OpenOffice 是個開源的辦公套件,提供了與 MS Word,Excel,PowerPoint 等
對應的多個軟體,它支援包括 MS Office 2007 在內的多種格式,並且能夠將其導
出為 PDF 檔案。
這個方案是在 linux 伺服器上安裝 openOffice 然後通過 openOffice 命令來轉換
pdf。
官方網址:http://www.openoffice.org/

在ubuntu下:

  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做轉換的方式。

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

安裝命令:

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);        }    }

 

java doc轉pdf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.