iTextSharp (version 4.1.6) - add text/table at top of existing PDF

314 views Asked by At

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);
    }
}
0

There are 0 answers