Office文档转pdf格式(三)
上面两篇介绍的Office文档转pdf格式的方式都只能在Windows系统下使用,存在一定的局限性,本文介绍一个在Windows和Linux下都可以使用的,而且是开源且免费的软件:LibreOffice,下载地址为:https://www.libreoffice.org/download/download-libreoffice/,使用这个软件,可以通过命令或者代码的方式来实现将Office文档转为pdf格式。具体方法如下:
1. 前提条件
安装LibreOffice软件,选择Windows(64位),点击下载,然后进行安装。
2. 通过命令方式转换
打开cmd命令行窗口,切换到目录C:\Program Files\LibreOffice\program\下面(或者可将其添加到环境变量中),输入命令:
soffice.exe --convert-to pdf --nologo 源文件全路径 --outdir 目标目录
3. 通过代码方式转换
实际上就是用代码的方式来运行LibreOffice,并执行转换命令(需要将C:\Program Files\LibreOffice整个目录拷到转换项目的运行目录下),示例代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSearch_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "文档|*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx;"; if (dialog.ShowDialog() == DialogResult.OK) { txtFilePath.Text = dialog.FileName; } } private void btnConvert_Click(object sender, EventArgs e) { string sourceFileFullName = txtFilePath.Text.Trim(); if (string.IsNullOrEmpty(sourceFileFullName)) { MessageBox.Show("请先选择要转换的文件!"); return; } FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "选择一个目录"; dialog.SelectedPath = Path.GetDirectoryName(sourceFileFullName); if (dialog.ShowDialog() == DialogResult.OK) { string targetFilePath = dialog.SelectedPath; try { string libreOfficePath = GetLibreOfficePath(); ProcessStartInfo procStartInfo = new ProcessStartInfo(libreOfficePath, string.Format("--convert-to pdf --nologo {0} --outdir {1}", sourceFileFullName, targetFilePath)); 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); } MessageBox.Show("转换成功!"); } catch(Exception ex) { MessageBox.Show("转换失败!"); } } } private string GetLibreOfficePath() { switch (Environment.OSVersion.Platform) { case PlatformID.Unix: return "/usr/bin/soffice"; case PlatformID.Win32NT: string binaryDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); return binaryDirectory + "\\LibreOffice\\program\\soffice.exe"; default: throw new PlatformNotSupportedException("你的系统暂不支持!"); } } } public class LibreOfficeFailedException : Exception { public LibreOfficeFailedException(int exitCode) : base(string.Format("LibreOffice错误 {0}", exitCode)) { } }