Python Usage Examples
Learn how to use the HTML to Image API in Python. We’ll show examples using both the requests
library for basic usage and Flask for web applications.
Installation
First, install the required package:
pip install requests
Basic Python Example
Here’s a simple example using the requests
library:
import requests
import os
from datetime import datetime
def html_to_image(html: str, css: str = '') -> bytes:
"""Convert HTML to image using the HTML to Image API."""
api_key = os.getenv('HTML2IMG_API_KEY')
url = 'https://app.html2img.com/api/html'
# Prepare the request data
data = {
'html': html,
'css': css,
'width': 800,
'height': 600
}
# Make the request
response = requests.post(
url,
json=data,
headers={'X-API-Key': api_key}
)
# Check if the request was successful
response.raise_for_status()
return response.content
# Example usage
if __name__ == '__main__':
try:
# Example HTML content
html = '''
<div style="padding: 20px; background: #f0f0f0;">
<h1>Hello from Python!</h1>
<p>Generated at {}</p>
</div>
'''.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# Example CSS
css = '''
h1 { color: #2563eb; }
p { color: #4b5563; }
'''
# Generate the image
image_data = html_to_image(html, css)
# Save the image
with open('output.png', 'wb') as f:
f.write(image_data)
print('Image saved as output.png')
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
Screenshot Example
Taking a screenshot of a webpage:
import requests
import os
def take_screenshot(url: str) -> bytes:
"""Take a screenshot of a webpage using the Screenshot API."""
api_key = os.getenv('HTML2IMG_API_KEY')
api_url = 'https://app.html2img.com/api/screenshot'
# Prepare the request data
data = {
'url': url,
'width': 1200,
'height': 800,
'dpi': 2,
'fullpage': True
}
# Make the request
response = requests.post(
api_url,
json=data,
headers={'X-API-Key': api_key}
)
# Check if the request was successful
response.raise_for_status()
return response.content
# Example usage
if __name__ == '__main__':
try:
# Take a screenshot
screenshot_data = take_screenshot('https://example.com')
# Save the screenshot
with open('screenshot.png', 'wb') as f:
f.write(screenshot_data)
print('Screenshot saved as screenshot.png')
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
Flask Example
Here’s how to use the API in a Flask application:
from flask import Flask, render_template, jsonify, send_file
import requests
import os
from io import BytesIO
app = Flask(__name__)
@app.route('/generate-image')
def generate_image():
try:
# Render template to string
html = render_template('example.html',
title='Hello from Flask!',
timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
)
# Make API request
response = requests.post(
'https://app.html2img.com/api/html',
json={
'html': html,
'width': 800,
'height': 600
},
headers={'X-API-Key': os.getenv('HTML2IMG_API_KEY')}
)
response.raise_for_status()
# Return the image directly
return send_file(
BytesIO(response.content),
mimetype='image/png',
as_attachment=True,
download_name='output.png'
)
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)}), 500
@app.route('/take-screenshot')
def take_screenshot():
try:
url = request.args.get('url', 'https://example.com')
response = requests.post(
'https://app.html2img.com/api/screenshot',
json={
'url': url,
'width': 1200,
'height': 800,
'dpi': 2,
'fullpage': True
},
headers={'X-API-Key': os.getenv('HTML2IMG_API_KEY')}
)
response.raise_for_status()
return send_file(
BytesIO(response.content),
mimetype='image/png',
as_attachment=True,
download_name='screenshot.png'
)
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)}), 500
# Example template (example.html)
'''
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: system-ui, sans-serif;
margin: 0;
padding: 20px;
}
.container {
background: #f0f0f0;
padding: 20px;
border-radius: 8px;
}
h1 { color: #2563eb; }
p { color: #4b5563; }
</style>
</head>
<body>
<div class="container">
<h1>{{ title }}</h1>
<p>Generated at {{ timestamp }}</p>
</div>
</body>
</html>
'''
FastAPI Example
If you’re using FastAPI, here’s how you can implement it:
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
import requests
import os
from datetime import datetime
app = FastAPI()
@app.get("/generate-image")
async def generate_image():
try:
html = f'''
<div style="padding: 20px; background: #f0f0f0;">
<h1>Hello from FastAPI!</h1>
<p>Generated at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
</div>
'''
response = requests.post(
'https://app.html2img.com/api/html',
json={
'html': html,
'width': 800,
'height': 600
},
headers={'X-API-Key': os.getenv('HTML2IMG_API_KEY')}
)
response.raise_for_status()
return Response(
content=response.content,
media_type="image/png"
)
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/screenshot")
async def take_screenshot(url: str = 'https://example.com'):
try:
response = requests.post(
'https://app.html2img.com/api/screenshot',
json={
'url': url,
'width': 1200,
'height': 800,
'dpi': 2,
'fullpage': True
},
headers={'X-API-Key': os.getenv('HTML2IMG_API_KEY')}
)
response.raise_for_status()
return Response(
content=response.content,
media_type="image/png"
)
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=500, detail=str(e))
Using with Async/Await
If you prefer using async/await with aiohttp
:
import aiohttp
import asyncio
import os
async def html_to_image_async(html: str, css: str = '') -> bytes:
"""Convert HTML to image using async HTTP requests."""
api_key = os.getenv('HTML2IMG_API_KEY')
url = 'https://app.html2img.com/api/html'
async with aiohttp.ClientSession() as session:
async with session.post(
url,
json={
'html': html,
'css': css,
'width': 800,
'height': 600
},
headers={'X-API-Key': api_key}
) as response:
if response.status == 200:
return await response.read()
else:
raise aiohttp.ClientError(
f'API Error: {response.status} - {await response.text()}'
)
# Example usage
async def main():
try:
html = '''
<div style="padding: 20px; background: #f0f0f0;">
<h1>Hello from Python Async!</h1>
<p>Generated at {}</p>
</div>
'''.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
image_data = await html_to_image_async(html)
with open('async_output.png', 'wb') as f:
f.write(image_data)
print('Image saved as async_output.png')
except Exception as e:
print(f'Error: {e}')
if __name__ == '__main__':
asyncio.run(main())
Remember to store your API key in environment variables and never commit it to version control.