Search code examples
pythonhtmlwebkit

how to render html code to transparent background image with python


I have locally an .html file and I need to render it to no background image. what I do now:

import imgkit
imgkit.from_file('test.html', 'out.png')
replace_white_pixels_to_transparent("out.png") # my function that's doing what it name says :)

output before cleaning the white pixels looks like: output

And after replacing the white pixels with transperent: enter image description here

So I do get a no background image, and when upscaling the qulity and zoom in the webkit options the result is much better.

the problem is that even if the image quality is crazy high the white pixels cleaning process will leave some close to white pixels on the edges of the elements and it will delete necessary white pixels (eg. the inner of the shapes supposed to be white, or white backgroung image etc).

My question basically is how to render the html straight to no background image? instead of rendering the elements on white background and then remove it.


Solution

  • this works pretty nicely:

    import imgkit
    kitoptions = {
        "transparent": "",
    }
    
    imgkit.from_file('test.html', 'out.png', options=kitoptions)