logo

Go

This guide explains how to generate an HTML string using Go's standard template engine and convert it to PDF by sending it to pdfg's API.

Technical Overview

  1. Create a Go template
  2. Pass data to the template to generate an HTML string
  3. Send the generated HTML string to pdfg's API to convert it to PDF

Sample

Defining the Template

<!-- templates/invoice.html -->
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div class="invoice">
      <h1>Invoice</h1>
      <table>
        <thead>
          <tr>
            <th>Item</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          {{range .Items}}
          <tr>
            <td>{{.Name}}</td>
            <td>{{.Price}} USD</td>
          </tr>
          {{end}}
        </tbody>
      </table>
      <p class="total">Total: {{.Total}} USD</p>
    </div>
  </body>
</html>

Using the Template and Generating PDF

// main.go
package main

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

type Item struct {
Name string
Price int
}

type Invoice struct {
Items []Item
Total int
}

type PdfgRequest struct {
HTML string `json:"html"`
PdfOptions map[string]interface{} `json:"pdfOptions"`
}

func main() {
// Load template
tmpl, err := template.ParseFiles("templates/invoice.html")
if err != nil {
panic(err)
}

    // Prepare data
    invoice := Invoice{
    	Items: []Item{
    		{Name: "Product A", Price: 1000},
    		{Name: "Product B", Price: 2000},
    	},
    	Total: 3000,
    }

    // Generate HTML string
    var buf bytes.Buffer
    if err := tmpl.Execute(&buf, invoice); err != nil {
    	panic(err)
    }

    // Create request body
    reqBody := PdfgRequest{
    	HTML: buf.String(),
    	PdfOptions: map[string]interface{}{
    		"format": "A4",
    	},
    }

    jsonData, err := json.Marshal(reqBody)
    if err != nil {
    	panic(err)
    }

    // Request to pdfg's API
    req, err := http.NewRequest("POST", "https://api.pdfg.net/v1", bytes.NewBuffer(jsonData))
    if err != nil {
    	panic(err)
    }

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer YOUR_API_KEY")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
    	panic(err)
    }
    defer resp.Body.Close()

    // Save PDF
    if resp.StatusCode == 200 {
    	out, err := os.Create("invoice.pdf")
    	if err != nil {
    		panic(err)
    	}
    	defer out.Close()

    	_, err = io.Copy(out, resp.Body)
    	if err != nil {
    		panic(err)
    	}
    }
}