2

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?

Inês Borges
  • 103
  • 1
  • 11
  • You target a `PdfWriter` at your path, no reader. Thus, the existing file is ignored and overwritten. Instead target a `PdfReader` at your existing file and a `PdfWriter` at a different output file. – mkl Jul 21 '21 at 15:45
  • @mkl And how do I add the cat.pdf file and the text.txt file to one pdf? That one pdf is a PdfWriter right? – Inês Borges Jul 21 '21 at 15:55
  • Does this answer your question? [ITextSharp insert text to an existing pdf](https://stackoverflow.com/questions/3992617/itextsharp-insert-text-to-an-existing-pdf) – Boris Sokolov Jul 21 '21 at 16:18
  • @Boris Solokov The problem is that I am using iText7 not ITextSharp and I don't have the method GetInstance for example. Could you please provide me with an answer with code that uses iText7? – Inês Borges Jul 21 '21 at 17:31

1 Answers1

2

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(); 
mkl
  • 90,588
  • 15
  • 125
  • 265
  • This is the correct answer, in case you want the same file to be Read from and Written to, you may do so using a FileStream with ReadWrite: `using FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);` and then pass the stream to the reader and writer – BotMaster3000 Jan 10 '23 at 09:53