IText 7 replace text in PDF

  • Thread starter Thread starter sdnd2000
  • Start date Start date
S

sdnd2000

Guest
Hi, I am trying to replace text in PDF through .net core console app, and I followed the tutorial from the official sample, however, I got blank page in PDF.

Replacing PDF objects

public readonly static String source = @"D:\\PDF\hello.pdf";
public readonly static String des = @"D:\\PDF\helloWorld.pdf";

static void Main(string[] args)
{
FileInfo file = new FileInfo(des);
file.Directory.Create();
ManipulatePdf(des);
}

public static void ManipulatePdf(String dest)
{

//PdfWriter writer = new PdfWriter(dest);
//PdfDocument pdf = new PdfDocument(writer);
//Document document = new Document(pdf);
//document.Add(new Paragraph("Hello World!"));
//document.Close();

PdfDocument pdfDoc = new PdfDocument(new PdfReader(source), new PdfWriter(dest));
PdfPage page = pdfDoc.GetFirstPage();
PdfDictionary dict = page.GetPdfObject();
PdfObject obj = dict.Get(PdfName.Contents);
if (obj != null && obj.IsStream())
{
PdfStream stream = (PdfStream)obj;
byte[] data = stream.GetBytes();
String replacedData = data.ToString().Replace("Hello World", "HELLO WORLD");
stream.SetData(Encoding.UTF8.GetBytes(replacedData));
}
pdfDoc.Close();

Continue reading...
 
Back
Top