We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Trimming of spaces

Hi,
I wanted to trim the leading and trailing spaces of the paragraph text. I am iterating through the runs to build a string, removing the runs along the way and creating a paragraph with the new trimmed string.
However, if the paragraph contains hyperlink run.getText() returns some garbage string (like \HYPERLINK), is there any alternative to achieve this using Aspose 15.8.

Attached the sample doc for your reference,
Here is the code snippet:

 for (Run run : (Iterable<Run>) paragraph.getRuns()) {
      stringBuilder.append(run.getText());
      run.remove();
 }
// Trim the text and add back to the same paragraph
Run trimmedRun = new Run(doc, stringBuilder.toString().trim());
paragraph.appendChild(trimmedRun);
  
Regards,
Prem Latha
Hi Prem,

Thanks for your inquiry. In your case, you need to remove the leading spaces of first Run node and trailing spaces of last Run node of Paragraph node. Please use following code example to achieve the desired output. Hope this helps you.

private final static Pattern LTRIM = Pattern.compile("^\\s+");
private final static Pattern RTRIM = Pattern.compile("\\s+$");

public static String ltrim(String s) {
return LTRIM.matcher(s).replaceAll("");
}

public static String rtrim(String s) {
return RTRIM.matcher(s).replaceAll("");
}

Document doc = new Document(MyDir + "Test+sample.docx");
for (Paragraph paragraph : (Iterable)doc.getChildNodes(NodeType.PARAGRAPH, true))
{
if(paragraph.getRuns().getCount() > 0)
{
//Remove the leading spaces of first Run node of Paragraph
Run run = paragraph.getRuns().get(0);
run.setText(ltrim(run.getText()));

//Remove the trailing spaces of last Run node of Paragraph
run = paragraph.getRuns().get(paragraph.getRuns().getCount() -1);
run.setText(rtrim(run.getText()));
}
}
doc.save(MyDir + "out v16.12.0.docx");