简体   繁体   中英

Does html2image support the img tag?

I am trying to understand the html2image package. But it does not seem to find my locally stored images.

I use the following code:

from html2image import Html2Image

hti = Html2Image()

html_str ="""
<!DOCTYPE html>
<html>
    <body>
        <img src="example.jpg">
    </body>
</html>
"""

css_str = """
body {
  margin: 0;
  background: black;
}
"""

hti.screenshot(html_str=html_str, css_str=css_str, save_as="test.png")

Here "example.jpg" is an image of a flower saved in the same folder as the python script.

The html_str copied into another file can be displayed by a browser without any problem.

But when running the above python script, I end up with a mostly black image with corrupted file symbol in the upper left corner.

Is there a way to fix this? Or does html2image not support the img tag?

Not sure if the best way, but I think you need to calculate the project path on the system from Python, and then serve the asset ahead of that URI. Assuming you can import os , here is how you would get current Python project directory:

ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root

Once this is made, ROOT_DIR goes in the <img src='foo'> tag, then html2image should render, as the browser reads the system paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM