iTextSharp - How to convert Document to byte[]

2019-01-26 12:23发布

问题:

I need to attach a pdf I created in memory to an email. Attachments can take a stream. So I believe I need to convert a iTextSharp Document object to stream. How can I do that? I tried serializing the Document object to a stream but it is not "marked as serializable".

回答1:

Look at iText.pdf.PdfWriter. There are methods that take a stream.

Here's a sample for streaming in ASP.NET- link text



回答2:

Here is a code sample

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    //creating a sample Document
    iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f);
    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
    doc.Open();
    doc.Add(new iTextSharp.text.Chunk("hello world"));
    doc.Close();
    byte[] result = ms.ToArray();
}