C # 3.0 Save itextsharp pdf to database using MemoryStream

I am trying to save a ddfse pdf file created by itextsharp. But so far I have not been successful.

I am using Linq for sql.

Here is 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 does not produce errors, but does not save anything in the database. The DB field is a type of image field. I also use this code to render pdf on the fly (I disabled byte [] pdfDone ... and returned a MemoryStream).

I don’t know what could be wrong ... And debugging, I could also see that the byte [] pdfDone has a value (something like 3487), but nothing is stored in the database.

Thanks in advance!

+3
source share
1 answer
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;
}
+5
source

Source: https://habr.com/ru/post/1716801/


All Articles