C# Word 转换 PDF 文件,如何转换 PDF

添加COM引用,本机已安装 Microsoft Office 2013,如果COM引用里没有"Microsoft Office x.x Object Library",则需要安装 Microsoft Office 软件。


C#代码

using System;
using System.IO;
using Word = Microsoft.Office.Interop.Word;

namespace ConsoleApp18
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                WordToPdf(AppDomain.CurrentDomain.BaseDirectory + "test.docx", AppDomain.CurrentDomain.BaseDirectory + "test.pdf");
                Console.WriteLine("Success");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }

        /// <summary>
        /// Word 转 Pdf
        /// </summary>
        /// <param name="sorucePath">The word path.</param>
        /// <param name="savePath">Save pdf path.</param>
        public static void WordToPdf(string sorucePath, string savePath)
        {
            Word.Application application = new Word.Application();
            Word.Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(sorucePath);

                // 目标存在则先删除
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                document.ExportAsFixedFormat(savePath, Word.WdExportFormat.wdExportFormatPDF);
            }
            catch
            {
                throw;
            }
            finally
            {
                document.Close();
                application.Quit();
                // 强制回收
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }
}


作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角