Coder Social home page Coder Social logo

imgkit's Introduction

Hi there


🐱My Github stats:

GitHub stats Top Langs

imgkit's People

Contributors

arayate avatar dependabot-preview[bot] avatar jackjiasap avatar jarrekk avatar lukew3 avatar mlpranav avatar xtrntr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imgkit's Issues

wkhtmltoimage --load-error-handling option incorrect handling

I think I spotted an issue that prevents the option wkhtmltoimage --load-error-handling to be properly handled by imgkit.

The issue happens here https://github.com/jarrekk/imgkit/blob/master/imgkit/imgkit.py#L239

    if 'Error' in stderr:
        raise IOError('wkhtmltoimage reported an error:\n' + stderr)

Running the last version of wkhtmltoimage (which disables local files loading by default) I see

~$ wkhtmltoimage index.html test.jpg
Loading page (1/2)
Error: Failed loading page file:///home/angelo/index.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1, due to unknown error.

~$ wkhtmltoimage --load-error-handling ignore index.html test.jpg
Loading page (1/2)
Warning: Failed loading page file:///home/angelo/index.html (ignored)
Rendering (2/2)
Done

>>> options['load-error-handling'] = 'ignore'
>>> imgkit.from_string(html, 'foobar.jpg', options = options)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/imgkit/api.py", line 90, in from_string
    return rtn.to_img(output_path)
  File "/usr/local/lib/python3.6/dist-packages/imgkit/imgkit.py", line 240, in to_img
    raise IOError('wkhtmltoimage reported an error:\n' + stderr)
OSError: wkhtmltoimage reported an error:
Loading page (1/2)
Warning: Blocked access to file
Error: Failed to load about:blank, with network status code 301 and http status code 0 - Protocol "about" is unknown
Rendering (2/2)
Done
Exit with code 1 due to network error: ProtocolUnknownError

As you can see imgkit detects the Error string in stderr and raises IOError. This is not correct and line 239 should be modified to something like this (abort is the default option while the other ones are ignore and skip)

    load_error_handling_option = self.options.get('--load-error-handling', 'abort')
    if 'Error' in stderr and load_error_handling_option in ('abort', ):
        raise IOError('wkhtmltoimage reported an error:\n' + stderr)

OSError: wkhtmltoimage exited with non-zero code 1. error: Unknown long argument --orientation

Im using code from example

body = """
<html>
  <head>
    <meta name="imgkit-format" content="png"/>
    <meta name="imgkit-orientation" content="Landscape"/>
  </head>
  Hello World!
  </html>
"""
	imgkit.from_string(body,'name.jpg')

and i get error:

OSError: wkhtmltoimage exited with non-zero code 1. error:
Unknown long argument --orientation

Name:
  wkhtmltoimage 0.12.5 (with patched qt)

Synopsis:
  wkhtmltoimage [OPTIONS]... <input file> <output file>

Description:
  Converts an HTML page into an image,

General Options:
      --crop-h <int>                  Set height for cropping
      --crop-w <int>                  Set width for cropping
      --crop-x <int>                  Set x coordinate for cropping
      --crop-y <int>                  Set y coordinate for cropping
  -H, --extended-help                 Display more extensive help, detailing
                                  less common command switches
  -f, --format <format>               Output file format (default png)
      --height <int>                  Set screen height (default is calculated
                                    from page content) (default 0)
  -h, --help                          Display help
      --license                       Output license information and exit
      --log-level <level>             Set log level to: none, error, warn or
                                  info (default info)
      --quality <int>                 Output image quality (between 0 and 100)
                                    (default 94)
  -q, --quiet                         Be less verbose, maintained for backwards
                                     compatibility; Same as using --log-level
                                   none
  -V, --version                       Output version information and exit
      --width <int>                   Set screen width, note that this is used
                                    only as a guide line. Use
                   --disable-smart-width to make it strict.
                 (default 1024)
Contact:
  If you experience bugs or want to request new features please visit
  <https://github.com/wkhtmltopdf/wkhtmltopdf/issues>

Failed to build: README.md not found

[aatri@localhost ~]$ sudo /usr/local/bin/pip3 install imgkit
Collecting imgkit
Downloading imgkit-0.0.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-dui2ueu6/imgkit/setup.py", line 38, in
long_description=long_description(),
File "/tmp/pip-build-dui2ueu6/imgkit/setup.py", line 27, in long_description
with codecs.open('README.md', encoding='utf8') as f:
File "/usr/local/lib/python3.5/codecs.py", line 895, in open
file = builtins.open(filename, mode, buffering)
FileNotFoundError: [Errno 2] No such file or directory: 'README.md'

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

When I start the code:
imgkit.from_string('hello', 'output.jpg')
it raise the error
** in ()
----> 1 imgkit.from_string(r'hello', 'out.jpg')

/opt/anaconda3/lib/python3.6/site-packages/imgkit/api.py in from_string(string, output_path, options, toc, cover, css, config, cover_first)
55 rtn = IMGKit(string, 'string', options=options, toc=toc, cover=cover, css=css,
56 config=config, cover_first=cover_first)
---> 57 return rtn.to_img(output_path)
58
59

/opt/anaconda3/lib/python3.6/site-packages/imgkit/imgkit.py in to_img(self, path)
240 try:
241 with codecs.open(path) as f:
--> 242 text = f.read(4)
243 if text == '':
244 raise IOError('Command failed: %s\n'

/opt/anaconda3/lib/python3.6/codecs.py in decode(self, input, final)
319 # decode input (taking the buffer into account)
320 data = self.buffer + input
--> 321 (result, consumed) = self._buffer_decode(data, self.errors, final)
322 # keep undecoded input until the next call
323 self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

How to set the DPI of output image?

My code is as follows:
options = {
"quiet": "",
"width": 460,
"dpi": 120,
}
imgkit.from_file("render.html", 'out.jpg', options=options)
But after I run it, PyCharm display:
Unknown long argument --dpi

Encoding character bug in .from_string

When using .from_string function, characters like °,Ç,ã, etc, has encoding bugs

Reproducing
My html string looks like this: "objeto aguardando retirada no endereço indicado Para retirá-lo, é preciso informar o código do objeto".

So i created this code for testing:
Screenshot_3

Outputs:

-With .from_file:

HtmlFromFile

-With .from_string:

HtmlFromString

  • OS: Windows 10 20H2
  • IMGkit Version: 1.2.1
  • wkhtmltopdf Version: 0.12.6 (with patched qt)

FileNotFoundError: [Errno 2] No such file or directory: 'which'

Hey there,

first of all, sorry to be bothering you.
I have a very simple python function which takes an HTML table and converts it to an img:

import imgkit

def create_image_from_html(html):
    config = imgkit.config(wkhtmltoimage='/usr/bin/wkhtmltoimage')
    options ={
        "crop-w": "550",
        "xvfb": ""
    }
    imgkit.from_string(html, "portfolio.jpg", options=options, css="table.css", config=config)
    return "portfolio.jpg"

It used to run fine, but suddenly it somehow stopped working (Ubuntu Server 20.0.4, Flask with uWSGI). I already uninstalled and installed it from the binary. I also installed xvbf, just in case.

But I still run into the following error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "./tradingbot/routes.py", line 104, in message
    message = portfolio_message.get_message_payload()
  File "./tradingbot/portfolio_message.py", line 25, in get_message_payload
    *self._get_stocks_block(),
  File "./tradingbot/portfolio_message.py", line 51, in _get_stocks_block
    filepath = create_image_from_html(html)
  File "./tradingbot/image.py", line 5, in create_image_from_html
    config = imgkit.config(wkhtmltoimage='/usr/bin/wkhtmltoimage')
  File "/home/jan/Slackbot/env/lib/python3.8/site-packages/imgkit/api.py", line 101, in config
    return Config(**kwargs)
  File "/home/jan/Slackbot/env/lib/python3.8/site-packages/imgkit/config.py", line 26, in __init__
    self.xvfb = subprocess.Popen(['which', 'xvfb-run'],
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'which'

I have confirmed that wkhtmltoimage exists in /usr/bin/, I can see it with ls.
Any idea what could be causing this?

Thank you very much in advance!

INFO: Could not find files for the given pattern(s)

imgkit/imgkit/config.py

Lines 15 to 27 in c5fb49a

if sys.platform == 'win32':
self.wkhtmltoimage = subprocess.Popen(['where', 'wkhtmltoimage'],
stdout=subprocess.PIPE).communicate()[0].strip()
else:
self.wkhtmltoimage = subprocess.Popen(['which', 'wkhtmltoimage'],
stdout=subprocess.PIPE).communicate()[0].strip()
if not self.xvfb:
if sys.platform == 'win32':
self.xvfb = subprocess.Popen(['where', 'xvfb-run'],
stdout=subprocess.PIPE).communicate()[0].strip()
else:
self.xvfb = subprocess.Popen(['which', 'xvfb-run'],
stdout=subprocess.PIPE).communicate()[0].strip()

Lines 15-27 in config.py have an issue, due to the lack of an stderr argument, it ALWAYS prints the stderr to console. This, for me, printed the message INFO: Could not find files for the given pattern(s). Adding stderr=subprocess.DEVNULL to each subprocess.Popen fixed it.

Zooming in

Is there anyway to zoom up in a webpage? Like to 125% instead of 100%
Also if my webpage isnt fully loaded, what do you reccomend I do.

Unable to install in python3 virtualenv

Does this library have python3 support?

$ pip install imgkit
Collecting imgkit
  Downloading imgkit-0.1.1.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-vop6vgef/imgkit/setup.py", line 29
        print e
              ^
    SyntaxError: Missing parentheses in call to 'print'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-vop6vgef/imgkit/

Not loading the ajax generated results

Hi there,
I am using imgkit to save my page with charts. I am using from_url function. It saves the page as jpg without any problem however the content that are loaded using ajax are not in the saved image. Is there a way I can add delays on the image creation process so that it will include the ajax results as well?

Thank you,

from_string doesn't look at options for encoding?

Hi there! Thanks for sharing this project! It has been very helpful.

Imgkit works very well for the majority of cases. My issue lies when I send it characters that are greater than 0x7f, which I would like to be interpreted using latin-1.

To indicate I would like to use latin-1, I've passed options with encoding set to latin-1 to my from_string function call: imgkit.from_string(htmlString, output.png, options={'encoding':'latin-1'})

I'm getting an UnicodeDecodeError on line 220 of imgkit.py. Looking at the code, it appears to be forcing utf-8.

Perhaps "from_string" does not use options? Is there something else I'm doing wrong?

Thanks in advance!

No wkhtmltoimage executable found

After install imgkit through pip install imgkit, i can't find wkhtmltoimage anywhere, it shows below:

~/.conda/envs/venv/lib/python3.6/site-packages/imgkit/api.py in from_string(string, output_path, options, toc, cover, css, config, cover_first)
     87     """
     88     rtn = IMGKit(string, 'string', options=options, toc=toc, cover=cover, css=css,
---> 89                  config=config, cover_first=cover_first)
     90     return rtn.to_img(output_path)
     91

~/.conda/envs/venv/lib/python3.6/site-packages/imgkit/imgkit.py in __init__(self, url_or_file, source_type, options, toc, cover, css, config, cover_first)
     32                  css=None, config=None, cover_first=None):
     33         self.source = Source(url_or_file, source_type)
---> 34         self.config = Config() if not config else config
     35         try:
     36             self.wkhtmltoimage = self.config.wkhtmltoimage.decode('utf-8')

~/.conda/envs/venv/lib/python3.6/site-packages/imgkit/config.py in __init__(self, wkhtmltoimage, meta_tag_prefix)
     34                           'If this file exists please check that this process can '
     35                           'read it. Otherwise please install wkhtmltopdf - '
---> 36                           'http://wkhtmltopdf.org\n'.format(self.wkhtmltoimage))

OSError: No wkhtmltoimage executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org

Error when calling imgkit

While using this method
imgkit.from_file('test.html', 'out.jpg')
imgkit doesn't seem to be able to work with a file name that doesnt contain an extension
imgkit.from_file('test.html', 'out')
is there any work around for this ?

Exporting image to a variable can include internal warnings from miscellanous components, producing an invalid output.

Basically, I'm using the code as following:

	options = {
		"xvfb"   : "",
		'format' : 'png',
	}

	img = imgkit.from_string(rendered_html, False, options=options)
	print("Image generated")

	with open("test.png", "wb") as fp:
		fp.write(img)

	buf = io.BytesIO(img)
	im = Image.open(buf)
	im.save("figure.png")

	buf.close()

PIL fails to open the bytes array with OSError: cannot identify image file <_io.BytesIO object at 0x7fde9c07d888>. Saving the image, Irfanview can open the file, but other viewers report it as invalid.

Opening the image in a hex editor yields:

00000000:  6c69 6270 6e67 2077 6172 6e69 6e67 3a20 6943 4350 3a20 6b6e  :libpng warning: iCCP: kn
00000018:  6f77 6e20 696e 636f 7272 6563 7420 7352 4742 2070 726f 6669  :own incorrect sRGB profi
00000030:  6c65 0a6c 6962 706e 6720 7761 726e 696e 673a 2069 4343 503a  :le.libpng warning: iCCP:
00000048:  206b 6e6f 776e 2069 6e63 6f72 7265 6374 2073 5247 4220 7072  : known incorrect sRGB pr
00000060:  6f66 696c 650a 4c6f 6164 696e 6720 7061 6765 2028 312f 3229  :ofile.Loading page (1/2)
00000078:  0a5b 3e20 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :.[>                     
00000090:  2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :                        
000000a8:  2020 2020 2020 2020 2020 2020 2020 5d20 3025 0d5b 3d3d 3d3d  :              ] 0%.[====
000000c0:  3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d  :========================
000000d8:  3d3d 3e20 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :==>                     
000000f0:  2020 2020 2020 2020 5d20 3530 250d 5b3d 3d3d 3d3d 3d3d 3d3d  :        ] 50%.[=========
00000108:  3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d  :========================
00000120:  3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d  :========================
00000138:  3d3d 3d5d 2031 3030 250d 5265 6e64 6572 696e 6720 2832 2f32  :===] 100%.Rendering (2/2
00000150:  2920 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :)                       
00000168:  2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :                        
00000180:  2020 2020 200a 5b3e 2020 2020 2020 2020 2020 2020 2020 2020  :     .[>                
00000198:  2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :                        
000001b0:  2020 2020 2020 2020 2020 2020 2020 2020 2020 205d 2030 250d  :                   ] 0%.
000001c8:  5b3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3d3d 3e20 2020 2020 2020  :[===============>       
000001e0:  2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020  :                        
000001f8:  2020 2020 2020 2020 2020 2020 205d 2032 3525 0d89 504e 470d  :             ] 25%..PNG.
00000210:  0a1a 0a00 0000 0d49 4844 5200 0004 0000 0000 c508 0600 0000  :.......IHDR.............
00000228:  ca77 8097 0000 0009 7048 5973 0000 0f61 0000 0f61 01a8 3fa7  :.w......pHYs...a...a..?.
00000240:  6900 0020 0049 4441 5478 0100 0880 f77f 01ff ffff ff00 0000  :i.. .IDATx..............
00000258:  0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000  :........................
00000270:  0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000  :........................
00000288:  0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000  :........................
000002a0:  0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000  :........................

So there's some output stuff at the beginning of the file (line breaks added manually):

libpng warning: iCCP: known incorrect sRGB profile.
libpng warning: iCCP: known incorrect sRGB profile.
Loading page (1/2).
[>                                                           ] 0%.
[==============================>                             ] 50%.
[============================================================]100%.
Rendering (2/2).
[>                                                           ] 0%.
[===============>                                            ] 25%.
.PNG

It looks like the stdout of something internal (wkhtmltopdf?) is getting captured into the "image" output, somehow.

Images not exactly the same as HTMLs?

Hello, I am wondering why some output images are not exactly the same as the HTMLs that I opened in the browser?

I tried to include disable-smart-shrinking in the options, but it seems not working.

Appreciate any help!

xvfb-run failed to start

After using this package, I have run into an issue with the invocation of xvfb-run under the hood. Each virtual headless server xvfb-run spins up will have spin down time. My script calls imgkit synchronously with repetitious invocations of the xvfb-run. The default server it tries is always the same (:99) of which each new one tries this server and fails as the process is still open in memory. A sleep of 100MS has been the work around.

The solution would be to tell xvfb-run with the option -a, --auto-servernum Try to get a free server number, starting at 99, or the argument to --server-num.

Is there a way currently to pass this option down from imgkit to the xvfb-run process being called?

If not, I will submit a PR of this possibility.

iis OSError: [WinError 6] 句柄无效

按照网上的教程实现html转图片写好demo,在本地可以跑,放到django也可以,但是放到iis 中就报错无效的句柄
File ".\Plugin\imgkit.py", line 25, in generate_img_html
cfg = imgkit.config(wkhtmltoimage=path_wkimg)
File "c:\api\venv\lib\site-packages\imgkit\api.py", line 101, in config
return Config(**kwargs)
File "c:\api\venv\lib\site-packages\imgkit\config.py", line 24, in init
stdout=subprocess.PIPE).communicate()[0].strip()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 665, in init
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 919, in _get_handles
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
OSError: [WinError 6] 句柄无效。

我修改了imgkit/congfig.py 24 行代码
self.xvfb = subprocess.Popen(['which', 'xvfb-run'],stdout=subprocess.PIPE, stderr=subprocess.STDOUT,stdin=subprocess.DEVNULL).communicate()[0].strip()

我不知道为什么会产生这样的原因,但是我这样修改就可以正常使用了

encoding is not supported?

imgkit.from_string(html, 'out.jpg', config=config_image)

Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

UnicodeDecodeError Traceback (most recent call last)
in ()
----> 1 imgkit.from_string(html, 'out.jpg', config=config_image)

C:\Users\Trader\Anaconda3\lib\site-packages\imgkit-0.0.7-py3.5.egg\imgkit\api.py in from_string(string, output_path, options, toc, cover, css, config, cover_first)
55 rtn = IMGKit(string, 'string', options=options, toc=toc, cover=cover, css=css,
56 config=config, cover_first=cover_first)
---> 57 return rtn.to_img(output_path)
58
59

C:\Users\Trader\Anaconda3\lib\site-packages\imgkit-0.0.7-py3.5.egg\imgkit\imgkit.py in to_img(self, path)
243 text = f.read(4)
244 else:
--> 245 text = f.read(4).encode()
246 if text == '':
247 raise IOError('Command failed: %s\n'

C:\Users\Trader\Anaconda3\lib\encodings\cp1252.py in decode(self, input, final)
21 class IncrementalDecoder(codecs.IncrementalDecoder):
22 def decode(self, input, final=False):
---> 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0]
24
25 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 786: character maps to

Is there a custom image size option?

it converts to image file just fine but the width is fixed to 1024 px and I could not find a way to change it.
cropping won't work for me because I need a wider screenshot so I am wondering if there is a way to change the image size.

QXcbConnection: Could not connect to display

image = from_url(preview_url, output_path=image_path)

Gives below error:

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

Environment:

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.1 LTS"

Unable to read UTF-8 characters

I am trying to generate images from an HTML table, but it seems that UTF-8 characters are not supported (Please see image attached). Is there any workaround to provide support to such characters?

styled_table

I am using MacOS Catalina 10.15.5
imgkit Version: 1.0.2

How do i prevent output?

Nov 28 12:25:56 Alice python3.7[28666]: [205B blob data]
Nov 28 12:26:07 Alice python3.7[28666]: Loading page (1/2)

I want to disable blob data output.

by = imgkit.from_string(
            html, False, options={
                "width": 444,
                "height": 250,
                "crop-w": 444
            })
return by

imgkit with xvfb renders blank images in output file

hi!
I am using a raspberry 3 B+ running Stretch Version 9.

I developed a python program using imgkit. I have html files in a local directory and I am trying to output them in jpg files.
When I launch my program manually from the terminal, my program works perfectly fine: my html files (that contains text and jpg files) are rendered with the correct css and saved as a jpg file with this message:

Loading page (1/2)
Rendering (2/2)
Done

But when I tried the first time to launch my script with systemctl start name.service , I got an error message telling me

QXcbConnection: Could not connect to display
You need to install xvfb(sudo apt-get install xvfb, then add option: {"xvfb": ""}

I followed the instructions, restarted my service, the program launched without the previous error. This is where the problem happens: when I looked at the output files, the css is correct, the text also, but all my images are blank.
I also have this error poping into my terminal:

libEGL warning: DRI2: failed to create any config
libEGL warning: DRI2: failed to create any config
Loading page (1/2)
Rendering (2/2)
Done

After looking all around the web, I can't find anything close to an answer. Do you have any idea of what to do?
Thank you 🌻

Unknown error not able to understand - wkhtmltoimage exited with non-zero code -9. error:

File "/home/frappe/docker-bench/env/lib/python3.8/site-packages/imgkit/api.py", line 90, in from_string
return rtn.to_img(output_path)
File "/home/frappe/docker-bench/env/lib/python3.8/site-packages/imgkit/imgkit.py", line 246, in to_img
raise IOError("wkhtmltoimage exited with non-zero code {0}. error:\n{1}\n\n{2}".format(exit_code, stderr, xvfb_error))
OSError: wkhtmltoimage exited with non-zero code -9. error:
Loading page (1/2)
[> ] 0%
[======> ] 10%
[=========> ] 16%
Warning: Failed to load file:///assets/frappe/css/bootstrap.css (ignore)
Warning: Failed to load file:///assets/frappe/css/font-awesome.css (ignore)
[=========> ] 16%
[============> ] 20%
[=============> ] 23%
[===============> ] 25%
[================> ] 28%
Warning: Failed to load /files/Limit_Sale.PNG (ignore)
[=================> ] 29%
[===================> ] 32%
Warning: Failed to load /files/pohaa759c5.jpg (ignore)
[===================> ] 33%
[=====================> ] 35%
[======================> ] 37%
[========================> ] 40%
Warning: Failed to load /files/[email protected] (ignore)
[========================> ] 41%
[=========================> ] 43%
[===========================> ] 45%
[===========================> ] 46%
[=============================> ] 49%
[==============================> ] 51%
[===============================> ] 53%
[=================================> ] 55%
[==================================> ] 57%
[===================================> ] 59%
[====================================> ] 61%
[=====================================> ] 62%
[======================================> ] 64%
[=======================================> ] 66%
[========================================> ] 67%
[=========================================> ] 69%
[==========================================> ] 71%
[===========================================> ] 73%
[============================================> ] 74%
[=============================================> ] 76%
[==============================================> ] 77%
Warning: Failed to load /files/Godrej-No1-Sandal-3+1-64.jpg (ignore)
[==============================================> ] 78%
Warning: Failed to load /files/Patanjali-Shampoo-Aloevera-1 2019-04-15 19:17:49.jpg (ignore)
Warning: Failed to load /files/Delivery_Beat_Route_2 2019-05-19 00:45:01.PNG (ignore)
[===============================================> ] 79%
Warning: Failed to load /files/Untitled_2.png (ignore)
[===============================================> ] 79%
Warning: Failed to load /files/Godrej-No1-Lime-3+1-64.jpg (ignore)
[================================================> ] 81%
[=================================================> ] 82%
Warning: Failed to load /files/[email protected] (ignore)
[=================================================> ] 83%
Warning: Failed to load /files/[email protected] (ignore)
[===================================================> ] 85%
[===================================================> ] 86%
[====================================================> ] 87%
[====================================================> ] 88%
Warning: Failed to load /files/Bundle_test.png (ignore)
[====================================================> ] 88%
[====================================================> ] 88%
[=====================================================> ] 89%
[=====================================================> ] 89%
Warning: Failed to load /files/Mortein_PG_8h_Coil_+_ActivCard_Free.png (ignore)
[=====================================================> ] 89%
[======================================================> ] 90%
[======================================================> ] 90%
Warning: Failed to load /files/Delivery_Beat_Route_1 2019-05-07 12:50:25.PNG (ignore)
[======================================================> ] 90%
[======================================================> ] 90%
[============================================================] 100%
Rendering (2/2)
[> ] 0%
[===============> ] 25%

Anyone please help me with this.
Used these options:

        options = {
            'quality': quality,
            'width': width,  
            'enable-javascript': None,
            'enable-local-file-access': None,
            'images': None,
            'no-stop-slow-scripts': None,
            # 'enable-smart-width': None,
            'enable-plugins': None,
            'encoding': 'UTF-8',
            'disable-smart-width': None,
            'load-media-error-handling':'ignore',
            'load-error-handling':'ignore'
        }

ImgKit takes a long time to convert an html file to a jpg file (3 minutes)

imgkit.from_file(html_filename, image_filename, options={"width": 660, "disable-smart-width": ""})
is what I ran, and for some reason, at most times, this will take 3 minutes to run, and just yesterday, and only for yesterday, was it running at around 3 to 10 secs. The html, I am trying to render, is not important to mention, as the same problem happens with "www.google.com", about 3 minutes as well. I am running on Ubuntu 20.04.

Extra Detail:
for most of the time, there is no output in the console, and only in the last few seconds, the output appears

Loading page (1/2)
Rendering (2/2)                                                    
Done                                                               

from_string() got an unexpected keyword argument 'config'

I have two issues to report. One is a product of the other.

My code for the first one is as follows:

wkhtmltoimage_binaries = imgkit.config(wkhtmltoimage = '/app/bin/wkhtmltoimage')
img = imgkit.from_string('<body>hi</body>', False, config = wkhtmltoimage_binaries)

The resulting error is as follows:

TypeError: from_string() got an unexpected keyword argument 'config'

This confused me, as it has worked for a long time until just recently. Your readme file also mentions config being a keyword argument. Nevertheless, I edited my code to the following in hopes that it might detect the binaries automatically:

img = imgkit.from_string('<body>hi</body>', False)

It did not detect them automatically. In fact, the new error seems to communicate the presence of a bug. The error is as follows:

OSError: No wkhtmltoimage executable found: "command not found"

So I have two questions:

  1. Are we no longer able to configure imgkit to where we can specify the location of the wkhtmltoimage binaries?

  2. Following No wkhtmltoimage executable found:, isn't it meant to display the directory that it attempted to read from, rather than "command not found"?

OS: Ubuntu 20.04.2 LTS (Focal Fossa)

ImgKit does not render images in local file

Hi,

I am trying to convert a local HTML file into a jpeg. Everything works, except for the image in the HTML document, which doesn't show up. I've tried everything, including setting the img src to base64. The image still doesn't show up in the final jpeg.

I also read somewhere that I should add a header to my document to make it work, but it doesn't help.

UnicodeDecodeError on using "quiet" option

This works fine.

img = imgkit.from_string(data.to_html(), False, options = {'width': 772, 'disable-smart-width': '', 'zoom' : 1.5})

This is the output.

Loading page (1/2)
Rendering (2/2)
Done

But if I add the "quiet" option to suppress output, it does not work.

img = imgkit.from_string(data.to_html(), False, options = {'width': 772, 'disable-smart-width': '', 'zoom' : 1.5, 'quiet': ''})

This is the error:

Traceback (most recent call last):
  File "D:\Libraries\Desktop\oi.py", line 139, in <module>
    img = imgkit.from_string(data.to_html(), False, options = {'width': 772, 'disable-smart-width': '', 'zoom' : 1.5, 'quiet': ''})
  File "C:\Users\prana\AppData\Roaming\Python\Python37\site-packages\imgkit\api.py", line 108, in from_string
    return rtn.to_img(output_path)
  File "C:\Users\prana\AppData\Roaming\Python\Python37\site-packages\imgkit\imgkit.py", line 242, in to_img
    stderr = stderr.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

This is data.to_html(), if it helps.

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Time</th>
      <th>CE</th>
      <th>PE</th>
      <th>PE-CE</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>16:33</td>
      <td>955450</td>
      <td>-12425</td>
      <td>-958314</td>
      <td>34129</td>
    </tr>
  </tbody>
</table>

If I remove False argument and save the image as a png file instead, it works.

Error: Authentication Required

The page I'm trying to create an image for has a Basic authentication mechanism enabled.
Is there a way to provide the basic auth details to imgkit.

Exact Error:

INFO: Could not find files for the given pattern(s).
Traceback (most recent call last):
File "C:/Users/xavier.r.QUOSPHERE/PycharmProjects/kalpaturu/img2png.py", line 4, in
imgkit.from_url('http://myurl.com', 'out.png')
File "C:\Users\xavier.r.QUOSPHERE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\imgkit\api.py", line 21, in from_url
return rtn.to_img(output_path)
File "C:\Users\xavier.r.QUOSPHERE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\imgkit\imgkit.py", line 240, in to_img
raise IOError('wkhtmltoimage reported an error:\n' + stderr)
OSError: wkhtmltoimage reported an error:
Loading page (1/2)
Error: Authentication Required
Rendering (2/2)
Done
Exit with code 1 due to network error: AuthenticationRequiredError

INFO: Could not find files for the given pattern(s)

OS: Windows

ip = 127.0.0.1

		options = {
			'quiet': ''
		}
		img = imgkit.from_url(f'http://{ip}', f"sites\\{ip}.png", options=options)

Will sometimes return INFO: Could not find files for the given pattern(s) , any idea on whats causing this? Everything is correctly added to path.

i have install wkhtmltopdf in ubuntu but it don't work

Traceback (most recent call last):
File "test.py", line 5, in
imgkit.from_url('www.aiyangniu.cn','out.jpg')
File "/usr/local/lib/python2.7/dist-packages/imgkit/api.py", line 19, in from_url
rtn = IMGKit(url, 'url', options=options, toc=toc, cover=cover, config=config, cover_first=cover_first)
File "/usr/local/lib/python2.7/dist-packages/imgkit/imgkit.py", line 34, in init
self.config = Config() if not config else config
File "/usr/local/lib/python2.7/dist-packages/imgkit/config.py", line 36, in init
'http://wkhtmltopdf.org\n'.format(self.wkhtmltoimage))
IOError: No wkhtmltoimage executable found: ""
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org


and i install wkhtmltopdf in my mac use "brew install wkhtmltopdf", there is a error:
Error: No available formula with the name "wkhtmltopdf"

i have updated my homebrew ,so help me plz.

"Cannot Resolve"

OSError: wkhtmltoimage reported an error:
Loading page (1/2)
QSslSocket: cannot resolve CRYPTO_num_locks ] 10%
QSslSocket: cannot resolve CRYPTO_set_id_callback
QSslSocket: cannot resolve CRYPTO_set_locking_callback
QSslSocket: cannot resolve sk_free
QSslSocket: cannot resolve sk_num
QSslSocket: cannot resolve sk_pop_free
QSslSocket: cannot resolve sk_value
QSslSocket: cannot resolve SSL_library_init
QSslSocket: cannot resolve SSL_load_error_strings
QSslSocket: cannot resolve SSLv3_client_method
QSslSocket: cannot resolve SSLv23_client_method
QSslSocket: cannot resolve SSLv3_server_method
QSslSocket: cannot resolve SSLv23_server_method
QSslSocket: cannot resolve X509_STORE_CTX_get_chain
QSslSocket: cannot resolve OPENSSL_add_all_algorithms_noconf
QSslSocket: cannot resolve OPENSSL_add_all_algorithms_conf
QSslSocket: cannot resolve SSLeay
QSslSocket: cannot call unresolved function CRYPTO_num_locks
QSslSocket: cannot call unresolved function CRYPTO_set_id_callback
QSslSocket: cannot call unresolved function CRYPTO_set_locking_callback
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function sk_num
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function SSL_library_init
Error: Failed loading page http://pokeirc.de (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: UnknownNetworkError
QSslSocket: cannot call unresolved function CRYPTO_num_locks
QSslSocket: cannot call unresolved function CRYPTO_set_id_callback
QSslSocket: cannot call unresolved function CRYPTO_set_locking_callback

unable to use options

using
imgkit.from_string('string', False, config=config) works fine, but when i add options

options = {'format': 'png', 'width': '640', 'height': '480'}
img = imgkit.from_string(template.render(a=elements, r=range(len(elements))), False, config=config, options=options)
and i get

OSError: wkhtmltoimage exited with non-zero code 1. error:
Unknown long argument --format

im using it in heroku with wkhtmltopdf-pack-ng==0.12.3.0

PermissionError: [Errno 13] Permission denied: b''

>>> import imgkit
>>> html = "\n  <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,300,400,600\" type=\"text/css\" media=\"all\" />\n  <style type=\"text/css\" media=\"all\">\n    html {\n      font-size: 62.5%;\n      box-sizing: border-box;\n    }\n    body {\n      margin: 0;\n      padding: 0;\n      font-size:10pt;\n      line-height: 1.5;\n      box-sizing: border-box;\n      font-family: \"Open Sans\", arial, sans-serif;\n    }\n    p, div {\n      margin: 0;\n      min-height: 18px;\n      box-sizing: border-box;\n    }\n    ol, ul {\n      margin: 0;\n    }\n  </style>\n  <p>asdgfa<span style='color: #0D73D9;'>asdfasdfasdfasdfasdgasdfa</span><span style='color: #E51515;'>sadasdfa</span><span style='font-size: 14pt;'><span style='color: #E51515;'>asdgasdf</span><span style='color: #FCB104;'>asdgasdfasdfhasdf</span></span></p><p><span style='font-size: 14pt;'><span style='color: #A742FF;'>PURPLE TEXT IS IMPORTANT</span></span></p>"
>>> options = {'format': 'png', 'xvfb': ''}
>>> test = imgkit.from_string(html, False, options=options)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/houstonwarnick/.local/share/virtualenvs/letter-service-eh0o3bg_/lib/python3.6/site-packages/imgkit/api.py", line 90, in from_string
    return rtn.to_img(output_path)
  File "/Users/houstonwarnick/.local/share/virtualenvs/letter-service-eh0o3bg_/lib/python3.6/site-packages/imgkit/imgkit.py", line 213, in to_img
    stderr=subprocess.PIPE)
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: b''

I've been able to get it working with my local macOS environment without using xvfb, but once I try in an AlpineLinux environment that requires xvfb I get this error. I can reproduce the error with my local environment by using the xvfb flag there.

on macos | Error: No available formula with the name "wkhtmltopdf"

when i try brew install wkhtmltopdf i get this:

`
Error: No available formula with the name "wkhtmltopdf"
==> Searching for a previously deleted formula (in the last month)...
Warning: homebrew/core is shallow clone. To get complete history run:
git -C "$(brew --repo homebrew/core)" fetch --unshallow

Error: No previously deleted formula found.
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
==> Searching taps on GitHub...
Error: No formulae found in taps.
`

anyone can help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.