首页 > 解决方案 > 使用 C# 和 Word 互操作将 Word 导出为 PDF 不会将链接导出到文档中的书签

问题描述

我有一个 C# 程序,我使用 Word Interop 在 .docx 中创建报告。该文档完美地创建了几个“标题”,并带有指向文档内页面上的书签的链接,然后保存。然后我尝试使用 ExportAsFixedFormat 将其导出为 pdf,导出的文件包括那些“标题”,但没有指向书签的链接,而是蓝色并带有下划线。

我用于导出的设置:

doc.ExportAsFixedFormat(
                newPdfPath,                                             //output file name
                WdExportFormat.wdExportFormatPDF,                       //export format
                false,                                                  //open after export
                WdExportOptimizeFor.wdExportOptimizeForPrint,           //optimize for
                WdExportRange.wdExportAllDocument,                      //export range
                1,                                                      //from
                1,                                                      //to
                WdExportItem.wdExportDocumentWithMarkup,                //export item - only text or include text with markups
                true,                                                   //include dox properties
                true,                                                   //copy information rights management
                WdExportCreateBookmarks.wdExportCreateWordBookmarks,    //export bookmarks and which types
                true,                                                   //include extra data to help screen readers (info about flow and logical organization of content
                true,                                                   //bitmap missing fonts
                false);                                                  //use ISO 19005-1

知道我哪里出错了吗?

PS:如果我用MS word打开那个word文档并手动将其导出为PDF,那么导出的版本就是它应该的样子,里面有所有的链接,所以问题一定出在ExportAsFixedFormat的使用上。

标签: c#ms-wordinterop

解决方案


根据我的测试,我认为我们应该使用WdSaveFormat.wdFormatPDF而不是 WdExportFormat.wdExportFormatPDF.

这是您可以参考的代码示例。

        using Microsoft.Office.Interop.Word;
        object oMissing = System.Reflection.Missing.Value;
        string filename = "D:\\1.docx";
        Application app = new Application();
        Document doc = app.Documents.Open(filename);
        doc.Activate();
        object fullname = filename.Replace(".docx", ".pdf");
        object fileFormat = WdSaveFormat.wdFormatPDF;
        doc.SaveAs(ref fullname,ref fileFormat, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
        ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
        ((_Application)app).Quit(ref oMissing, ref oMissing, ref oMissing);

结果: 在此处输入图像描述


推荐阅读