Convert HTML to PDF in Go

Convert HTML to PDF in Go using the HTML2PDFAPI REST API. Works with Gin, Echo, Fiber, and any Go application.

Quick Start

package main

import (
    "bytes"
    "encoding/json"
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    payload := map[string]interface{}{
        "html":   "<h1>Hello World</h1>",
        "format": "pdf",
    }

    jsonData, err := json.Marshal(payload)
    if err != nil {
        log.Fatal(err)
    }

    req, err := http.NewRequest("POST", "https://html2pdfapi.com/render", bytes.NewBuffer(jsonData))
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    out, err := os.Create("output.pdf")
    if err != nil {
        log.Fatal(err)
    }
    defer out.Close()
    io.Copy(out, resp.Body)
}

Gin Framework Example

package main

import (
    "bytes"
    "encoding/json"
    "io"
    "net/http"
    "os"

    "github.com/gin-gonic/gin"
)

func generatePDF(c *gin.Context) {
    htmlContent := renderTemplate("invoice.html", invoiceData)

    payload := map[string]interface{}{
        "html":   htmlContent,
        "format": "pdf",
        "options": map[string]interface{}{
            "format": "A4",
        },
    }

    jsonData, err := json.Marshal(payload)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    req, err := http.NewRequest("POST", "https://html2pdfapi.com/render", bytes.NewBuffer(jsonData))
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    req.Header.Set("Authorization", "Bearer "+os.Getenv("HTML2PDFAPI_KEY"))
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    defer resp.Body.Close()

    pdfData, err := io.ReadAll(resp.Body)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.Header("Content-Disposition", "attachment; filename=invoice.pdf")
    c.Data(http.StatusOK, "application/pdf", pdfData)
}

Available Options

OptionTypeDescription
formatstringOutput format: "pdf", "png", "jpeg", "webp"
htmlstringHTML content to convert
urlstringURL to convert
options.formatstringPage size: "A4", "Letter", etc.
options.landscapeboolLandscape orientation
options.printBackgroundboolInclude background colors/images

Other Integrations

Node.js Python PHP Ruby cURL n8n

See Use Cases

Add PDF generation to your Go app

Works with Gin, Echo, Fiber, and standard net/http.