Package: html2image
PyPI PackageGitHub RepositoryA lightweight Python package acting as wrapper around the headless mode of existing web browsers, allowing image generation from HTML/CSS strings, files and URLs.This package has been tested on Windows, Ubuntu (desktop and server) and MacOS. If you encounter any problems or difficulties while using it, feel free to open an issue on the GitHub page of this project. Feedback is also welcome!PrincipleMost web browsers have a Headless Mode, which is a way to run them without displaying any graphical interface. Headless mode is mainly used for automated testing but also comes in handy if you want to take screenshots of web pages that are exact replicas of what you would see on your screen if you were using the browser yourself.However, for the sake of taking screenshots, headless mode is not very convenient to use. HTML2Image aims to hide the inconveniences of the browsers' headless modes while adding useful features, such as allowing the creation of images from simple strings.For more information about headless modes :(Chrome)https://developers.google.com/web/updates/2017/04/headless-chrome(Firefox)https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_modeInstallationHTML2Image is published on PyPI and can be installed through pip:pip install --upgrade html2imageIn addition to this package, at least one of the following browsersmustbe installed on your machine :Google Chrome (Windows, MacOS)Chromium Browser (Linux)Microsoft EdgeUsageFirst, import the package and instantiate itfromhtml2imageimportHtml2Imagehti=Html2Image()Multiple arguments can be passed to the constructor:browser:  Browser that will be used, can be set to'chrome'(default) or'edge'.browser_executable: The path or the command that can be used to find the executable of a specific browser.output_path: Path to the folder to which taken screenshots will be outputted. Default is the current working directory of your python program.size: 2-Tuple representing the size of the screenshots that will be taken. Default value is(1920, 1080).temp_path: Path that will be used to put together different resources when screenshotting strings of files. Default value is%TEMP%/html2imageon Windows, and/tmp/html2imageon Linux and MacOS.keep_temp_files: Pass True to this argument to not automatically remove temporary files created intemp_path. Default is False.Example:hti=Html2Image(size=(500,200))You can also change these values later:hti.size=(500,200)Then take a screenshotThescreenshotmethod is the basis of this package. Most of the time, you won't need to use anything else. It can take screenshots of various things:URLs via theurlparameter;HTML and CSSfilesvia thehtml_fileandcss_fileparameters;HTML and CSSstringsvia thehtml_strandcss_strparameters;and "other" types of files via theother_fileparameter (try it with .svg files!).And you can also (optional):Change the size of the screenshots using thesizeparameter;Save the screenshots as a specific name using thesave_asparameter.N.B.: Thescreenshotmethod returns alistcontaining the path(s) of the screenshot(s) it took.A few examplesURL to imagehti.screenshot(url='https://www.python.org',save_as='python_org.png')HTML & CSS strings to imagehtml="""<h1> An interesting title </h1> This page will be red"""css="body {background: red;}"hti.screenshot(html_str=html,css_str=css,save_as='red_page.png')HTML & CSS files to imagehti.screenshot(html_file='blue_page.html',css_file='blue_background.css',save_as='blue_page.png')Other files to imagehti.screenshot(other_file='star.svg')Change the screenshots' sizehti.screenshot(other_file='star.svg',size=(500,500))Click to show all the images generated with all the code aboveChange the directory to which the screenshots are savedhti=Html2Image(output_path='my_screenshot_folder')ORhti.output_path='my_screenshot_folder'N.B. : the output path will be changed for all future screenshots.Use lists in place of any parameters while using thescreenshotmethodScreenshot multiple objects using only one filename, or one filename per file:# create three files from one filenamehti.screenshot(html_str=['A','B','C'],save_as='ABC.png')# outputs ABC_0.png, ABC_1.png, ABC_2.png# create three files from from different filenameshti.screenshot(html_str=['A','B','C'],save_as=['A.png','B.png','C.png'])# outputs A.png, B.png, C.pngTake multiple screenshots with the same size# take four screenshots with a resolution of 100*50hti.screenshot(html_str=['A','B','C','D'],size=(100,50))Take multiple screenshots with different sizes# take four screenshots with different resolutions from three given sizeshti.screenshot(html_str=['A','B','C','D'],size=[(100,50),(100,100),(50,50)])# respectively 100*50, 100*100, 50*50, 50*50# if not enough sizes are given, the last size in the list will be repeatedApply CSS string(s) to multiple HTML string(s)# screenshot two html strings and apply css strings on bothhti.screenshot(html_str=['A','B'],css_str='body {background: red;}')# screenshot two html strings and apply multiple css strings on bothhti.screenshot(html_str=['A','B'],css_str=['body {background: red;}','body {font-size: 50px;}'])# screenshot one html string and apply multiple css strings on ithti.screenshot(html_str='A',css_str=['body {background: red;}','body {font-size: 50px;}'])Retrieve the path of the generated file(s)Thescreenshotmethod returns a list containing the path(s) of the screenshot(s):paths=hti.screenshot(html_str=['A','B','C'],save_as="letters.png",)print(paths)# >>> ['D:\\myFiles\\letters_0.png', 'D:\\myFiles\\letters_1.png', 'D:\\myFiles\\letters_2.png']Change browser flagsIn some cases, you may need to change theflagsthat are used to run the headless mode of a browser.Flags can be used to:Change the default background color of the pages;Hide the scrollbar;Add delay before taking a screenshot;Allow you to use Html2Image when you're root, as you will have to specify the--no-sandboxflag;You can find the full list of Chrome / Chromium flagshere.There are two ways to specify custom flags:# At the object instanciationhti=Html2image(custom_flags=['--my_flag','--my_other_flag=value'])# Afterwardshti.browser.flags=['--my_flag','--my_other_flag=value']Flags example use-case: adding a delay before taking a screenshotWith Chrome / Chromium, screenshots are fired directly after there is no more "pending network fetches", but you may sometimes want to add a delay before taking a screenshot, to wait for animations to end for example.
There is a flag for this purpose,--virtual-time-budget=VALUE_IN_MILLISECONDS. You can use it like so:hti=Html2Image(custom_flags=['--virtual-time-budget=10000','--hide-scrollbars'])hti.screenshot(url='http://example.org')Default flagsFor ease of use, some flags are set by default. However default flags are not used if you decide to specifycustom_flagsor change the value ofbrowser.flags:# Taking a look at the default flags>>>hti=Html2Image()>>>hti.browser.flags['--default-background-color=000000','--hide-scrollbars']# Changing the value of browser.flags gets rid of the default flags.>>>hti.browser.flags=['--1','--2']>>>hti.browser.flags['--1','--2']# Using the custom_flags parameter gets rid of the default flags.>>>hti=Html2Image(custom_flags=['--a','--b'])>>>hti.browser.flags['--a','--b']Using the CLIHTML2image comes with a Command Line Interface which you can use to generate screenshots from files and URLs on the go.The CLI is a work in progress and may undergo changes.
You can call it by typinghtiorhtml2imageinto a terminal.argumentdescriptionexample-h, --helpShows the help messagehti -h-U, --urlsScreenshots a list of URLshti -U https://www.python.org-H, --htmlScreenshots a list of HTML fileshti -H file.html-C, --cssAttaches a CSS files to the HTML oneshti -H file.html -C style.css-O, --otherScreenshots a list of files of type "other"hti -O star.svg-S, --save-asA list of the screenshot filename(s)hti -O star.svg -S star.png-s, --sizeA list of the screenshot size(s)hti -O star.svg -s 50,50-o, --output_pathChange the output path of the screenshots (default is current working directory)hti star.svg -o screenshot_dir-q, --quietDisable all CLI's outputshti --quiet-v, --verboseMore details, can help debugginghti --verbose--chrome_pathSpecify a different chrome path--temp_pathSpecify a different temp path (where the files are loaded)... now within a Docker container !You can also test the package and the CLI without having to install everything on your local machine, via a Docker container.Firstgit clonethis repocdinside itBuild the image :docker build -t html2image .Run and get inside the container :docker run -it html2image /bin/bashInside that container, thehtml2imagepackage as well aschromiumare installed.You can load and execute a python script to use the package, or simply use the CLI.On top of that, you can also usevolumesto bind a container directory to your local machine directory, allowing you to retrieve the generated images, or even load some resources (HTML, CSS or Python files).TestingOnly basic testing is available at the moment. To run tests, install the requirements (Pillow) and run PyTest at the root of the project:pip install -r requirements-test.txtpython -m pytestFAQCan I automatically take a full page screenshot?Sadly no, it is not easily possible. Html2Image relies on the headless mode of Chrome/Chromium browsers to take screenshots and there is no way to "ask" for a full page screenshot at the moment. If you know a way (by estimating the page size for example), please open an issue or a discussion!Can I add delay before taking a screenshot?Yesyou can, please take a look at theChange browser flagssection of the readme.Can I speed up the screenshot-taking process?Yes, when you are taking a lot of screenshots, you can achieve better performance using Parallel Processing or Multiprocessing methods. You can find anexample of it here.Can I make a cookie modal disappear?Yes and no.No, because there is no options to do it magically andextensions are not supported in headless Chrome(TheI don't care about cookiesextension would have been useful in this case).Yes, because you can make any element of a page disappear by retrieving its source code, modifying it as you wish, and finally screenshotting the modified source code.TODO ListA nice CLI (currently in a WIP state).Support for other browsers, such as Firefox, once their screenshot feature becomes operational.PDF generation?Contributing, issue templates, pull request template, code of conduct.If you see any typos or notice things that are oddly said, feel free to create an issue or a pull request.