iTextSharp - 如何将文档转换为byte[]

8

我需要将在内存中创建的PDF附加到电子邮件中。附件可以采用流的形式。因此,我认为我需要将iTextSharp Document对象转换为流。我该怎么做呢?

我尝试将Document对象序列化到流中,但它没有“标记为可序列化”。

2个回答

24

这里有一种方法,使用一个新的样本A4文档,并在其中添加“hello world”。

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

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接