Exporting Document Fragments as Images

Since we have customer using this kind of document, We might not know how they created the document.
Is there a way we can fix this kind of issue and can we generate image?

p.s: somehow I am not able to download the docx.

plus I am getting an exception

“stackTrace”: " at DocConversionApi.Controllers.ConvertController.RenderNode(Node node, ImageSaveOptions imageOptions, String savePath) in /Users/ConvertController.cs:line 225\n at DocConversionApi.Controllers.ConvertController.ConvertDocx2Html(Stream data) in /Users/ConvertController.cs:line 102\n at lambda_method5(Closure , Object , Object[] )\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()\n— End of stack trace from previous location —\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()\n— End of stack trace from previous location —\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\n at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.InvokeCore(HttpContext context, PathString matchedPath, PathString remainingPath)\n at DocConversionApi.Middlewares.HandleExceptionMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) in /Users/Middlewares/HandleExceptionMiddleware.cs:line 47"
}

any idea how to fix it?

@m.darshan.shah Unfortunately, there is no way to keep the position of the image inside the form, and this is not a general solution for that. The only way is to put all the content inside the blue shape and try to change the position of the paragraphs:

if (currentNode is InlineStory || currentNode is Story)
{
    CompositeNode composite = (CompositeNode)currentNode;
    NodeCollection compositeNodes = composite.GetChildNodes(NodeType.Any, false);
    if (compositeNodes.Count == 1 && compositeNodes[0].GetText().Trim().Equals(string.Empty))
        return;
    foreach (Node childNode in composite.GetChildNodes(NodeType.Any, false))
    {
        if (childNode == null) continue;

        Paragraph shapeParagraph = shape.FirstParagraph;
        if (shapeParagraph != null && shapeParagraph.FirstChild is Shape)
        {
            Shape childShape = shapeParagraph.FirstChild as Shape;
            childShape.AppendChild(childNode.Clone(true));
        }
        else
            shape.AppendChild(childNode.Clone(true));
    }
}

or try to create a table inside the shape and put the form in the text in the cells. But this solution is only for one case with such forms.

@m.darshan.shah It is not clear from this message what the problem is. I don’t think I can help you with this issue without debugging.

@vyacheslav.deryushev
headerFooter.docx (286.6 KB)

I am facing bit of a strange issue.
after the executing this file. Header image is not looking perfect any idea what could be the issue?

@m.darshan.shah You are using Aspose.Words without a license, so the resulting document has an image inside the header, which is causing this problem. Please check the license if you have one, or you can get a temporary license for your tests. Please check Temporary License - Purchase - aspose.com

1 Like

@m.darshan.shah You can try using the following simple code to convert headers/footers to image:

Document doc = new Document("C:\\Temp\\in.docx");

int sectIndex = 0;
foreach (Section s in doc.Sections)
{
    foreach (HeaderFooter hf in s.HeadersFooters)
    {
        // Create a temporary document for rendering header content.
        Document tmp = (Document)doc.Clone(false);
        tmp.Sections.Add(tmp.ImportNode(hf.ParentSection, false, ImportFormatMode.UseDestinationStyles));
        tmp.FirstSection.AppendChild(new Body(tmp));
        // Copy content of the header to the temporary section.
        foreach (Node n in hf.GetChildNodes(NodeType.Any, false))
            tmp.FirstSection.Body.AppendChild(tmp.ImportNode(n, true, ImportFormatMode.UseDestinationStyles));

        // Remove top and bottom margins.
        tmp.FirstSection.PageSetup.TopMargin = 0;
        tmp.FirstSection.PageSetup.BottomMargin = 0;

        // Use LayoutEnumerator to calculate the bottom edge fo visible content.
        LayoutEnumerator enumerator = new LayoutEnumerator(tmp);
        RectangleF rect = RectangleF.Empty;
        rect = CalculateVisibleRect(enumerator, rect);
        tmp.FirstSection.PageSetup.PageHeight = rect.Height;
        Console.WriteLine(rect.Height);
        tmp.UpdatePageLayout();

        tmp.Save($@"C:\Temp\hf_{sectIndex}_{hf.HeaderFooterType}.png");
    }

    sectIndex++;
}
private static RectangleF CalculateVisibleRect(LayoutEnumerator enumerator, RectangleF rect)
{
    RectangleF result = rect;
    do
    {
        if (enumerator.MoveFirstChild())
        {
            if (enumerator.Type == LayoutEntityType.Line || enumerator.Type == LayoutEntityType.Span)
                result = result.IsEmpty ? enumerator.Rectangle : RectangleF.Union(result, enumerator.Rectangle);
            result = CalculateVisibleRect(enumerator, result);
            enumerator.MoveParent();
        }
    } while (enumerator.MoveNext());

    return result;
}

Hi @alexey.noskov , that’s great. its working fine. but its creating the big image with white space,
is there a way I can create just header content and footer content ?

@m.darshan.shah I cannot reproduce the problem. Most likely you are using Aspose.Words in evaluation more and size of watermark is included into the calculation.

1 Like