C# word 转换 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();
            }
        }
    }
}


热门推荐