Microsoft word issue using .net - word addin

phani kumar 0 Reputation points
2026-09-23T11:41:32.96+00:00

Hi, I am getting below problem in Word add-in. Please help me in fixing this.

I have word document with bookmarks , when i do save as of that document -> save as type(pdf),click on options below are my options which i have books marks are getting correctlyUser's image

User's image

the above heading is coming from table of contents from word document which is below

1.1           Heading 2 [Alt+2]

1.1.1           Heading 3 [Alt+3]

1.1.1.1           Heading 4 Alt+4

1.1.1.1.1                Heading 4 [Alt+5]
a.         Heading 6 [Alt+6]

1)        Heading 7 [Alt+7]

a)         Heading 8 [Alt+8]

(1)      Heading 9 [Alt+9]

Text_Normal [Alt+T, N]

Indent_1 [Alt+I, 1]

Indent_2 [Alt+I, 2]

Indent_3 [Alt+I, 3]

Indent_4 [Alt+I, 4]

Indent_5 [Alt+I, 5]

X    Text_a. [Alt+T,A]

X    Text_1) [Alt+T,1]

X    Text_(a) [Alt+T,B]

X    Text_(1) [Alt+T,2]

·     Bullet_1 [Alt+B, 1]

·     Bullet_2 [Alt+B, 2]

·     Bullet_3 [Alt+B, 3]

·     Bullet_4 [Alt+B, 4]

·     Bullet_5 [Alt+B, 5]

-    Dash_1 [Alt+D, 1]

-    Dash_2 [Alt+D, 2]

-    Dash_3 [Alt+D, 3]

-    Dash_4 [Alt+D, 4]

-    Dash_5 [Alt+D, 5]

o  Ring_1 [Alt+R, 1]

from code

books marks are getting correctly

public static bool ConvertWordToPDFXPS(Microsoft.Office.Interop.Word.Application wordApplication,

                                    string sourceFilePath,

                                    string targetFilePath,

                                    string targetFormat,

                                    out string sOutputError)

    {

        bool bRetVal = true;

        sOutputError = string.Empty;

        // Create an instance of the Word ApplicationClass object. 

        //Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();


        

        //// Disable all macros & security warnings

        if ("true".Equals(msoAutomationSecurityForceDisable, StringComparison.InvariantCultureIgnoreCase))

        {

            wordApplication.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;

        }

        // Disable all Alerts

        wordApplication.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;

        // Declare a variable to hold the reference to the document.

        _Document wordDocument = null;

        object paramSourceFilePath = sourceFilePath;

        object paramTrue = true;

        object paramFalse = false;

        object paramMissing = Type.Missing;

        object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;

        WdExportFormat paramExportFormat;

        //Target format could be "PDF", "XPS" or empty. 

        //When empty the default format is "PDF" 

        if ("XPS".Equals(targetFormat.ToUpperInvariant())) { paramExportFormat = WdExportFormat.wdExportFormatXPS; }

        else { paramExportFormat = WdExportFormat.wdExportFormatPDF; }

        try

        {

            // Open the source document.

            wordDocument = wordApplication.Documents.Open(

                            ref paramSourceFilePath,    //FileName - Required Object. The name of the document 

                            ref paramMissing,           //ConfirmConversions - Optional Object. True to display the Convert File dialog box if the file isn't in Microsoft Word format

                            ref paramFalse,              //ReadOnly - Optional Object. True to open the document as read-only           

                            ref paramMissing,           //AddToRecentFiles - Optional Object. True to add the file name to the list of recently used files at the bottom of the File menu

                            ref wordPassword,           //PasswordDocument - Optional Object. The password for opening the document

                            ref paramMissing,           //PasswordTemplate - Optional Object. The password for opening the template

                            ref paramTrue,              //Revert - Optional Object. Controls what happens if FileName is the name of an open document. True to discard any unsaved changes to the open document and reopen the file. False to activate the open document 

                            ref paramMissing,           //WritePasswordDocument - Optional Object. The password for saving changes to the document

                            ref paramMissing,           //WritePasswordTemplate - Optional Object. The password for saving changes to the template

                            ref paramMissing,           //Format - Optional Object. The file converter to be used to open the document. Can be a WdOpenFormat constant

                            ref paramMissing,           //Encoding - Optional Object. The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. The default value is the system code page

                            ref paramTrue,             //Visible - Optional Object. True if the document is opened in a visible window. The default value is True

                            ref paramMissing,           //OpenAndRepair - Optional Object. True to repair the document to prevent document corruption

                            ref paramMissing,           //DocumentDirection - Optional Object. Can be a WdDocumentDirection constant

                            ref paramTrue,              //NoEncodingDialog - Optional Object. True to skip displaying the Encoding dialog box that Word displays if the text encoding cannot be recognized. The default value is False.

                            ref paramMissing);          //XMLTransform - Optional Object. Specifies a transform to use.

            // Export it in the specified format.

            if (wordDocument != null)

            {

                //Disable all Fill-In and Ask types of fields to prevent pop-ups with requests to insert value   

                DisableWordFillInFields((Document)wordDocument);

                //Convert to PDF

                wordDocument.ExportAsFixedFormat(

                            targetFilePath,             //OutputFileName - Required String. The path and file name name of the new PDF or XPS file.  

                            paramExportFormat,          //ExportFormat - Required WdExportFormat. Specifies either PDF or XPS format.  

                            false,                      //OpenAfterExport - Optional Boolean. Opens the new file after exporting the contents  

                            WdExportOptimizeFor.wdExportOptimizeForPrint, //OptimizeFor - Optional WdExportOptimizeFor. Specifies whether to optimize for screen or print  

                            WdExportRange.wdExportAllDocument, //Range - Optional WdExportRange. Specifies whether the export range is the entire document, the current page, a range of text, or the current selection. the default is to export the entire document 

                            0,                          //From - Optional Long. Specifies the starting page number, if the Range parameter is set to wdExportFromTo 

                            0,                          //To - Optional Long. Specifies the ending page number, if the Range parameter is set to wdExportFromTo 

                            WdExportItem.wdExportDocumentContent, //Item - Optional WdExportItem. Specifies whether the export process includes text only or includes text with markup 

                            true,                       //IncludeDocProps - Optional Boolean. Specifies whether to include document properties in the newly exported file  

                            true,                       //KeepIRM - Optional Boolean. Specifies whether to copy IRM permissions to an XPS document if the source document has IRM protections. Default value is True  

                            WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, //CreateBookmarks - Optional WdExportCreateBookmarks. Specifies whether to export bookmarks and the type of bookmarks to export  

                            true,                       //DocStructureTags - Optional Boolean. Specifies whether to include extra data to help screen readers, for example information about the flow and logical organization of the content. Default value is True  

                            true,                       //BitmapMissingFonts - Optional Boolean. Specifies whether to include a bitmap of the text. Set this parameter to True when font licenses do not permit a font to be embedded in the PDF file. If False, the font is referenced, and the viewer's computer substitutes an appropriate font if the authored one is not available. Default value is True  

                            false,                      //UseISO19005_1 - Optional Boolean. Specifies whether to limit PDF usage to the PDF subset standardized as ISO 19005-1. If True, the resulting files are more reliably self-contained but may be larger or show more visual artifacts due to the restrictions of the format. Default value is False 

                            ref paramMissing);          //FixedFormatExtClassPtr - Optional Variant. Specifies a pointer to an add-in that allows calls to an alternate implementation of code. The alternate implementation of code interprets the EMF and EMF+ page descriptions that are generated by the applications to make their own PDF or XPS 

                //wordDocument.Close(ref doNotSaveChanges, ref paramMissing, ref paramMissing);

                //wordDocument = null;

            }

        }

        catch (System.Exception ex)

        {                

            sOutputError = string.Format("ERROR - Password proteced: \n{0}\n{1}", sourceFilePath, ex.ToString());

            System.Reflection.MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();

            object[] vecMethodParameters = new object[3];

            vecMethodParameters[0] = sourceFilePath;

            vecMethodParameters[1] = targetFilePath;

            vecMethodParameters[2] = targetFormat;                

            bRetVal = false;

        }

        finally

        {

            // Close and release the Document object.

            //if (wordDocument != null)

            //{

            //    wordDocument.Close(ref doNotSaveChanges, ref paramMissing, ref paramMissing);

            //    wordDocument = null;

            //}

            // Quit Word and release the ApplicationClass object.

            //if (wordApplication != null)

            //{

            //    wordApplication.Quit(ref doNotSaveChanges, ref paramMissing, ref paramMissing);

            //    wordApplication = null;

            //}

            GC.Collect();

            GC.WaitForPendingFinalizers();

            GC.Collect();

            GC.WaitForPendingFinalizers();

        }

        return bRetVal;

    }
Bookmarks are not coming correctly. coming like this. these are coming from   
  




**Question is how to get the bookmarks from Table of contents with my code are there any other options.I have used WdExportCreateBookmarks.wdExportCreateHeadingBookmarks in one of the parameters**

Microsoft 365 and Office | Microsoft Forms | For business

1 answer

Sort by: Most helpful
  1. Liora 2,080 Reputation points Independent Advisor
    2026-09-23T13:27:31.7133333+00:00

    Dear @phani kumar,

    I hope you’re having a good day. 

    Thank you for sharing the additional details.

    I spent some time testing a similar scenario with a Word document containing a Table of Contents, Heading 1-5 styles, and Word bookmarks. From my testing, I found that Word can generate PDF bookmarks from either the document's heading structure or from Word bookmarks, depending on the export method used.

    Your code is already using:

    WdExportCreateBookmarks.wdExportCreateHeadingBookmarks
    

    which is the correct option if the goal is to create PDF bookmarks from the document's heading hierarchy.

    One important observation is that Word Interop does not appear to provide a separate option to create PDF bookmarks directly from the Table of Contents entries themselves. The available export options are based on Headings or Word Bookmarks, not the TOC object.

    Before exporting, you may want to ensure the document structure is fully updated:

    wordDocument.Fields.Update();
    
    foreach (TableOfContents toc in wordDocument.TablesOfContents)
    {
        toc.Update();
    }
    
    

    and then perform the export again using:

    WdExportCreateBookmarks.wdExportCreateHeadingBookmarks
    
    

    If your requirement is for the PDF bookmark tree to exactly match the TOC entries shown in the document, a possible approach would be to read the TOC programmatically, export the PDF normally, and then create the PDF bookmarks with a PDF library after export.

    Since this question is very specific to Word Interop, document structure, and PDF bookmark generation, I would also recommend posting the question in the Microsoft Tech Community developer forums, where Word automation and Office add-in developers are more likely to have experience with this scenario: Home | Microsoft Community Hub

    User's image

    I hope this information is helpful. If you discover any additional differences between the PDF generated manually and the PDF generated through ExportAsFixedFormat(), please share them, as they may help narrow down the behavior further.

    Looking forward to hearing back from you with any updates or additional details.  

    Warm regards,  


    If the answer is helpful, please select "Yes, accept answer". If you have any questions or new updates, please feel free to comment below.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.