PDF or Other “report viewer” options for Asp.net C#

后端 未结 2 1417
慢半拍i
慢半拍i 2020-12-20 04:10

I\'m in a bind with my current project. It\'s a payroll application and I\'m developing in ASP.net webforms with C#. My boss said that the ideal function of this site is to

相关标签:
2条回答
  • 2020-12-20 04:55

    A HTML to PDF converter that I've recently discovered is WKHTMLtoPDF

    It's open source and uses WebKit to convert HTML to PDF so it's pretty standards compliant.

    An example of how you might use it is

    using (var pdfStream = new FileStream(dlg.FileName, FileMode.OpenOrCreate))
    {
        // pass in the HTML you want to appear in the PDF, and the file stream it writes to
        Printer.GeneratePdf(htmlStream, pdfStream);
    }
    

    where GeneratePdf is defined as

        public static void GeneratePdf(Stream html, Stream pdf) 
        {
            Process process;
            StreamWriter stdin;
            var psi = new ProcessStartInfo();
    
            psi.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Lib", "wkhtmltopdf.exe");
            psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);
    
            // run the conversion utility
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
    
            psi.Arguments = "-q -n --disable-smart-shrinking - -";
            process = Process.Start(psi);
    
            try
            {
                stdin = process.StandardInput;
                stdin.AutoFlush = true;
                //stdin.Write(html.ReadToEnd());
                stdin.Write(new StreamReader(html).ReadToEnd());
                stdin.Dispose();
    
                process.StandardOutput.BaseStream.CopyTo(pdf);
    
                process.StandardOutput.Close();
                pdf.Position = 0;
    
                process.WaitForExit(10000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                process.Dispose();
            }
        }
    

    In your case, instead of writing it to a file stream, you'd write it to the HTTP output stream as a PDF.

    Please note however, that this example is more suitable to writing PDF files to disk, rather than the output stream so you'd need to do it differently slightly for it to work for you.

    0 讨论(0)
  • 2020-12-20 05:00

    I also agree that html -> pdf is the best option nowadays if you want to render complex report and stay productive.

    I have implemented a wrapper for html -> pdf conversion called jsreport.

    If you are using asp.net mvc, you can check out my post Rendering pdf from Asp.Net MVC views or more generic post Pdf reports in c#.

    Disclaimer: I am the author of jsreport

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