locked
IText 7 replace text in PDF RRS feed

  • Question

  • 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.

    https://itextpdf.com/en/resources/examples/itext-7/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();


    • Edited by sdnd2000 Tuesday, June 2, 2020 1:04 AM
    Tuesday, June 2, 2020 1:03 AM

Answers

  • Instead of data.ToString(), try Encoding.UTF8.GetString(data).

    • Marked as answer by sdnd2000 Tuesday, June 2, 2020 8:26 PM
    Tuesday, June 2, 2020 3:19 AM

All replies