Issue when insert Image and Table of Content

Hi all,

When I insert an image to my existing document, it works as expected.
But when I insert an image and a table of content to my existing document, it doesn’t. There are 2 images in my document. I don’t know why. Please help me in this case. I am using Aspose.Words: 17.7.0

Please take a look on 2 lines:

builder.InsertTableOfContents("\o “1-3” \h \z \u");
dstDoc.UpdateFields();

If I comment 2 above lines, it works. But I also want to have a table of content in my document, then it doesn’t.
This is my function. I also upload my 2 generated documents. Please help to take a look.

Thank you so much.

    public async Task<IActionResult> GenerateBooklet2()
    {
        try
        {
            var documentIds = new List<int> {21};

            var bookletName = $"Generated Booklet_{DateTime.Now.ToString("ddMMyyyyHHmm")}.docx";

            Document dstDoc = new Document("bookletCoverTemplate.docx");

            DocumentBuilder builder = new DocumentBuilder(dstDoc);

            builder.MoveToDocumentEnd();
            builder.InsertBreak(BreakType.PageBreak);

            builder.Writeln("Table of Contents");

            builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

            IAzureAdTokenService tokenCache = (IAzureAdTokenService)HttpContext.RequestServices.GetService(typeof(IAzureAdTokenService));
            ClientContext context = await tokenCache.GetExpd8SiteClientContextAsync();
            var docs = _sharePointService.GetDocumentByIds(context, Constants.DocumentTemplates, documentIds.ToArray());

            var fileName = string.Empty;
            foreach (var doc in docs)
            {
                var binaryStream = doc.File.OpenBinaryStream();
                context.Load(doc);
                context.ExecuteQuery();
                fileName = doc["FileLeafRef"].ToString();

                AddItem(builder, "Item " + fileName);

                if (fileName.IsImage())
                {
                    ExtensionMethod.CreateFileStream(binaryStream.Value, fileName);

                    builder.MoveToDocumentEnd();

                    builder.InsertImage(fileName);

                    System.IO.File.Delete(fileName);
                }
            }

            dstDoc.UpdateFields();

            dstDoc.Save("C:\\" + bookletName);

            return Ok(1);
        }
        catch (Exception ex)
        {
            _telemetry.TrackException(ex);
            return new StatusCodeResult(500);
        }
    }

private void AddItem(DocumentBuilder builder, string text)
{
Aspose.Words.Font font = builder.Font;
font.Size = 26;
font.Bold = true;

        font.Name = "Arial";

        builder.InsertBreak(BreakType.LineBreak);

        builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
        builder.Writeln(text);
    }

Denerated Documents.zip (492.1 KB)

@tuandomvn,

Thanks for your inquiry. To ensure a timely and accurate response, please attach the following resources here for testing:

  • Your input Word document.
  • Your input image.
  • Please create a standalone console application (source code without compilation errors) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we’ll start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

Dear @tahir.manzoor,

Please see the standalone console application in the attachment. I have the input folder (with word and image) and output folder in this path: InsertImageWithTOC\src\InsertImageWithTOC\bin\Debug\net461\win7-x64

InsertImageWithTOC.zip (536.9 KB)

Please notice that if I comment 2 lines below (line 35 and 45), it works. But I also want to have a table of content in my document, then it will generate 2 images.

builder.InsertTableOfContents("\o “1-3” \h \z \u");
dstDoc.UpdateFields();

Please help to investigate the issue.
Thanks

@tuandomvn,

Thanks for sharing the detail. Please use the following modified code to get the desired output. We suggest you please read following article. Hope this helps you.
How to Insert and Work with the Table of Contents Field

public static void GenerateBooklet()
{
    try
    {
        var fileFolder = AppDomain.CurrentDomain.BaseDirectory;

        Document dstDoc = new Document(fileFolder + "bookletCoverTemplate.docx");

        DocumentBuilder builder = new DocumentBuilder(dstDoc);

        builder.MoveToDocumentEnd();
        builder.InsertBreak(BreakType.PageBreak);

        builder.Writeln("Table of Contents");
        //Resets to default paragraph formatting. 	
        builder.ParagraphFormat.ClearFormatting();
        builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");


        var fileName = fileFolder + "2.png";
        AddItem(builder, "My picture " + fileName);
        builder.MoveToDocumentEnd();

        builder.Font.ClearFormatting();
        builder.InsertImage(fileName);
        dstDoc.UpdateFields();

        var bookletName = $"Generated Booklet_{DateTime.Now.ToString("ddMMyyyyHHmm")}.docx";
        dstDoc.Save(fileFolder + "output\\" + bookletName);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

private static void AddItem(DocumentBuilder builder, string text)
{
    Aspose.Words.Font font = builder.Font;
    font.Size = 26;
    font.Bold = true;

    font.Name = "Arial";

    builder.InsertBreak(BreakType.LineBreak);

    builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
    builder.Writeln(text);
    //Resets to default paragraph formatting. 	
    builder.ParagraphFormat.ClearFormatting();
}