ChruS
ChruS

Reputation: 3747

Proper way to convert HTML to PDF

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

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

Upvotes: 7

Views: 6941

Answers (5)

Victor Singha
Victor Singha

Reputation: 1

// npm i jspdf
// npm i html2canvas

SavePDF(fileName: any) {
  let section = (document.querySelector('#mainContainer') as HTMLElement);
  html2canvas(section, {
    scale: 2, // Canvas Quality
  }).then((canvas: any) => {
    var link = document.createElement('a');
    link.href = canvas.toDataURL();
    link.download = fileName;
    document.body.appendChild(link);
    // link.click(); // To Download Image
    // open()?.document.write('<img src="'+canvas.toDataURL()+'"/>');
    var pdf = new jsPDF("p", "pt", "a4", true); // true and false for compress
    const imgProps = pdf.getImageProperties(canvas.toDataURL());
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
    pdf.addImage(canvas.toDataURL(), 'PNG', 0, 0, pdfWidth, pdfHeight, 'FAST'); // NONE, FAST, MEDIUM and SLOW,
    window.open(URL.createObjectURL(pdf.output("blob")))
    pdf.save('file_name' + '.pdf');
  });
}
<div id="mainContainer">
  <p>Hello World</p>
</div>

Upvotes: -1

Mr. Doge
Mr. Doge

Reputation: 886

google chrome Save as PDF
the output looks exactly the same (as rendered by chrome)

here, I use Puppeteer to automate the process: singlefile or in Folder
https://github.com/FuPeiJiang/puppeteer-pdf

Upvotes: 1

Anatoly Shipov
Anatoly Shipov

Reputation: 504

patched wkhtmltopdf (a very good WebKit-based command line tool, fast) with --print-media-type --no-stop-slow-scripts keys

chromium --headless --no-zygote --single-process ... --print-to-pdf= ... (slower, Portrait orientation only)

chromium headless via DevTools Protocol (slow, only a few programming languages do have bindings to)

wrapper around Blink Engine (e.g., Qt5 https://code.qt.io/cgit/qt/qtwebengine.git/tree/examples/webenginewidgets/html2pdf?h=5.15)

If you believe in containers, - https://github.com/thecodingmachine/gotenberg (internally - chromium headless via DevTools Protocol)

Upvotes: 2

Atir Tahir
Atir Tahir

Reputation: 11

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.

Upvotes: 2

yms
yms

Reputation: 10418

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.

Upvotes: 2

Related Questions