C# 3.0 Save itextsharp pdf to database using MemoryStream

只谈情不闲聊 提交于 2019-12-06 07:24:07

问题


I'm trying to save to databse a pdf file generated by itextsharp. But, I haven't been successfully so far.

I'm using Linq to sql.

Here's the code:

            MemoryStream ms = new MemoryStream();
            Document d = new Document(PageSize.A4, 60, 60, 40, 40);
            PdfWriter w = PdfWriter.GetInstance(d, ms);
            w.CloseStream = false;

            string txtTemplate = "";
            Encoding en = Encoding.GetEncoding("iso-8859-1");
            StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("~/Content/templates/CessaoDireitosDica.txt"), en);
            txtTemplate  = sr.ReadToEnd();
            sr.Close();
            string conselhos = "";

            Font font = new Font(Font.HELVETICA, 11, Font.NORMAL);
            font.SetColor(0xC6, 0xC6, 0xC6);

            Paragraph txtBody = new Paragraph(txtTemplate, font);

            txtBody .SetAlignment(ElementTags.ALIGN_JUSTIFIED);

            d.Open();
            d.Add(txtBody);
            d.Close();

            byte[] pdfDone = ms.ToArray();
            w.Flush();
            ms.Flush();
            ms.Close();

            return pdfDone;

It throws no error, but it doesn't save nothing in DB. The DB field is an "image" field type. I also use this code to render a pdf on the fly (I cut off the byte[] pdfDone... and return the MemoryStream).

I don't know what can be wrong... And debugging, I could also see that byte[] pdfDone has a value (something like 3487), but nothing is saved to DB.

Thanks in advance!


回答1:


function byte[] CreatePdf(){
            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                Document pDoc = new Document(PageSize.A4, 0, 0, 0, 0);
                PdfWriter writer = PdfWriter.GetInstance(pDoc, ms);
                pDoc.Open();

                //here you can create your own pdf.

                pDoc.Close();
                result = ms.GetBuffer();
            }

            return result;
}


来源:https://stackoverflow.com/questions/1374184/c-sharp-3-0-save-itextsharp-pdf-to-database-using-memorystream

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