Search code examples
c#pdfitextmemorystream

iText 7 and C# writing a PDF file from MemoryStream?


I have a PDF document (using iText 7/C# 4.01) that I am creating in a MemoryStream and at the end, I want to write it out to a file. Part of the reason I am creating it in a memory stream is that I want to stamp a header table and footers on it at the end and was hoping to avoid writing it to a file then reading the file back in, stamping, then writing out a new file (as the examples I keep finding on iText website seem to do). However, I seem to be having some sort of chicken/egg scenario in the below code. It seems that you have to Close() the document in order for iText to fully form it. However, if I Close() it, then I get an ObjectDisposedException when trying to write it (simplified example below). I have to be missing something simple here, right? Thanks

    MemoryStream baos = new MemoryStream();
    PdfWriter writer = new PdfWriter(baos);
    PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
    //writer.SetCloseStream(true);
    //pdfDocument.SetCloseWriter(true);
    //pdfDocument.SetCloseReader(true);
    //pdfDocument.SetFlushUnusedObjects(true);
    Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
    d.Add(new Paragraph("Hello world!"));
    //d.Close();

    FileStream file = new FileStream("C:\test.pdf", 
    FileMode.Create, FileAccess.Write);
    baos. WriteTo(file);
    file.Close();
    //baos.Close();
    //d.Close();

Solution

  • Try this

    I dont have IDE for test, but i think this work

    MemoryStream baos = new MemoryStream();
    PdfWriter writer = new PdfWriter(baos);
    PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
    
    Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
    d.Add(new Paragraph("Hello world!"));
    
    d.Close();
    
    byte[] byte1 = baos.ToArray();
    File(byte1, "application/pdf", "C:\\iTextTester\\test.pdf");