I’m writing a piece of code that will go in and replace a specific set of texts with dynamic text being loaded from elsewhere. Everything is working correctly except that if the text is more than two lines long, it overlaps with the content above it. I feel like the issue is that the text paragraph is being rendered up the page rather than down, such that the last line of the new text is at the same position of the old text (and at the same time, the new text not moving the other content to make room).
This is the code I have written so far:
var txtAbsorber = new TextFragmentAbsorber(@"[([A-Z|a-z|/|~].*?)]");
txtAbsorber.TextSearchOptions = new TextSearchOptions(true);
txtAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation;PDFDocument.Pages.Accept(txtAbsorber); foreach (TextFragment fragment in txtAbsorber.TextFragments) { var processedToken = ProcessPDFToken(fragment.Text, data); TextFragment newTextFrag = new TextFragment(processedToken.Value); if (processedToken.FontSize > 0) newTextFrag.TextState.FontSize = processedToken.FontSize; fragment.Text = ""; TextParagraph par = new TextParagraph(); par.Position = fragment.Position; par.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords; par.HorizontalAlignment = processedToken.Position; par.AppendLine(newTextFrag); TextBuilder textBuilder = new TextBuilder(fragment.Page); textBuilder.AppendParagraph(par); }
Where the ProcessPDFToken function does the work to look at which token is being currently loaded and then replacing it with the correct value.
I’ve tried to use ‘VerticalAlignment’ on the TextParagraph object, but all values except for ‘None’ and ‘Bottom’ seem to end up rendering nothing. I’ve also tried (my first attempt) to just do replace using text paragraph using the exact same code except without the new TextFragment object, but that gives me an “Object reference not set to an instance of an object.” exception down the line on the AppendParagraph() call.
The original PDF that’s being ingested by my code: Equipping-Families Before Code.pdf (235.6 KB)
The PDF after my code has ran: Equipping-Families After Code.pdf (232.3 KB)