Skip to content
0

HTML to Image Converter Template

This project serves as a template for converting a section of an HTML page into a PNG image, exactly at your defined dimensions, using the html-to-image JavaScript library. It includes a pre-configured setup that handles common browser security issues, allowing you to easily adapt it for your own local image generation needs.

I use this template to create A+ content images for the Amazon store. There are two standard dimensions for A+ images: 1,464 by 600 pixels for desktop screens, and 600 by 450 pixels for mobile screens. The template's responsive design uses CSS media query techniques. You can manually adjust your browser size to generate and download the two sets of images, one for each required dimension.

Core Technology

  • HTML/CSS: For structuring and styling the content to be converted.
    • Define and use your own custom fonts
    • Define and use your own custom SVG icons
    • What you see is what you get—for instance, a 1,464 by 600 pixels image for the desktop screens
  • html-to-image: A powerful library that renders an HTML DOM node into a vector (SVG) or raster (PNG, JPEG) image.
  • JavaScript: For orchestrating the conversion process on the rendered HTML page.

The "Why": Understanding the Need for a Local Server

When you open an HTML file directly in a browser, it uses the file:/// protocol. For security reasons, modern browsers heavily restrict scripts loaded this way from accessing local files—even if those files are in the same directory.

The html-to-image library needs to fetch all the assets (like images and fonts) referenced in your HTML to accurately render the final image. When run from a file:/// page, this action is blocked by the browser's Cross-Origin Resource Sharing (CORS) policy, leading to errors in the console and preventing the script from working.

Solution: By using a local development server, you serve your files over the http:// protocol (e.g., http://127.0.0.1:5500). This makes the browser treat all your local files as being from the same origin, satisfying the CORS policy and allowing the html-to-image library to function correctly.

Getting Started

Prerequisites

  1. A Code Editor: Visual Studio Code is highly recommended.
  2. A Local Server Extension: If using VS Code, the Live Server extension is a perfect choice.

Step-by-Step Guide

  1. Structure Your Content:

    • Place all the HTML content you want to convert inside a single container element. In hotel-edition.html, this is the <div class="main-container">.
    • Give this container a unique identifier (like a class or ID) so you can select it with JavaScript.
    html
    <!-- hotel-edition.html -->
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="hotel-edition.css" />
        <!-- Load html-to-image from a CDN -->
        <script src="https://unpkg.com/html-to-image"></script>
        <script defer src="hotel-edition.js"></script>
        <title>Hotel Edition</title>
      </head>
      <body>
        <!-- The element to be converted -->
        <div class="main-container">
          <div class="grid-layout">
            <!-- Feature 1 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Bell with a slash -->
                <img
                  src="01.minimize-guest-confusions.svg"
                  alt="Bell with a slash icon"
                />
              </div>
              <h3>MINIMIZE GUEST CONFUSIONS</h3>
              <p>
                Our intuitive, single-day alarm automatically resets daily,
                eliminating a common source of negative reviews and unnecessary
                front desk calls.
              </p>
            </div>
    
            <!-- Feature 2 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Shield -->
                <img src="02.custom-built-for-hotel.svg" alt="Shield icon" />
              </div>
              <h3>CUSTOM BUILT FOR HOTEL</h3>
              <p>
                Engineered for the demands of hospitality, featuring a security
                lanyard to deter theft and a robust build to protect your investment
                long-term.
              </p>
            </div>
    
            <!-- Feature 3 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Globe -->
                <img src="03.global-power-supply.svg" alt="Globe icon" />
              </div>
              <h3>GLOBAL POWER SUPPLY</h3>
              <p>
                Simplify deployment with a universal power supply (AC 100V-240V)
                that includes US, UK, and EU plugs for use in any hotel, conforming
                to local standard.
              </p>
            </div>
    
            <!-- Feature 4 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Headphone Jack -->
                <img
                  src="04.foolproof-audio-option.svg"
                  alt="Headphone Jack icon"
                />
              </div>
              <h3>FOOLPROOF AUDIO OPTION</h3>
              <p>
                An attached line-in audio cable provides a simple plug-and-play
                connection, ensuring all guests can enjoy their own music,
                regardless of tech-savviness.
              </p>
            </div>
    
            <!-- Feature 5 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Soundwave with boundary -->
                <img
                  src="05.prevent-noise-complaints.svg"
                  alt="Soundwave with boundary icon"
                />
              </div>
              <h3>PREVENT NOISE COMPLAINTS</h3>
              <p>
                Audio is expertly volume-optimized to provide rich sound filling the
                guest room without bleeding through walls and disturbing others.
              </p>
            </div>
    
            <!-- Feature 6 -->
            <div class="feature-item">
              <div class="icon-container">
                <!-- Icon: Refresh / Reset -->
                <img
                  src="06.one-touch-system-reset.svg"
                  alt="Refresh / Reset icon"
                />
              </div>
              <h3>ONE-TOUCH SYSTEM RESET</h3>
              <p>
                Streamline housekeeping workflow with a simple reset button that
                instantly clears the previous guest's settings, ensuring privacy and
                convenience.
              </p>
            </div>
          </div>
        </div>
        <!-- The button to trigger the conversion -->
        <button id="convert-button">Convert to PNG</button>
      </body>
    </html>
  2. Link Your Assets:

    • Place all necessary links and scripts in the <head> of your HTML file. The following example shows the required assets:
    html
    <!-- hotel-edition.html -->
    <head>
      <link rel="stylesheet" href="hotel-edition.css" />
      <script src="https://unpkg.com/html-to-image"></script>
      <script defer src="hotel-edition.js"></script>
    </head>
    • CSS File: Link your stylesheet (hotel-edition.css) to ensure your content is styled before the conversion script runs.
    • html-to-image Library: Include the library via a CDN <script> tag. This pulls the core engine that performs the conversion, exposing a global htmlToImage object that your custom script can use.
    • Custom JavaScript (hotel-edition.js): Link your custom logic file using the defer attribute. defer is crucial—it tells the browser to wait until the HTML document is fully parsed before executing the script. This guarantees that elements like .main-container and #convert-button exist and are ready to be manipulated.
    css
    /* hotel-edition.css */
    /* Basic Reset and Font Import */
    @font-face {
      font-family: "sfq-font";
      src: url("Knockout 28.otf") format("opentype");
      font-weight: normal;
      font-style: normal;
    }
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    html,
    body {
      height: 100%;
      margin: 0;
    }
    body {
      font-family: "sfq-font", sans-serif;
      background-color: #f0f2f5; /* A light grey to see the container boundaries */
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    /* Main Container - Wide screen layout (default) */
    .main-container {
      width: 1464px;
      height: 600px;
      background-color: #ffffff;
      padding: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    }
    
    /* Grid Layout */
    .grid-layout {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(2, 1fr);
      gap: 40px 50px; /* Vertical and Horizontal gap */
      width: 100%;
      height: 100%;
    }
    
    /* Individual Feature Item Styling */
    .feature-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      padding: 10px;
    }
    
    /* Icon Styling */
    .icon-container {
      margin-bottom: 15px;
      color: #005a9c; /* A professional blue color */
    }
    
    .icon-container img {
      width: 50px;
      height: 50px;
    }
    
    /* Typography Styling */
    .feature-item h3 {
      font-size: 24px; /* Large, clear heading */
      font-weight: 600;
      color: #1a202c;
      margin-bottom: 8px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    .feature-item p {
      font-size: 20px; /* Readable body text */
      font-weight: 400;
      color: #4a5568;
      line-height: 1.5;
      max-width: 300px; /* Prevents text lines from getting too long */
    }
    
    /* Media Query for Narrow Screens */
    @media (max-width: 1463px) {
      .main-container {
        width: 600px;
        height: 450px;
        padding: 20px;
      }
    
      .grid-layout {
        gap: 20px 25px;
      }
    
      .icon-container {
        margin-bottom: 10px;
      }
    
      .icon-container img {
        width: 40px;
        height: 40px;
      }
    
      .feature-item h3 {
        font-size: 16px;
      }
    
      .feature-item p {
        font-size: 14px;
        max-width: 100%;
      }
    }
  3. Understand the JavaScript:

    • Ideally you don't have to change any code inside the hotel-edition.js.
    • The script will first select the trigger button (#convert-button) and the target container (.main-container).
    • An event listener is attached to the button. On click, it calls htmlToImage.toPng() on the target container.
    • This function returns a promise that resolves with a dataUrl (a Base64 representation of the PNG).
    • The script then creates a temporary link, sets its href to the dataUrl, assigns a download filename, and programmatically clicks the link to trigger the browser's download prompt.
    javascript
    // hotel-edition.js
    // Get the button and the element to convert
    const convertButton = document.getElementById("convert-button");
    const mainContainer = document.querySelector(".main-container");
    
    // Wrap the event listener logic in a window.onload event
    // This ensures all assets (images, fonts, etc.) are loaded before we attach the listener.
    window.onload = function () {
      convertButton.addEventListener("click", () => {
        // Use htmlToImage.toPng() to convert the element
        htmlToImage
          .toPng(mainContainer)
          .then(function (dataUrl) {
            // Create a link element to download the image
            const link = document.createElement("a");
            link.download = "main-container.png";
            link.href = dataUrl;
            link.click();
          })
          .catch(function (error) {
            console.error("oops, something went wrong!", error);
          });
      });
    };
  4. Launch with Live Server:

    • Right-click on your hotel-edition.html file in the VS Code explorer.
    • Select "Open with Live Server".
    • Your default browser will open a new tab with your page loaded from a local server address.
    • Click the "Convert to PNG" button. The generated image will now download as expected.

You can now modify the HTML and CSS with your own local assets to create and export new images using this reliable template.

最近更新