c# How to return a byte array from pdf using iTextsharp

余生颓废 提交于 2019-12-01 21:33:25

This is a basic example:

private byte[] CreatePdf()
{
    Document document = new Document();
    using (MemoryStream ms = new MemoryStream())
    {
        PdfWriter.GetInstance(document, ms);
        document.Open();
        document.Add(new Paragraph("Hello World"));
        document.Close();
        return ms.ToArray();
    }
}

It is similar to a previous answer, but in that answer in isn't made clear that you need to Close() the document instance before you get the bytes from the MemoryStream. In your code snippet, you have:

byte[] bytes = null;
document.Close();

Based on the previous answer, you might change this into:

byte[] bytes = ms.ToArray();
document.Close();

That would be wrong, because the bytes array wouldn't contain the full PDF. Upon document.Close(), a lot of essential data is written to the output stream (the info dictionary, the root dictionary, the cross-reference table).

Update:

In C#, it is custom to use using as indicated in the comments:

private byte[] CreatePdf()
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (Document document = new Document())
        {
            PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new Paragraph("Hello World"));
        }
        return ms.ToArray();
    }
}

My argument that the document needs to be closed to get a complete PDF remains valid: the document instance is closed implicitly by the } right before return ms.ToArray().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!