Proper way to convert HTML to PDF

2019-04-11 16:19发布

I want to convert HTML page to PDF. There are several options, but they have some problems.

  • Print HTML page in IE through PDFCreator (too cumbersome)
  • Use wkhtmltopdf (low quality)
  • Use PhantomJS (low quality)

Maybe I can use a complex solution? To print with PhantomJS through PDFCreator, or improve quality of wkhtmltopdf, or maybe something else?

1条回答
戒情不戒烟
2楼-- · 2019-04-11 16:58

Maybe you can try with Amyuni WebkitPDF. It's not open source, but it's free for commercial use, and it can be used from C#.

Sample code for C# from the documentation:

static private void SaveToFile(string url, string file)
{        
    // Store the WebkitPDFContext returned value in an IntPtr
    IntPtr context = IntPtr.Zero;
    // Open the URL. The WebkitPDFContext returned value will be stored in
    // the passed in IntPtr
    int ret = WKPDFOpenURL(url, out context, 0, false);
    if (ret == 0)
    {
        // if ret is 0, then we succeeded in opening the URL.
        // Save the result as PDF to a file. Use the obtained context value
        ret = WKPDFSaveToFile(file, context);
    }
    if (ret != 0)
        Debug.WriteLine("Failed to run SaveToFile on '" + url + "' to generate file '" + file + "'");
    // Make sure to close the WebkitPDFContext because otherwise the
    // internal PDFCreator as well as other objects will not be released
    WKPDFCloseContext(context);
}

Usual disclaimer applies.

查看更多
登录 后发表回答