Search code examples
pythonhtml-to-pdf

Converting HTML Files to PNG Images


I'm parsing a site and retrieving a div. For the past few days I have been trying to find a library that can turn this div into a .png image. Is there any way I can do this without using a REST API? Any python libraries that can export to png? I have tried HTML2PNG(white background), imgkit(can't render gradients). I'd appreciate any advice, suggestions and information. Thank you :) I can also export to PDF and convert it to PNG from there, if I can get the transparency.

Things I need to do:

  • Load External CSS.
  • Export only the div to PDF/PNG with transparent background.

Solution

  • You can use weasyprint

    from weasyprint import HTML, CSS
    
    div = 'your div as string'
    css_string = 'your css as string'
    
    html = HTML(string=div)
    css = CSS(string=css_string)
    html.write_png('output.png', stylesheets=[css])
    

    EDIT:
    As of current stable version 59.0b1 weasyprint no longer supports the function write_png (See here)