Free Support Forum - aspose.com

Bookmarks are not generated when saving word as pdf

We have an issue with saving word documents as pdf.
We want pdf bookmarks to be generated and we have written code to do so.
But if we do not save the word document into an stream it will not work.
We do not know why.
please see the attached project:

DocumentApp1.zip (184.6 KB)

This is desired output with bookmarks generated:
Desired.pdf (50.0 KB)

these are input documents:
input.zip (21.8 KB)

@Mo2,

Please try using the following code:

Document document = new Document("D:\\Temp\\input (2)\\TestTocForSample.docx");
Document child = new Document("D:\\Temp\\input (2)\\TestTocForSample2.docx");

document.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
document.AppendDocument(child, ImportFormatMode.KeepSourceFormatting);

document.UpdateFields();

//As soon as we uncomment the following block bookmarks get generated. why we need this block?

//using (var stream = new MemoryStream())
//{
//    document.Save(stream, SaveFormat.Docx);
//    var temp = new Document(stream);
//    document = temp;
//}

CreateBookmarks(document);           

var pdfSaveOptions = new Aspose.Words.Saving.PdfSaveOptions
{
    JpegQuality = 100,
    EmbedFullFonts = false,
    SaveFormat = Aspose.Words.SaveFormat.Pdf
               
};
pdfSaveOptions.OutlineOptions.DefaultBookmarksOutlineLevel = 1;

document.UpdatePageLayout();
document.Save("D:\\Temp\\input (2)\\18.8.pdf", pdfSaveOptions);

private static void CreateBookmarks(Document document)
{
    DocumentBuilder documentBuilder = new DocumentBuilder(document);
    foreach (Aspose.Words.Bookmark bm in document.Range.Bookmarks)
    {
        if (bm.Name.StartsWith("_Toc"))
        {
            documentBuilder.MoveToBookmark(bm.Name, false, false);
            var bmText = bm.Text;
            documentBuilder.StartBookmark(bmText);
            documentBuilder.EndBookmark(bmText);
        }
    }
}