添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

i tried install wkhtmltopdf but it failed https://github.com/wkhtmltopdf/wkhtmltopdf/blob/master/INSTALL.md#linux how I can do

Can you use one of the precompiled binaries? Try the Ubuntu trusty one... http://wkhtmltopdf.org/downloads.html

which code i must use with the bash for download or clone and execute the Linux (Ubuntu Trusty) 32-bit   64-bit built on Ubuntu 14.04.1

Hi, i'm trying to get wkhtmltopdf to work through xvfb-run, but getting the error below. Can anyone advise?

wkhtmltopdf.sh

xvfb-run -a -s "-screen 0 1920x1080x16" /home/guidingstarcc/bin/usr/local/bin/wkhtmltopdf "$@"

if i try to run that, i get the following error

./wkhtmltopdf.sh google.com google.pdf
xkbcommon: ERROR: failed to add default include path auto
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent en
ough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
Loading page (1/2)
Segmentation fault
              

note that the Qt error was not related

export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb & xvfb-run -a -e xvfb-run.log /home/guidingstarcc/bin/usr/local/bin/wkhtmltopdf pythonanywhere.com pa.pdfZ
Loading page (1/2)
Segmentation fault                                           ] 10%

So any guidance out there for getting wkhtmltopdf to work? I am using the 64 bit ubuntu trusty binary

Hi guidingstarcc,

I poked around a bit and I can confirm that the following code works with our experimental docker consoles, but not with the standard console (let us know if you want us to switch that on for you- also note that we don't have docker for webapps or scheduled tasks yet):

wget https://bitbucket.org/wkhtmltopdf/wkhtmltopdf/downloads/wkhtmltox-0.13.0-alpha-7b36694_linux-trusty-amd64.deb
dpkg-deb -x wkhtmltox-0.13.0-alpha-7b36694_linux-trusty-amd64.deb wkhtml-install
xvfb-run --auto-servernum ./wkhtml-install/usr/local/bin/wkhtmltopdf http://google.com google.pdf

and then navigating via the files tab to download and open google.pdf

I also saw the same errors as you with Qt and xkbcommon when doing the conversion.

Hi conrad,

thanks for the assistance!

I need this for use with django-wkhtmltopdf. It runs wkhtmltopdf in a subprocess; I am guessing that is a child of the web application shell/console/runtime, so docker is not available.

Can you confirm? Whats the timeframe on getting docker consoles running for webapps/scheduled tasks?

Hi, i'm trying to generate a pdf with wkhtmltopdf and it returns a Permission Error [Errno 13] when I try this : pdfkit.from_string(html, file, css = css_path,configuration = config, options = options) Any help ?

I should correct what I was saying above; pdfkit uses the WebKit rendering engine and QT; in theory that could work using a virtual frame buffer (eg. a fake display that doesn't actually show anywhere, but does exist in memory). But right now WebKit doesn't work on PythonAnywhere due to the way our virtualization system works.

I want to install wkhtmltopdf to my server as well.

How to get access to new virtualization system.

Plus, let me know if it's going to harm my current or stop my site which is running since few years.

I've switched on the new virtualization system for your account -- any new consoles you start will use it; websites and scheduled/always-on tasks will pick it up the next time they're started. Right now it won't be used in Jupyter notebooks or in SSH sessions, though that will change in the future.

It won't harm or stop your current site -- its features are superset of the old virtualization system's. We're planning to switch it on for everyone sometime over the coming month or two; the only reason we haven't done that yet is that we're testing how well it scales when there are thousands of people using it rather than just a few hundred.

Thanks for switching my account to new virtualization. Going to test it soon and then I will update if wkhtmltopdf is working fine or not.

Anyway, love the support here. I have seen responding you to Stackoverflow as well regarding Pythonanywhere.com questions.

Thanks for switching my account to new virtualization. Going to test it soon and then I will update if wkhtmltopdf is working fine or not.

Anyway, love the support here. I have seen responding you to Stackoverflow as well regarding Pythonanywhere.com questions. keep up the good work!

FileNotFoundError: [Errno 2] No such file or directory: b'/home/Nivas13897/.local/lib/python2.7/site-packages/django_wkhtmltopdf-3.3.0.dist-info.exe' NO MATCH During handling of the above exception, another exception occurred: NO MATCH Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, callback_args, callback_kwargs) File "./app/views.py", line 1225, in placeOrder getpdf = genorderpdf(ordr,ordername) File "./app/views.py", line 1944, in genorderpdf config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) File "/home/Nivas13897/.local/lib/python3.8/site-packages/pdfkit/api.py", line 83, in configuration return Configuration(*kwargs) File "/home/Nivas13897/.local/lib/python3.8/site-packages/pdfkit/configuration.py", line 24, in init raise IOError('No wkhtmltopdf executable found: "%s"\n' OSError: No wkhtmltopdf executable found: "b'/home/Nivas13897/.local/lib/python2.7/site-packages/django_wkhtmltopdf-3.3.0.dist-info.exe'" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf![enter image description here][1]

My Code :

path_wkthmltopdf = b'/home/Nivas13897/.local/lib/python2.7/site-packages/django_wkhtmltopdf-3.3.0.dist-info' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

YES EXACTLY ! That's why i asked in my earlier question "Let me know the wkhtmltopdf executable path", In my local system there is path "C:\Programfiles\wkhtmltopdf\bin\wkhtmltopdf.exe" , Similarly in pythonanywhere i don't know the executable path.Kindly give me the Path ?

My Code :

NEED TO REPLACE PYTHON ANYWHERE EXECUTABLE PATH

path_wkthmltopdf = b'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

ADDING ERROR LOG :

Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, callback_args, callback_kwargs) File "./app/views.py", line 1225, in placeOrder getpdf = genorderpdf(ordr,ordername) File "./app/views.py", line 1948, in genorderpdf pdfkit.from_file(Html_file_abs+ordername+'.html',pdf_path_abs+ordername+'.pdf',configuration=config) File "/home/Nivas13897/.local/lib/python3.8/site-packages/pdfkit/api.py", line 49, in from_file return r.to_pdf(output_path) File "/home/Nivas13897/.local/lib/python3.8/site-packages/pdfkit/pdfkit.py", line 159, in to_pdf raise IOError("wkhtmltopdf exited with non-zero code {0}. error:\n{1}".format(exit_code, stderr)) OSError: wkhtmltopdf exited with non-zero code -6. error: QXcbConnection: Could not connect to display NO MATCH*

Hi @nivas13897 sorry for the late response I did this a while ago so I'm not 100% sure what I did but if you give me a day or so I'll try to get back to you. What I can say is you will need the support team to switch your account to the virtualization system so that you can download it yourself. From what I can tell their latest system image isn't working properly or maybe I missed something.

Thanks for your valuable time and response @myles2. Sure take your time and let me know soon asap.,bcz i'm stucking with further development process.I hope don't need to download now already library is there in pythonanywere '/usr/bin/wkhtmltopdf' but i don't know the path , where is executable file for it to be configured in pdfkit??

In Local it works with : path_wkthmltopdf = b'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf).

Similarly we need to know the executable file path in pythonanywhere??

Thanks in advance @myles2 and @suppor- pythonanywhere

Hi Glenn,

I was wondering if you could help me - running into a similar problem

2020-07-11 09:22:08,076: OSError: wkhtmltoimage exited with non-zero code -6. error: 2020-07-11 09:22:08,077: QXcbConnection: Could not connect to display 2020-07-11 09:22:08,077: 2020-07-11 09:22:08,077: 2020-07-11 09:22:08,077: You need to install xvfb(sudo apt-get install xvfb, yum install xorg-x11-server-Xvfb, etc), then add option: {"xvfb": ""}.

Many thanks,

I've switched on the new virtualization system for your account, so your code will use it in any new consoles; websites and scheduled/always-on tasks will pick it up the next time they're restarted.

If it still doesn't work, could you share the code you're using and any new error messages?

Thank you Giles, still not working for me unfortunately. Code and errors below

   import random
   import pandas as pd
   import imgkit
   import os
   import time
   def DataFrame_to_slack(data, imgcss, outputfile, imgformat):
    fn = str(random.random() * 100000000).split(".")[0] + ".html"
    pd.set_option('precision', 0)
    data = data.round(0)
    try:
        os.remove(fn)
    except:
    text_file = open(fn, "a")
    # write the CSS
    text_file.write(imgcss)
    # write the HTML-ized Pandas DataFrame
    text_file.write(data.to_html())
    text_file.close()
    # # See IMGKit options for full configuration,
    # e.g. cropping of final image
    imgkitoptions = {"format": imgformat}
    imgkit.from_file(fn, outputfile, options=imgkitoptions)
    os.remove(fn)

Error:

2020-07-11 22:08:47,270: You need to install xvfb(sudo apt-get install xvfb, yum install xorg-x11-server-Xvfb, etc), then add option: {"xvfb": ""}.
2020-07-11 22:45:44,057: Traceback (most recent call last):
2020-07-11 22:45:44,058:   File "/usr/lib/python3.8/site-packages/bottle.py", line 862, in _handle
2020-07-11 22:45:44,058:     return route.call(**args)
2020-07-11 22:45:44,058:   File "/usr/lib/python3.8/site-packages/bottle.py", line 1742, in wrapper
2020-07-11 22:45:44,058:     rv = callback(*a, **ka)
2020-07-11 22:45:44,058:   File "/home/canonburygroup/.local/lib/python3.8/site-packages/truckpad/bottle/cors.py", line 53, in wrapper
2020-07-11 22:45:44,058:     return callback(*args, **kwargs)
2020-07-11 22:45:44,058:   File "/home/canonburygroup/mysite/bottle_app.py", line 207, in payrollrun
2020-07-11 22:45:44,058:     DataFrame_to_slack(gian, imgcss, "gian.png", "png")
2020-07-11 22:45:44,059:   File "/home/canonburygroup/mysite/dftoimg.py", line 62, in DataFrame_to_slack
2020-07-11 22:45:44,059:     imgkit.from_file(fn, outputfile, options=imgkitoptions)
2020-07-11 22:45:44,059:   File "/home/canonburygroup/.local/lib/python3.8/site-packages/imgkit/api.py", line 64, in from_file
2020-07-11 22:45:44,059:     return rtn.to_img(output_path)
2020-07-11 22:45:44,059:   File "/home/canonburygroup/.local/lib/python3.8/site-packages/imgkit/imgkit.py", line 246, in to_img
2020-07-11 22:45:44,059:     raise IOError("wkhtmltoimage exited with non-zero code {0}. error:\n{1}\n\n{2}".format(exit_code, stderr, xvfb_error))
2020-07-11 22:45:44,059: OSError: wkhtmltoimage exited with non-zero code -6. error:
2020-07-11 22:45:44,059: QXcbConnection: Could not connect to display 
2020-07-11 22:45:44,059: 
2020-07-11 22:45:44,059: 
2020-07-11 22:45:44,059: You need to install xvfb(sudo apt-get install xvfb, yum install xorg-x11-server-Xvfb, etc), then add option: {"xvfb": ""}.

Unfortunately this script gets all from my app and needs to run automatically

[edit by admin: formatting]

wkhtmltopdf is installed in our latest system image, but it only works with our new virtualisation system. We can update both for you. Note that switching to the new system image may break some of your existing code that worked on older versions. You may need to recreate any virtualenvs that you're using and you will need to start new consoles and reload your web apps. You will also need to kill any ipython notebook processes that are running by using the "Fetch processes" button on the Consoles page.

I'm getting an error during the execution of pdfkit. code:

pdf = pdfkit.from_url(url, False, options=options)
response = HttpResponse(pdf,content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="reportcard.pdf"
return response

Error

wkhtmltopdf exited with non-zero code -6. error:
QXcbConnection: Could not connect to display

Locally I'm using this version of wkhtmltopdf, and it works fine: wkhtmltopdf 0.12.6

& on pythonanywhere the version is a bit older wkhtmltopdf 0.12.2.4.

I saw on stackoverflow upgrading to the latest version might work: https://stackoverflow.com/a/51789478/8252429

Can you please upgrade the version?

My account previously got upgraded for new virtualization but I thought I will check it on the next site update but later due to COVID issue, I stopped my business so I had to shut down this website for few months and then I upgraded my account again. So basically my account switched to basic like free account and then to $5 monthly plan. I'm wondering if I still get the wkhtmltopdf automatically upgraded if not then please enable it for me as well.

Hi I am on the beginner account, and trying out pythonanywhere. I also have got as far as using the system /usr/bin/wkhtmltopdf, but end up with the error wkhtmltopdf exited with non-zero code -6. error: QXcbConnection: Could not connect to display Is it possible to avoid this, or should I switch to weasyprint which I see is installed?

Thank you @fjl for confirming you saved my weekend by this quick response and @glenn + all devs for such an awesome update with this virtualization. My app is running perfectly without any issue. Pythonanywhere supporting WKHTMLTOPDF perfectly. Awesome!!!!!!

i have run into the same problem with wkhtmltopdf on our eu.pythonanywhere.com account

unfortunately i can't login with the eu credentials for the forum :(

@fjl is there any chance you might change our eu account (controlaltcoop) to the new virtualization system so we can test if wktohtml works for us?

hi i am getting the error as 'OSError: wkhtmltopdf exited with non-zero code -11. error:' have followed all the steps in this post and also from post "https://stackoverflow.com/questions/62783277/how-can-i-create-a-pdf-file-from-jinja-template-in-flask-question-tagged-pytho" can some one please help me.

Hello, please can this account be switched to the new virtualisation? I have a webapp pdf export function coded with pdfkit, which – no surprise now having read this thread – doesn’t work on PA. Thanks!

FWIW – I saw wkhtmltopdf was installed on PA so went ahead with pdfkit, having baulked at the dependencies of weasleyprint I’d need locally. Might be worth making a note on https://help.pythonanywhere.com/pages/PDF

Here’s the recipe that worked for me. First, in a bash console –

  • cat /etc/*release ← find out linux distribution, in this case Ubtuntu 16
  • wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.xenial_amd64.deb ← get the corresponding download from https://wkhtmltopdf.org/downloads.html
  • mkdir wkhtml-install ← create a directory to contain the wkhtml executable etc.
  • dpkg-deb -x wkhtmltox_0.12.6-1.xenial_amd64.deb wkhtml-install ← extract the download into the directory
  • Find the executable in there. Within that folder, it’s at usr/local/bin/wkhtmltopdf
  • Then, in the python web app code –

  • PDFKIT_CONFIGURATION = pdfkit.configuration() if settings.DEBUG else pdfkit.configuration(wkhtmltopdf='/home/<your user name>/wkhtml-install/usr/local/bin/wkhtmltopdf’)
  • Wherever you call pdfkit, add configuration=PDFKIT_CONFIGURATION
  • e.g. pdfkit.from_string(html, tempfile.name, configuration=PDFKIT_CONFIGURATION)

    Hi @gleen,

    my application produces a PDF and I have this error:

    OSError: wkhtmltopdf exited with non-zero code -6. error: QXcbConnection: Could not connect to display

    I think it is the same problem of the other guys, can you turn on virtualization for my account too?

    Thank you very much!!

    Virtualization was activated for my account for I'm still running into issues.

    I'm using django and django-wkhtmltopdf. PDF generation work fine on my local machine. This is the message in the logs when I access the view generating the PDF.

    subprocess.CalledProcessError: Command '['/usr/bin/wkhtmltopdf', '--encoding', 'utf8', '/tmp/wkhtmltopdfmnz2jqo_.html', '-']' died with <Signals.SIGABRT: 6>.
    

    From my virtualenv I ran this command :

    wkhtmltopdf --encoding utf8 /tmp/wkhtmltopdfmnz2jqo_.html -
    

    And got this error :

    QXcbConnection: Could not connect to display 
    Aborted
    

    Any ideas on how to fix this issue ?

    Thank you

    Could you try adding this to the start of your script:

    from pyvirtualdisplay import Display
    

    ...and then wrapping your call to generate the PDF inside a:

    with Display():
    

    ...and see if that helps?

    I managed to generate the PDF from the command line by running a small python script with the pyvirtualdisplay command :

    with Display():
        os.system("wkhtmltopdf --encoding utf-8 /tmp/wkhtmltopdfii56luye.html -")
    

    I'm now struggling to integrate the Display call with the django-wkhtmltopdf library. This is what a view looks like :

    class MyPDF(PDFTemplateView):
        filename = 'my_pdf.pdf'
        template_name = 'template.html'
    

    Any idea where the display command should go ? I tried to modify the render_to_response method but I get the same error message.

    def render_to_response(self, context, **response_kwargs):
        with Display():
            response = super().render_to_response(context, **response_kwargs)
        return response
    

    Thanks !

    Friends generates the pdf for me now but it is not rendering the images that I need to pass to pdf someone I have the following code:

    options={
            'page-size': 'A4',
            'margin-top': '15',
            'margin-right': '25',
            'margin-left': '20',
            'margin-bottom': '5',
            'zoom': '1.1',
            'encoding': "UTF-8",
        #image = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1200px-Python-logo-notext.svg.png"
        image = "file:///home/cchavita23/username/app/static/images/logo-ori.png"
        name = "username"
        print_html = render_template('cert/certificado.html', img=image, ced=cedula, fecha=strfecha,
                                    name=name, sr=dirig)
        pdfkit.from_string(print_html, url_direct+"/certificado.pdf", options=options, configuration=PDFKIT_CONFIGURATION)
    

    I hope you can help me, thanks

    The server event log shows me this error:

    10%#015[==============================>                             ] 50%#015Warning: Failed to load https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1200px-Python-logo-notext.svg.png (ignore)#012[============================================================] 100%#015Printing pages (2/2)                                               #012[>                                                           ] #015Done
                  

    Friends I already managed to solve it, I hope it will serve you as it worked for me

    disp = Display().start() # Generamos una dependecia de venvDisplay
        options={
            'page-size': 'A4',
            'margin-top': '15',
            'margin-right': '25',
            'margin-left': '20',
            'margin-bottom': '5',
            'zoom': '1.1',
            'encoding': "UTF-8",
        image = "file:///home/cchavita23/Registro_temperatura/app/static/images/logo-ori.png"
        name = "Username"
        print_html = render_template('cert/certificado.html', img=image, ced=cedula, fecha=strfecha,
                                    name=name, sr=dirig)
        pdfkit.from_string(print_html, url_direct+"/certificado.pdf", options=options)
        disp.stop()     # Cerramos la conexion del pdf
    

    I hope I can help you

    I am getting same error, wkhtmltoimage exited with non-zero code -6. error: QXcbConnection: Could not connect to display

    Please help me out as well, turning on virtualisation, i tried with Display(), but wouldnt work!

    @fjl thankyou so much! Everything working just as wanted!

    if anyone came till here and still couldnt figure it out <br>Steps: <li> Get your virtualisation -<li> Install wkhtml <li>install pyvirtualdisplay <li> wrap your code around Display() function

    @fjl thankyou so much! Everything working just as wanted!

    if anyone came till here and still couldnt figure it out Steps: - Get your virtualisation - Install wkhtml - install pyvirtualdisplay - wrap your code around Display() function

    Hello,How do we know if the new virtualization is enabled for our account? If it isn't for mine, please enable it. Thank you

    Hi @hbconcepts. We're currently in the process of enabling the new virtualization system for all accounts on PythonAnywhere, which unfortunately may take a week or two to complete. We'll let you know when that has been done for your account; I've made a note to make sure that you're in one of the first batches to be moved over to it.

    Hi @Finch4. We're currently in the process of enabling the new virtualization system for all accounts on PythonAnywhere, which unfortunately may take a week or two to complete. We'll let you know when that has been done for your account; I've made a note to make sure that you're in one of the first batches to be moved over to it.

    Hi @Finch4 -- we've enabled virtualization feature for you. Here are the next steps:

    To use Chrome, you'll need to upgrade Selenium for your account -- for example, if you're using Python 3.7, run this in Bash:

    pip3.7 install --user --upgrade selenium
    

    ...and then you can run Selenium with Chrome using code like this:

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    browser = webdriver.Chrome(options=chrome_options)
        browser.get("https://www.google.com")
        print("Page title was '{}'".format(browser.title))
    finally:
        browser.quit()
                  

    But how to use it if I use wkhtmltopdf not directly by code below:

    rendered = render_template('pdf/register_template.html', adres=adres,nazwa_usera=nazwa_usera,haslo=haslo)
        options = {"enable-local-file-access": None}
        pdf = pdfkit.from_string(rendered, False, configuration=config, options=options)
            Sorry, we have had to rate-limit your feedback sending.
    Please try again in a few moments... Thanks for the feedback! Our tireless devs will get back to you soon.