Hi , I have one example of some older pdf form , and when I try to replace word with other it delete some parts of document and mess with other.
This is the code for replacement and the file is attached:
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Application_Form_ Identity_certificate.pdf");
PdfBrush redact = PdfBrushes.Black;
PdfBrush brush = new PdfSolidBrush(Color.Black);
PdfTextFindOptions findOptions = new PdfTextFindOptions();
findOptions.Parameter = TextFindParameter.WholeWord | TextFindParameter.IgnoreCase;
List<string> dictionary =new List<string>();
dictionary.Add("E-mail id");
int i = 0;
PdfFont font1;
//Font font1;
foreach (string word in dictionary)
{
foreach (PdfPageBase page in doc.Pages)
{
i++;
// PdfTextFind[] result = page.FindText(word, true,true).Finds;
PdfTextFinder finder = new PdfTextFinder(page);
finder.Options = findOptions;
List<PdfTextFragment> result = finder.Find(word);
PdfTextReplacer replacer = new PdfTextReplacer(page);
replacer.Options.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth;
if (result.Count() > 0)
{
foreach (PdfTextFragment findWord in result)
{
PdfFamily myFamily;
if (!Enum.TryParse(findWord.TextStates[0].FontFamily, out myFamily)) myFamily = PdfFamily.Helvetica;
font1 = new PdfFont(myFamily, findWord.TextStates[0].FontSize);
PdfStringFormat format = new PdfStringFormat();
SizeF sizeOne = font1.MeasureString("~", format);
int count = (int)(findWord.Bounds[0].Width / sizeOne.Width);
if (count == 0) count = 1;
string replaseStr = String.Concat(Enumerable.Repeat("~", count));
SizeF sizereplace = font1.MeasureString(replaseStr, format);
while ((findWord.Bounds[0].Width - sizeOne.Width) > sizereplace.Width)
{
replaseStr = replaseStr + "~";
sizereplace = font1.MeasureString(replaseStr, format);
}
try
{
replacer.ReplaceText(findWord.Text, replaseStr);
}
catch (Exception ex)
{
}
}
}
}
}
doc.SaveToFile(@"C:\Application_Form_ Identity_certificate1.pdf");