从iTextSharp生成Base64

时间:2017-04-28 13:07:45

标签: javascript c# pdf base64 itext

我的项目中有以下方法。

        [Route("GerarPdf")]
        [HttpGet()]
        public object GerarPdf()
        {

            var doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            var mem = new MemoryStream();

            PdfWriter wri = PdfWriter.GetInstance(doc, mem);

            doc.Open();//Open Document to write
            Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
            Phrase pharse = new Phrase("This is my second line using Pharse.");
            Chunk chunk = new Chunk(" This is my third line using Chunk.");

            doc.Add(paragraph);
            doc.Add(pharse);
            doc.Add(chunk);

            var pdf = mem.ToArray();

            return Convert.ToBase64String(pdf);
        }

此代码的目标是生成可通过以下JavaScript代码下载的PDF文件

     var dataURI = "data:application/pdf;base64," +result;
     window.open(dataURI,'_blank'); 

但新打开的页面在加载PDF时始终返回错误。方法返回给结果变量的base64代码是:

JVBERi0xLjQKJeLjz9MK

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

问题是在转换为bytearray的那一刻文档没有关闭。我添加了doc.Close(); PDF已成功生成。

        [Route("GerarPdf")]
        [HttpGet()]
        public object GerarPdf()
        {

            var doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            var mem = new MemoryStream();

            PdfWriter wri = PdfWriter.GetInstance(doc, mem);

            doc.Open();//Open Document to write
            Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
            Phrase pharse = new Phrase("This is my second line using Pharse.");
            Chunk chunk = new Chunk(" This is my third line using Chunk.");

            doc.Add(paragraph);
            doc.Add(pharse);
            doc.Add(chunk);

            doc.Close();

            var pdf = mem.ToArray();

            return Convert.ToBase64String(pdf);
        }

答案 1 :(得分:1)

要让MemoryStreamDocument自动关闭+处置,请将它们放入using()这样的块中:

[Route("GerarPdf")]
[HttpGet()]
public object GerarPdf()
{
    byte[] pdf = new byte[] { };

    using (var mem = new MemoryStream())
    {
        using (var doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35))
        {
            PdfWriter wri = PdfWriter.GetInstance(doc, mem);

            doc.Open(); //Open Document to write

            Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
            Phrase pharse = new Phrase("This is my second line using Pharse.");
            Chunk chunk = new Chunk(" This is my third line using Chunk.");

            doc.Add(paragraph);
            doc.Add(pharse);
            doc.Add(chunk);
        } // doc goes out of scope and gets closed + disposed

        pdf = mem.ToArray();
    } // mem goes out of scope and gets disposed

    return Convert.ToBase64String(pdf);
}