Search code examples
javascripthtmlcssimagerender

Render HTML to an image


Is there a way to render html to image like PNG? I know that it is possible with canvas but I would like to render standard html element like div for example.


Solution

  • There is a lot of options and they all have their pro and cons.

    Option 1: Use an API

    Pros

    • Execute Javascript
    • Near perfect rendering
    • Fast when caching options are correctly used
    • Scale is handled by the APIs
    • Precise timing, viewport, ...
    • Most of the time they offer a free plan

    Cons

    • Not free if you plan to use them a lot

    Option 2: Use one of the many available libraries

    Pros

    • Conversion is quite fast most of the time

    Cons

    • Bad rendering
    • Does not execute javascript
    • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
    • Sometimes not so easy to install
    • Complicated to scale

    Option 3: Use PhantomJs and maybe a wrapper library

    Pros

    • Execute Javascript
    • Quite fast

    Cons

    • Bad rendering
    • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
    • Complicated to scale
    • Not so easy to make it work if there is images to be loaded ...

    Option 4: Use Chrome Headless and maybe a wrapper library

    Pros

    • Execute Javascript
    • Near perfect rendering

    Cons

    • Not so easy to have exactly the wanted result regarding:
      • page load timing
      • viewport dimensions
    • Complicated to scale
    • Quite slow and even slower if the html contains external links

    Disclosure: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.