0

I have a pdf document (created by iTextSharp - free version 4.1.6) and I want to add text / table at the top of this pdf. I have tried to create two memory streams from iTextSharp Documents and combine them to one, see my code below. But the new PDF file cannot be opened. Any ideas what I am doing wrong? Any other ideas to add text / table at the top of an existing PDF? Thanks in advance!

public void CreateTestPDF(string _pathOfOriginalPDF, string _pathOfModifiedPDF)
{
    string oldFile = _pathOfOriginalPDF;
    string newFile = pathOfModifiedPDF;
 
    byte[] bytesHeader;
    byte[] bytesBody;
    byte[] bytesCombined;
 
    using (MemoryStream ms = new MemoryStream())
    {
        Document doc = new Document();
        doc.Open();
        doc.Add(new Paragraph("This is my header paragraph"));
        if (doc.IsOpen())
        {
            doc.Close();
        }
 
        bytesHeader = ms.ToArray();
    }
 
    using (MemoryStream ms = new MemoryStream())
    {
        Document doc = new Document();
        //doc.Open();
        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(oldFile, FileMode.Create));
        if (doc.IsOpen())
        {
            doc.Close();
        }
 
        bytesBody = ms.ToArray();
    }
 
    IEnumerable<byte> iCombined = bytesHeader.Concat(bytesBody);
    bytesCombined = iCombined.ToArray();
 
    string testFile = _pathOfModifiedPDF;

    using (FileStream fs = File.Create(testFile))
    {
        fs.Write(bytesBody, 0, (int)bytesBody.Length);
    }
}
kHLVT
  • 93
  • 6
Alexander
  • 23
  • 3
  • Some conceptual issues: in your first `using` block you don't put anything into the `MemoryStream`. In your second `using` block you neither open the document nor add anything to it. And @KJ already explained that what you do at the end cannot work either – mkl Sep 04 '21 at 18:02
  • iTextsharp 4 is around 10 years old, potentially has a lot of functional and security issues and no longer maintained. I recommend updating to iText 7 – Alexey Subach Sep 20 '21 at 22:34

0 Answers0