Calculate left indent of paragraph

Good morning everyone,

I am facing an issue when I try to find the LeftIndent (the space between the left border of my document and my text) of a paragraph. I have developped the following function :

private double GetActualIndent(Aspose.Words.Paragraph paragraph){
        return paragraph.ParagraphFormat.LeftIndent + paragraph.ParagraphFormat.FirstLineIndent;
}

It works fine when the paragraph alignment is “Left” or “Justify”. However, when it is either “Right” or “Center”, the value is always 0. If I understand, it is because the “paragraph.ParagraphFormat.LeftIndent” and “paragraph.ParagraphFormat.FirstLineIndent” values are linked with the alignment type of the paragraph.

How could I calculate the following space between the left border of my sheet and the first character of my paragraph (the blue arrow), please ?

Thank you very much for your help,
Best regards

@BlackSea You can use LayoutCollector and LayoutEnumerator to calculate this position. For example see the following code:

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

// Wrap paragraph into the bookmakrs.
int bkIndex = 0;
foreach (Paragraph p in doc.GetChildNodes(NodeType.Paragraph, true))
{
    // LayoutCollector and LayoutEnumerator work only with nodes in the main document body.
    if (p.GetAncestor(NodeType.HeaderFooter) != null || p.GetAncestor(NodeType.Shape) != null)
        continue;

    string bkName = $"_tmp_{bkIndex++}";
    p.PrependChild(new BookmarkStart(doc, bkName));
    p.AppendChild(new BookmarkEnd(doc, bkName));
}

// Use LayoutCollector and LayoutEnumerator to calculate paragraph bounds.
LayoutCollector collector = new LayoutCollector(doc);
LayoutEnumerator enumerator = new LayoutEnumerator(doc);

// Get position of bookmakr starts. This position will give an absolute coordinates of paragraphs first line.
foreach (Bookmark bk in doc.Range.Bookmarks)
{
    if(!bk.Name.StartsWith("_tmp_"))
        continue;

    enumerator.Current = collector.GetEntity(bk.BookmarkStart);
    Console.WriteLine(enumerator.Rectangle);
}

Thank you very much for your answer, it works perfectly!

1 Like