将HTML转换为PDF的正确方法 [英] Proper way to convert HTML to PDF
本文介绍了将HTML转换为PDF的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将HTML页面转换为PDF。有几种选择,但他们有一些问题。
- 通过
PDFCreator在IE中打印HTML页面(太麻烦)
- 使用
wkhtmltopdf
(低品质) - 使用
PhantomJS
(低质量)
也许我可以使用复杂的解决方案?使用 PhantomJS
至 PDFCreator
进行打印,或者改善 wkhtmltopdf
,或者别的什么东西? 可能你可以试试 Amyuni WebkitPDF 。它不是开源的,但它可以免费用于商业用途,它可以在C#中使用。
示例代码来自文档:
static private void SaveToFile(字符串url,字符串文件)
{
//将WebkitPDFContext的返回值存储在IntPtr
中IntPtr context = IntPtr.Zero;
//打开网址。 WebkitPDFContext的返回值将存储在
中//传入IntPtr
int ret = WKPDFOpenURL(url,out context,0,false);
if(ret == 0)
{
//如果ret为0,那么我们成功地打开了URL。
//将结果保存为PDF文件。使用获得的上下文值
ret = WKPDFSaveToFile(file,context);
if(ret!= 0)
Debug.WriteLine(无法在''+ url +''上运行SaveToFile来生成文件''+ file +'');
//确保关闭WebkitPDFContext,否则
//内部PDFCreator以及其他对象不会被释放
WKPDFCloseContext(context);
常用免责声明。
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?
解决方案
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.
这篇关于将HTML转换为PDF的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文