Free Support Forum - aspose.com

How to Trim Paragraphs?

Hello,
I am importing paragraph nodes into another document by using VisitParagraphStart function. But my problem is the original paragraph has a lot of white spaces and unwanted new line characters in beginning and at the end or paragraph, which I need to trim before importing them to new document. Can you please show me how can I trim the beginning and end of paragraphs?

Here is what I need to do:

Public Overrides Function VisitParagraphStart(ByVal paragraph As Aspose.Words.Paragraph) As Aspose.Words.VisitorAction

Dim oCommentDoc As New Document

Dim oImp As New NodeImporter(paragraph.Document, oCommentDoc, ImportFormatMode.KeepSourceFormatting)

‘Here, Before Importing the Nodes, I need to Trim Unwanted spaces.

Dim oTempPara As Paragraph = oImp.ImportNode(Paragraph, True)

oCommentDoc.FirstSection.Body.AppendChild(oTempPara)

oCommentDoc.Save(“C:\Temp.Doc”)

Return VisitorAction.Continue

End Function

Thanks in advance,

Jerry

Hi

Thanks for your request. Try to use the following code to achieve this.

public override VisitorAction VisitParagraphStart(Paragraph paragraph)

{

Document doc = new Document("out_97926.doc");

NodeImporter importer = new NodeImporter(paragraph.Document, doc, ImportFormatMode.KeepSourceFormatting);

Paragraph par = (Paragraph)importer.ImportNode(paragraph, true);

if (par.Runs.Count > 0)

{

//remove spaces at the beginning of paragraph

while (par.Runs[0].Text.Substring(0, 1) == " ")

{

par.Runs[0].Text = par.Runs[0].Text.Remove(0, 1);

}

//remove spaces at the end of paragraph

int lastRunIndex = par.Runs.Count - 1;

int lastRunLenth = par.Runs[lastRunIndex].Text.Length;

while (par.Runs[lastRunIndex].Text.Substring(lastRunLenth - 1, 1) == " ")

{

par.Runs[lastRunIndex].Text = par.Runs[lastRunIndex].Text.Remove(lastRunLenth - 1, 1);

}

}

doc.FirstSection.Body.AppendChild(par);

doc.Save(@"out_97926.doc");

return VisitorAction.Continue;

}

I hope that it will help you.

Best regards.