(using 'imgkit' on Ubuntu server) wkhtmltopdf: could not connect to any X display

前端 未结 2 505
不知归路
不知归路 2021-01-28 17:09

I have a python script running on a remote Ubuntu server. At some point in my code, I create an HTML file which I then convert to a png. I therefore elected to use imgkit, which

2条回答
  •  情歌与酒
    2021-01-28 17:51

    I did not find the solution to my question: then add option: {"xvfb": ""}

    However I was able to get my code to work. There are two solutions.

    1) Use wkhtmltopdf:

    import os
    
    os.system("xvfb-run -a wkhtmltopdf %s %s"%('filenameIn.html','filenaneOut.png'))
    

    That produces a PDF file, without the need to setup a virtual display.

    2) Setup a virtual display using pyvirtualdisplay:

    import imgkit
    from pyvirtualdisplay import Display
    
    display = Display(visible=0, size=(600,600))
    display.start()
    imgkit.from_file("filenameIn.html", "filenameOut.png")
    display.stop()
    

    Actually, 2) was answered before and I missed it while searching StackOverflow: "Could not connect to display" on EC2 Server

    Note: you can combine 1) and 2): use wkhtmltopdf to convert to png directly, but with a virtual display (otherwise the png will not show the resulting image, at least it was the case for me).

    I thought it could help. :) Berti

    ------------------------------------EDIT-----------------------------------

    I had a mistake (now fixed) in my solution: for 2): it should have been "filenameOut.png" instead of "filenameOut.html

提交回复
热议问题