简体   繁体   中英

Unable to evaluate expression error while trying to display PDF using memorystream

I'm trying to generate PDF of my SharePoint page but keep getting an "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack." error. Am I going about doing this the correct way?

protected void btnDownload_Click(object sender, EventArgs e)
        {

            try
            {
                SPSite spBtnSite = new SPSite(SPContext.Current.Site.Url);
                SPWeb btnSPWeb = SPContext.Current.Web;
                string doclibURL = string.Empty;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (var pdfWriter = new PdfWriter(ms))
                    {
                        ConverterProperties properties = new ConverterProperties();
                        pdfWriter.SetCloseStream(false);
                        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

                        //For setting the PAGE SIZE
                        pdfDocument.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4);
                        Document document1 = new Document(pdfDocument, pdfDocument.GetDefaultPageSize(), false);
                        using (var document = HtmlConverter.ConvertToDocument(hidText.Text, pdfDocument, properties))
                        {

                        }
                        ms.Position = 0;
                        byte[] bytesInStream = ms.ToArray(); // simpler way of converting to array
                        ms.Close();

                        if (bytesInStream != null)
                        {
                            Page.Response.Clear();
                            Page.Response.ClearHeaders();
                            Page.Response.ClearContent();
                            Page.Response.ContentType = "application/pdf";
                            Page.Response.AddHeader("content-length", bytesInStream.Length.ToString());
                            Page.Response.BinaryWrite(bytesInStream);
                            Page.Response.End();
                        }
                    }

                }
            }
            catch (Exception ex_btnSubmit_Click)
            {
                Exceptions.SaveException(UserID, ex_btnSubmit_Click.Message, ex_btnSubmit_Click.StackTrace, (ex_btnSubmit_Click.InnerException != null) ? ex_btnSubmit_Click.InnerException.Message : "");
            }
        }

You got ThreadAbortException on Response.End() . According to this , you should use HttpContext.Current.ApplicationInstance.CompleteRequest instead of Response.End() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM