html2png
html2png
Use the html2png API to convert HTML to an image or document. Supports PNG, JPEG, WEBP, and PDF formats.
Installation
-
Add the dependency to your
shard.yml:dependencies: html2png: github: jgaskins/html2png -
Run
shards install
Usage
require "html2png"
# Convert the HTML to an image (PNG by default)
result = HTML2PNG.convert(<<-HTML)
<!doctype html>
<html>
<head>
<title>Stuff</title>
</head>
<body>
hello world
</body>
</html>
HTML
# Get the URL of the image
url = result.url
Image format
You can use a different image format by specifying it as an argument to the convert method:
HTML2PNG.convert(html, format: :png)
HTML2PNG.convert(html, format: :jpeg)
HTML2PNG.convert(html, format: :webp)
HTML2PNG.convert(html, format: :pdf)
Image size
HTML2PNG.convert(html, width: 800, height: 600)
Page color scheme
HTML2PNG.convert(html, color_scheme: :dark)
HTML2PNG.convert(html, color_scheme: :light)
Delayed rendering
If your HTML page takes additional time to load, such as to render assets, you can set a delay.
HTML2PNG.convert(html, delay: 3.seconds)
You can also wait for a specific CSS selector to load into the page before rendering.
HTML2PNG.convert(html, selector: "#my-content")
Transparent background
To avoid rendering the default white background (as browsers generally do):
HTML2PNG.convert(html, omit_background: true)
Pixel density and zoom
To set pixel density (for example, Retina vs non-Retina rendering), set the device_scale_factor. You can also set the zoom level:
HTML2PNG.convert(html, device_scale_factor: 2) # 1..4
HTML2PNG.convert(html, zoom: 2.5) # 0.1..3.0
Downloading the result
You can download to a Path:
HTML2PNG.convert(html).download_to(Path["/tmp/file"])
... or to an IO directly, such as an HTTP::Server::Response:
def call(context : HTTP::Server::Context)
buffer = IO::Memory.new
render "views/template.ecr", to: buffer
HTML2PNG.convert(buffer.to_s).download_to(context.response)
end
Contributing
- Fork it (https://github.com/jgaskins/html2png/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
Contributors
- Jamie Gaskins - creator and maintainer
html2png
- 0
- 0
- 0
- 0
- 0
- about 14 hours ago
- December 25, 2025
MIT License
Thu, 25 Dec 2025 05:05:27 GMT