- Code: Select all
public void ReplaceText(PdfDocument doc, string posField, string newText, string nameFile)
{
try
{
doc.LoadFromFile(formCOPTemplatePath);
PdfBrush brush = new PdfSolidBrush(Color.Black);
for (int i = 0; i < doc.Pages.Count; i++)
{
PdfPageBase page = doc.Pages[i];
PdfTextFindCollection collection = page.FindText(posField, TextFindParameter.IgnoreCase);
if (posField == "%name%")
{
foreach (PdfTextFind find in collection.Finds)
{
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Calibri (Body)", 10f, FontStyle.Regular));
RectangleF rec;
// Gets the bound of the found text in page
rec = find.Bounds;
page.Canvas.DrawRectangle(PdfBrushes.White, rec);
page.Canvas.DrawString(newText, font, brush, rec);
}
}
}
doc.SaveToFile(formCOPDownloadPath + nameFile);
}
I have noticed that only the line "page.Canvas.DrawRectangle(PdfBrushes.White, rec);" (which overlays the text with a white object) seems to be working, while the line "page.Canvas.DrawString(newText, font, brush, rec);" (which is intended to replace the text) does not appear to be working. This issue occurs in most of the PDF files I've tested.
I'm using Windows 11, Free Spire PDF 8.6.0, and ASP.NET Framework 4.8.
Can anyone provide suggestions or solutions to this issue, and explain why the line of code to replace the text is not working correctly? Thank you.