Here you go! Hope this helps.
Code:
class Program
{
static void Main(string[] args)
{
string originalPdf = @"C:\origPdf.pdf";
CreatePdf(originalPdf);
using (var doc = PdfReader.Open(originalPdf, PdfDocumentOpenMode.Modify))
{
var page = doc.Pages[0];
var contents = ContentReader.ReadContent(page);
ReplaceText(contents, "Hello", "Hola");
page.Contents.ReplaceContent(contents);
doc.Pages.Remove(page);
doc.AddPage().Contents.ReplaceContent(contents);
doc.Save(originalPdf);
}
Process.Start(originalPdf);
}
// Code from http://www.pdfsharp.net/wiki/HelloWorld-sample.ashx
public static void CreatePdf(string filename)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic, new XPdfFontOptions(PdfFontEncoding.WinAnsi));
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document...
document.Save(filename);
// ...and start a viewer.
}
// Please refer to the pdf tech specs on what all entails in the content stream
// https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf
public static void ReplaceText(CSequence contents, string searchText, string replaceText)
{
// Iterate thru each content items. Each item may or may not contain the entire
// word if there are different stylings (ex: bold parts of the word) applied to a word.
// So you may have to replace a character at a time.
for (int i = 0; i < contents.Count; i++)
{
if (contents[i] is COperator)
{
var cOp = contents[i] as COperator;
for (int j = 0; j < cOp.Operands.Count; j++)
{
if (cOp.OpCode.Name == OpCodeName.Tj.ToString() ||
cOp.OpCode.Name == OpCodeName.TJ.ToString())
{
if (cOp.Operands[j] is CString)
{
var cString = cOp.Operands[j] as CString;
if (cString.Value.Contains(searchText))
{
cString.Value = cString.Value.Replace(searchText, replaceText);
}
}
}
}
}
}
}
}
Best,
Reas