且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PDF或其它"报告观众QUOT;对于Asp.net C#的选项

更新时间:2023-02-15 19:48:07

一个HTML到PDF转换器,我最近发现是的 WKHTMLtoPDF

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

它是开源的,并且使用的WebKit为HTML转换为PDF因此它的pretty符合标准。

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);
}

其中, GeneratePdf 定义为

    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();
        }
    }

在你的情况,而不是将其写入文件流,你把它写到HTTP输出流为PDF。

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

请注意,这个例子是比较适合的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.