Hello,
I’m evaluating the Aspose.PDF .NET library. I’m trying to update an existing PDF by:
- Locating the first Paragraph in the pdf that contains a particular text string (e.g., “tite-text-to-replace”)
- Replacing that Paragraph with a small bit of HTML (e.g.,
<h2>Here is my title</h2>
)
The problem I’m running into is that the Aspose PDF API treats HtmlFragments differently than TextFragments, especially when it comes to positioning and coordinates.
I was able to create a method which locates the Paragraph using a ParagraphAbsorber:
private MarkupParagraph GetFirstParagraphWithText(string textToFind)
{
ParagraphAbsorber absorber = new ParagraphAbsorber();
absorber.Visit(_doc);
foreach (PageMarkup markup in absorber.PageMarkups)
{
foreach (MarkupSection section in markup.Sections)
{
foreach (MarkupParagraph paragraph in section.Paragraphs)
{
foreach (List<TextFragment> line in paragraph.Lines)
{
foreach (TextFragment fragment in line)
{
if (fragment.Text.Contains(textToFind))
{
return paragraph;
}
}
}
}
}
}
return null;
}
I then “replaced” that paragraph with my Html:
public void ReplaceTextWithHtml(string textToFind, string html)
{
MarkupParagraph markupParagraph = GetFirstParagraphWithText(textToFind);
HtmlFragment htmlFragment = new HtmlFragment(html);
// get reference of first fragment in the paragraph
TextFragment textFragment = markupParagraph.Fragments[0];
Page page = textFragment.Page;
Rectangle fragmentRect = (Rectangle)textFragment.Rectangle.Clone();
// Specify margins in order to position the new htmlFragment
// Determine X,Y coords based on the first fragment in the paragraph that we're replacing
MarginInfo info = new MarginInfo(
fragmentRect.LLX - page.Rect.LLX,
fragmentRect.LLY - page.Rect.LLY,
page.Rect.URX - fragmentRect.URX,
page.Rect.URY - fragmentRect.URY);
htmlFragment.Margin = info;
// blank out the entire paragraph
foreach (TextFragment fragment in markupParagraph.Fragments)
{
fragment.Text = string.Empty;
}
page.Paragraphs.Add(htmlFragment);
return;
}
Unfortunately, the positioning of my new HtmlFragment is not working properly.
I don’t understand why, but the HtmlFragment positioning is based on Margins, whereas the MarkupParagraph is based on absolute position.
I also tried incorporating page.PageInfo.Margin into the margin calculations, but that was incorrect:
MarginInfo info = new MarginInfo(
fragmentRect.LLX - page.Rect.LLX - page.PageInfo.Margin.Left,
fragmentRect.LLY - page.Rect.LLY - page.PageInfo.Margin.Top,
page.Rect.URX - fragmentRect.URX - page.PageInfo.Margin.Right,
page.Rect.URY - fragmentRect.URY - page.PageInfo.Margin.Bottom);
How can I add a new HtmlFragment at the same coordinates as an existing MarkupParagraph?
Thanks,
Mike