问题
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:
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.
回答2:
You can properly convert HTML to PDF using GroupDocs.Conversion for .NET API. Have a look at the code:
// Setup Conversion configuration and Initailize ConversionHandler
ConversionConfig config = new ConversionConfig();
config.StoragePath = "source file storage path";
// Initailize ConversionHandler
ConversionHandler conversionHandler = new ConversionHandler(config);
// Convert and save converted document
var convertedDocumentPath = conversionHandler.Convert("sample.html", new PdfSaveOptions{});
convertedDocumentPath.Save("result-" + Path.GetFileNameWithoutExtension("sample.html") + ".pdf");
Disclosure: I work as Developer Evangelist at GroupDocs.
来源:https://stackoverflow.com/questions/12837560/proper-way-to-convert-html-to-pdf