Search code examples
c#itext7

How to add text to an existing pdf without overwriting the content with iText7 and C#?


I have this piece of code that was supposed to insert a text after an image in a pdf.

        // Read the data from input file
        string reader = "C:\\InesProjetos\\PrintTextWithImage\\PrintTextWithImage\\cat.pdf";
        string dest = "C:\\demo.pdf";
        string text = "C:\\InesProjetos\\PrintTextWithImage\\PrintTextWithImage\\text.txt";
        StreamReader rdr = new StreamReader(text);
        // Must have write permissions
        //to the path folder
        PdfWriter writer = new PdfWriter(dest);
        PdfReader readerFile = new PdfReader(reader);
        PdfDocument pdf = new PdfDocument(writer); 
        Document document = new Document(pdf);
        document.Add(new Paragraph(rdr.ReadToEnd()));
        document.Close();     

How do insert the text in text.txt file in cat.pdf file without overwriting the image that is in cat.pdf?

UPDATE

What to do with the readerFile object? Should I insert cat.pdf into demo.pdf and then add the text? And if so how?


Solution

  • Whenever you want to add something to an existing pdf, you have to not only write but also read, i.e. you need both a PdfWriter and a PdfReader for the PdfDocument:

    PdfReader reader = new PdfReader(source);
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdf = new PdfDocument(reader, writer);
    

    If you furthermore don't want existing content to be covered by new content, you have to tell the objects so, e.g. if you use a Document to add new content:

    Document document = new Document(pdf);
    document.Add(new AreaBreak(AreaBreakType.LAST_PAGE));
    document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
    document.Add(new Paragraph(rdr.ReadToEnd()));
    document.Close();