I am working to replace the specific word inside pdf document using iTextSharp and C#.net, while I am debugging getting the proper value but the outputted pdf getting zero bytes(empty),its not filling with the content. Here is my code:
ReplacePDFText("Mumbai",StringComparison.CurrentCultureIgnoreCase,Application.StartupPath + "\\test.pdf","D:\\test_words_replaced.pdf");
public void ReplacePDFText(string strSearch, StringComparison scCase, string strSource, string strDest)
{
PdfStamper psStamp = null;
PdfContentByte pcbContent = null;
if (File.Exists(strSource))
{
PdfReader pdfFileReader = new PdfReader(strSource);
psStamp = new PdfStamper(pdfFileReader, new FileStream(strDest, FileMode.Create));
pbProgress.Value = 0;
pbProgress.Maximum = pdfFileReader.NumberOfPages;
for (int intCurrPage = 1; intCurrPage <= pdfFileReader.NumberOfPages; intCurrPage++)
{
LocTextExtractionStrategy lteStrategy = new LocTextExtractionStrategy();
pcbContent = psStamp.GetUnderContent(intCurrPage);
lteStrategy.UndercontentCharacterSpacing = pcbContent.CharacterSpacing;
lteStrategy.UndercontentHorizontalScaling = pcbContent.HorizontalScaling;
string currentText = PdfTextExtractor.GetTextFromPage(pdfFileReader, intCurrPage, lteStrategy);
List<itextsharp.text.rectangle> lstMatches = lteStrategy.GetTextLocations(strSearch, scCase);
PdfLayer pdLayer = default(PdfLayer);
pdLayer = new PdfLayer("Overrite", psStamp.Writer);
pcbContent.SetColorFill(BaseColor.BLACK);
foreach (iTextSharp.text.Rectangle rctRect in lstMatches)
{
pcbContent.Rectangle(rctRect.Left, rctRect.Bottom, rctRect.Width, rctRect.Height);
pcbContent.Fill();
pcbContent.BeginLayer(pdLayer);
pcbContent.SetColorFill(BaseColor.BLACK);
pcbContent.Fill();
PdfGState pgState = default(PdfGState);
pgState = new PdfGState();
pcbContent.SetGState(pgState);
pcbContent.SetColorFill(BaseColor.WHITE);
pcbContent.BeginText();
pcbContent.SetTextMatrix(rctRect.Left, rctRect.Bottom);
pcbContent.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
pcbContent.ShowText("AMAZING!!!!");
pcbContent.EndText();
pcbContent.EndLayer();
}
pbProgress.Value++;
pdfFileReader.Close();
}
}
}</itextsharp.text.rectangle>