Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to convert HTML to PDF

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?

like image 997
ChruS Avatar asked Oct 11 '12 10:10

ChruS


People also ask

Why are my PDF files showing as chrome HTML?

Sometimes even when setting Adobe Acrobat DC as the Default, downloaded PDFs will open in Chrome instead. This is because Chrome is set to use it's integrated PDF viewer when files are downloaded by default. You will need to turn this off to make it go away.

Does Adobe convert HTML PDF?

Whether you use a Mac or Windows computer, the Adobe Acrobat desktop app, or the Acrobat extension for your web browser, converting an HTML document to PDF is easy. Customize the Conversion Settings to change page size, orientation, or scaling.


2 Answers

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.

like image 61
yms Avatar answered Oct 16 '22 02:10

yms


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.

like image 29
Atir Tahir Avatar answered Oct 16 '22 02:10

Atir Tahir