借助LibreOffice, 該軟件是openoffice辦公套件衍生版,開源,支持多系統
下載地址:https://zh-cn.libreoffice.org/download/libreoffice/
linux下安裝方式
具體可見:https://wiki.documentfoundation.org/Documentation/Install/Linux
$ tar zxvf LibreOffice_$version_Linux_x86-rpm.tar.gz
$ cd LibreOffice_$version_Linux_x86-rpm/
$ cd RPMS/
Fedora / CentOS
$ su -c 'yum install *.rpm'
Mandriva / Mageia
$ su -c 'urpmi *.rpm'
Other RPM based systems =
su -c ‘rpm -Uvh *.rpm’
$ sudo ln -n -s /opt/libreoffice$version/ /usr/lib/libreoffice
通知執行libreoffice命令行命令進行轉換文件
$ soffice --convert-to pdf --outdir /home --nologo xxx.docx
/home :轉換后文件的目錄
xxx.docx:要轉換的文件
轉換后的pdf出現亂碼
原因:word中的字體在linux下不存在
解決方法:將字體文件拷貝到linux下
封裝類庫如下:
using DocXToPdfConverter; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; namespace Util { public class OfficeConverter { public static void DocxToPdf(string libreOfficePath, string officePath, string outPutPath) { //獲取libreoffice命令的路徑 //string libreOfficePath = getLibreOfficePath(); ProcessStartInfo procStartInfo = new ProcessStartInfo(libreOfficePath, string.Format("--convert-to pdf --outdir {0} --nologo {1}", outPutPath, officePath)); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; //procStartInfo.WorkingDirectory = Environment.CurrentDirectory; //開啟線程 Process process = new Process() { StartInfo = procStartInfo, }; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { throw new LibreOfficeFailedException(process.ExitCode); } } } public class LibreOfficeFailedException : Exception { public LibreOfficeFailedException(int exitCode) : base(string.Format("LibreOffice錯誤 {0}", exitCode)) { } } }