How to write PDF into MemoryStream with iText and C#?

Example

var stream = new MemoryStream();

var writer = new PdfWriter(stream);
//  This is crucial step.
writer.SetCloseStream(false);

var pdf = new PdfDocument(writer);
var document = new Document(pdf);

//  Create font.
var font = PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN);

//  Add paragraph.
document.Add(new Paragraph("iText is:").SetFont(font));
//  Create list.
List list = new List()
    .SetSymbolIndent(12)
    .SetListSymbol("u2022")
    .SetFont(font);
//  Add ListItem objects.
list.Add(new ListItem("Never gonna give you up"))
    .Add(new ListItem("Never gonna let you down"))
    .Add(new ListItem("Never gonna run around and desert you"))
    .Add(new ListItem("Never gonna make you cry"))
    .Add(new ListItem("Never gonna say goodbye"))
    .Add(new ListItem("Never gonna tell a lie and hurt you"));

//  Add the list.
document.Add(list);
document.Close();

Now PDF is contained in the memory stream.

Writing to file

using (var fileStream = File.Create(fileName))
{
    stream.Seek(0, SeekOrigin.Begin);
    stream.CopyTo(fileStream);
}

Read more