Generate invoice and report PDFs from HTML
Turn the HTML templates you already have into pixel-perfect invoice and report PDFs, with page breaks, print styles and paper sizes.
7 min read
Most PDF libraries ask you to learn their own layout language and give up on modern CSS. If you can already render an invoice as a web page, you’re nearly done: send that HTML to shotsmith and get back a PDF that looks exactly like the page, with selectable text and working links.
1. Send your HTML, get a PDF
Render your invoice template to an HTML string with your framework’s usual tools (Blade, Jinja, ERB, Razor, React’s renderToString), then POST it. HTML belongs in a request body, not a URL: it’s too long for one, and it holds customer data that shouldn’t end up in logs.
import { Shotsmith } from '@shotsmith/sdk';
const shotsmith = new Shotsmith({ accessKey: 'YOUR_ACCESS_KEY' });
import { writeFile } from 'node:fs/promises';
const file = await shotsmith.take({
html: '<h1>Invoice #1042</h1><p>Total: £120.00</p>',
format: 'pdf',
pdf_paper_format: 'a4',
pdf_print_background: true,
});
await writeFile('invoice.pdf', file);
<?php
require 'vendor/autoload.php';
use Shotsmith\Client;
$shotsmith = new Client('YOUR_ACCESS_KEY');
$file = $shotsmith->take([
'html' => '<h1>Invoice #1042</h1><p>Total: £120.00</p>',
'format' => 'pdf',
'pdf_paper_format' => 'a4',
'pdf_print_background' => true,
]);
file_put_contents('invoice.pdf', $file);
curl -X POST "https://shotsmith.dev/v1/take" \
-H "X-Access-Key: YOUR_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format": "pdf",
"pdf_paper_format": "a4",
"pdf_print_background": true
}' \
--fail-with-body \
-o invoice.pdf
import { writeFile } from 'node:fs/promises';
const res = await fetch('https://shotsmith.dev/v1/take', {
method: 'POST',
headers: {
'X-Access-Key': 'YOUR_ACCESS_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
html: '<h1>Invoice #1042</h1><p>Total: £120.00</p>',
format: 'pdf',
pdf_paper_format: 'a4',
pdf_print_background: true,
}),
});
if (!res.ok) throw new Error((await res.json()).error_message);
await writeFile('invoice.pdf', Buffer.from(await res.arrayBuffer()));
import json
import urllib.request
body = {
"html": "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format": "pdf",
"pdf_paper_format": "a4",
"pdf_print_background": True
}
req = urllib.request.Request(
"https://shotsmith.dev/v1/take",
data=json.dumps(body).encode(),
headers={"X-Access-Key": "YOUR_ACCESS_KEY", "Content-Type": "application/json"},
method="POST",
)
# Raises urllib.error.HTTPError on a 4xx/5xx response
with urllib.request.urlopen(req, timeout=120) as res, open("invoice.pdf", "wb") as f:
f.write(res.read())
<?php
$ch = curl_init('https://shotsmith.dev/v1/take');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['X-Access-Key: YOUR_ACCESS_KEY', 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'html' => '<h1>Invoice #1042</h1><p>Total: £120.00</p>',
'format' => 'pdf',
'pdf_paper_format' => 'a4',
'pdf_print_background' => true,
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
]);
$body = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
throw new RuntimeException(json_decode($body, true)['error_message']);
}
file_put_contents('invoice.pdf', $body);
package main
import (
"io"
"net/http"
"os"
"strings"
)
func main() {
body := strings.NewReader(`{
"html": "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format": "pdf",
"pdf_paper_format": "a4",
"pdf_print_background": true
}`)
req, _ := http.NewRequest("POST", "https://shotsmith.dev/v1/take", body)
req.Header.Set("X-Access-Key", "YOUR_ACCESS_KEY")
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(res.Body)
panic(string(msg))
}
out, err := os.Create("invoice.pdf")
if err != nil {
panic(err)
}
defer out.Close()
io.Copy(out, res.Body)
}
require "net/http"
require "json"
body = {
"html" => "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format" => "pdf",
"pdf_paper_format" => "a4",
"pdf_print_background" => true
}
res = Net::HTTP.post(
URI("https://shotsmith.dev/v1/take"),
body.to_json,
"X-Access-Key" => "YOUR_ACCESS_KEY",
"Content-Type" => "application/json"
)
raise res.body unless res.is_a?(Net::HTTPSuccess)
File.binwrite("invoice.pdf", res.body)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
public class Request {
public static void main(String[] args) throws Exception {
var body = """
{
"html": "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format": "pdf",
"pdf_paper_format": "a4",
"pdf_print_background": true
}
""";
var request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/take"))
.header("X-Access-Key", "YOUR_ACCESS_KEY")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofFile(Path.of("invoice.pdf")));
if (res.statusCode() != 200) {
throw new RuntimeException("HTTP " + res.statusCode());
}
}
}
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-Access-Key", "YOUR_ACCESS_KEY");
var body = """
{
"html": "<h1>Invoice #1042</h1><p>Total: £120.00</p>",
"format": "pdf",
"pdf_paper_format": "a4",
"pdf_print_background": true
}
""";
var res = await http.PostAsync(
"https://shotsmith.dev/v1/take",
new StringContent(body, Encoding.UTF8, "application/json")
);
res.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync("invoice.pdf", await res.Content.ReadAsByteArrayAsync());
2. Make it look right on paper
pdf_print_background=truekeeps background colours and images, such as table stripes and coloured headers. Without it, browsers print them white.- Paper and margins:
pdf_paper_format(a4,letter,legaland more),pdf_landscape, andpdf_marginwith units, such as15mm. - Images and fonts: use absolute URLs, or inline them as data URIs, because the page is rendered on our servers, not yours.
3. Control page breaks
CSS print rules decide where pages break. These three cover most invoices and reports:
/* Repeat the table header on every page */
thead { display: table-header-group; }
/* Never split a line item across two pages */
tr, .line-item { break-inside: avoid; }
/* Start the terms and conditions on a fresh page */
.terms { break-before: page; }
PDFs use print styles, so anything in @media print applies. Set media_type=screen if you want the on-screen design instead.
4. Generate in the background
A PDF takes a second or two, so generate it in a background job when the invoice is created, store it, and email or link to the stored file. Two options help:
store=truewith astorage_pathsuch asinvoices/{date}/{id}uploads the PDF straight to your own S3-compatible bucket.external_identifier, set to the invoice number, is echoed in webhooks and shown in your dashboard, so you can trace any PDF back to its invoice.
Language-specific versions: Laravel, Rails, Django and .NET.