ASP.NET MVC: render view to generate PDF: use iTextSharp or better solution?

后端 未结 3 1326
野性不改
野性不改 2021-02-04 21:59

I display receipt in both HTML and printer-friendly version. HTML version does jQuery tabs, etc, while printer-friendly has zero scripts and external dependencies, no master lay

相关标签:
3条回答
  • 2021-02-04 22:12
     public class Pdf : IPdf
        {
            public FileStreamResult Make(string s)
            {
                using (var ms = new MemoryStream())
                {
                    using (var document = new Document())
                    {
                        PdfWriter.GetInstance(document, ms);
                        document.Open();
                        using (var str = new StringReader(s))
                        {
    
                            var htmlWorker = new HTMLWorker(document);
    
                            htmlWorker.Parse(str);
                        }
                        document.Close();
                    }
    
                    HttpContext.Current.Response.ContentType = "application/pdf";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
                    HttpContext.Current.Response.Buffer = true;
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                    HttpContext.Current.Response.OutputStream.Flush();
                    HttpContext.Current.Response.End();
    
                    return new FileStreamResult(HttpContext.Current.Response.OutputStream, "application/pdf");
                }
            }
        }
    
    0 讨论(0)
  • 2021-02-04 22:12

    Finally used wkhtmltopdf which works fine when I set encoding, I found out how to setup page breaks, and it processes my CSS very nice. On issue is that it can't correctly process stdin/out in Windows version (don't remember if it's in or out that doesn't work) - may be fixed in recent versions, but I'm ok with temp files.

    0 讨论(0)
  • 2021-02-04 22:27

    If you can have the HTML in memory then you can convert it to PDF. I've once did something similar using xhtmlrenderer. It is a JAVA framework that bundles iText and that is capable of converting an HTML stream into PDF. As it is written in JAVA I've used the ikvmc.exe to convert the jar file into a .NET assembly and use it directly from managed code.

    0 讨论(0)
提交回复
热议问题