<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valerian on Medium]]></title>
        <description><![CDATA[Stories by Valerian on Medium]]></description>
        <link>https://medium.com/@imvalerian?source=rss-df4724dbd262------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Xd0zxfqLE8gZWjW0</url>
            <title>Stories by Valerian on Medium</title>
            <link>https://medium.com/@imvalerian?source=rss-df4724dbd262------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imvalerian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel PDFs without dompdf or wkhtmltopdf: send the Blade view to a hosted renderer]]></title>
            <link>https://medium.com/@imvalerian/laravel-pdfs-without-dompdf-or-wkhtmltopdf-send-the-blade-view-to-a-hosted-renderer-93ad8f689a80?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ad8f689a80</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 00:57:07 GMT</pubDate>
            <atom:updated>2026-10-21T00:57:07.014Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>Most Laravel PDF questions on Stack Overflow are about two packages. barryvdh/laravel-dompdf turns HTML into PDF in pure PHP. barryvdh/laravel-snappy calls the wkhtmltopdf binary. The questions people keep landing on tell you where each one hurts:</p><ul><li>“Laravel DomPdf Add Custom Font” (about 72,000 views)</li><li>“Laravel dompdf error ‘Image not found or type unknown’” (about 67,000)</li><li>“How to make pdf exact 10CM width with DOMPDF and Laravel?” (about 48,000)</li><li>Snappy crashing with “The process has been signaled with signal 11” (about 22,000)</li><li>“Custom fonts not working in Generated PDF using WKHTMLTOPDF Library” (about 22,000)</li></ul><p>This piece takes one Blade invoice, shows what dompdf does with it, explains why Snappy is a poor choice for a new project, and then moves the same view to a hosted renderer with a small Laravel service. Every file below ran in a fresh Laravel 13 app on PHP 8.4, and the results are at the end.</p><h3>Where dompdf stops</h3><p>dompdf is honest about its limits. Its README says it “Handles most CSS 2.1 and a few CSS3 properties”, and the Known Issues list includes:</p><ul><li>Table cells are not pageable, meaning a table row must fit on a single page</li><li>Does not support CSS flexbox</li><li>Does not support CSS Grid</li></ul><p>(Issue links removed from the quote.)</p><p>(<a href="https://github.com/dompdf/dompdf#limitations-known-issues">dompdf README</a>)</p><p>Most Blade layouts written in the last few years use flexbox or grid somewhere. The invoice view below was rendered with dompdf 3.1.6 and with a browser engine. The flex header (title on the left, a badge on the right) collapsed into a full width bar, and the two grid cards stacked on top of each other:</p><p>You can rewrite the view with tables and floats, and plenty of teams do. It works, but the PDF template then lives apart from the rest of your front end and every new design starts with “how is this done in CSS 2.1?”</p><h3>Where Snappy stops</h3><p>Snappy uses a real browser engine, so flexbox mostly works. The problem is the engine itself. The wkhtmltopdf GitHub repository is archived, with its last push in November 2022, and the project’s own status page starts its recommendations with:</p><blockquote><em>Do not use wkhtmltopdf with any untrusted HTML</em></blockquote><p>It goes on to say that user supplied HTML or JavaScript can lead to a complete takeover of the server.</p><p>(<a href="https://wkhtmltopdf.org/status.html">wkhtmltopdf status</a>)</p><p>There is also the binary to ship. The laravel-snappy README warns that “some dependencies (libXrender for example) may not be present on your system and may require manual installation”, and the same question comes up on every new host. One Laracasts thread asks about Laravel Cloud: “Are these binaries already available on Laravel Cloud servers?”</p><h3>The other route: keep the Blade view, send the HTML away</h3><p>A Blade view is just a string once you call render(). You can send that string to something that runs a current browser engine and get a PDF back. You can run that engine yourself (spatie/laravel-pdf and Browsershot can drive headless Chrome through Node), or you can call a hosted API and install nothing.</p><p>The code below uses the <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=laravel-pdf-dompdf-snappy-alternative">thirds.ai HTML to PDF API</a>. It sends the HTML, waits for the job, downloads the file, and sends an Idempotency-Key so a retry or a double click returns the same PDF instead of making a second one. It uses only Laravel&#39;s HTTP client, so there is no extra Composer package.</p><h3>1. Config</h3><p>Add this to config/services.php, and put THIRDS_API_KEY in the server environment or your uncommitted .env. Reading it through config() keeps it working after php artisan config:cache.</p><pre>&#39;thirds&#39; =&gt; [<br>        &#39;key&#39; =&gt; env(&#39;THIRDS_API_KEY&#39;),<br>        &#39;url&#39; =&gt; env(&#39;THIRDS_API_URL&#39;, &#39;https://thirds.ai&#39;),<br>    ],</pre><h3>2. The service</h3><p>app/Services/ThirdsPdf.php does the HTTP work. The retry key is your document name plus a hash of the request body. Asking for the same invoice twice reuses the job. Editing the invoice changes the hash, so you never get the API&#39;s conflict error for reusing a key with a different body.</p><pre>&lt;?php</pre><pre>namespace App\Services;</pre><pre>use App\Exceptions\ThirdsPdfException;<br>use Closure;<br>use Illuminate\Http\Client\ConnectionException;<br>use Illuminate\Http\Client\PendingRequest;<br>use Illuminate\Http\Client\Response;<br>use Illuminate\Support\Facades\Http;</pre><pre>class ThirdsPdf<br>{<br>    public ?string $lastJobId = null;</pre><pre>    public function __construct(<br>        private ?string $key,<br>        private string $baseUrl = &#39;https://thirds.ai&#39;,<br>        private int $waitSeconds = 60,<br>    ) {}</pre><pre>    /**<br>     * Turn an HTML string into PDF bytes.<br>     *<br>     * $retryKey names the document, for example &quot;invoice-1042&quot;. The same<br>     * document sent again returns the same job instead of a second PDF.<br>     */<br>    public function render(string $html, array $pdf, string $retryKey): string<br>    {<br>        if (blank($this-&gt;key)) {<br>            throw ThirdsPdfException::missingKey();<br>        }</pre><pre>        $body = [&#39;html&#39; =&gt; $html, &#39;pdf&#39; =&gt; $pdf];<br>        // A changed invoice gets a new key, so an edit never collides with an old job.<br>        $idempotencyKey = $retryKey.&#39;-&#39;.substr(hash(&#39;sha256&#39;, json_encode($body)), 0, 16);</pre><pre>        $job = $this-&gt;send(fn () =&gt; $this-&gt;api()<br>            -&gt;withHeaders([&#39;Idempotency-Key&#39; =&gt; $idempotencyKey])<br>            -&gt;post(&#39;/v1/pdf&#39;, $body))-&gt;json();</pre><pre>        $deadline = now()-&gt;addSeconds($this-&gt;waitSeconds);<br>        while (in_array($job[&#39;status&#39;], [&#39;queued&#39;, &#39;running&#39;], true)) {<br>            if (now()-&gt;greaterThan($deadline)) {<br>                throw ThirdsPdfException::stillRunning($job[&#39;id&#39;]);<br>            }<br>            sleep(1);<br>            $job = $this-&gt;send(fn () =&gt; $this-&gt;api()-&gt;get(&#39;/v1/pdf/&#39;.$job[&#39;id&#39;]))-&gt;json();<br>        }</pre><pre>        $this-&gt;lastJobId = $job[&#39;id&#39;];<br>        if ($job[&#39;status&#39;] !== &#39;succeeded&#39;) {<br>            throw ThirdsPdfException::renderFailed($job);<br>        }</pre><pre>        // The download link is signed and lasts 15 minutes. It needs no API key.<br>        return $this-&gt;send(fn () =&gt; Http::baseUrl($this-&gt;baseUrl)-&gt;timeout(60)<br>            -&gt;get($job[&#39;download&#39;][&#39;url&#39;]))-&gt;body();<br>    }</pre><pre>    private function api(): PendingRequest<br>    {<br>        return Http::baseUrl($this-&gt;baseUrl)-&gt;withToken($this-&gt;key)-&gt;acceptJson()-&gt;timeout(30);<br>    }</pre><pre>    private function send(Closure $request): Response<br>    {<br>        try {<br>            $response = $request();<br>        } catch (ConnectionException $e) {<br>            throw ThirdsPdfException::network($e);<br>        }<br>        if ($response-&gt;failed()) {<br>            throw ThirdsPdfException::fromResponse($response);<br>        }</pre><pre>        return $response;<br>    }<br>}</pre><p>Bind it in AppServiceProvider::register():</p><pre>$this-&gt;app-&gt;bind(ThirdsPdf::class, fn () =&gt; new ThirdsPdf(<br>            config(&#39;services.thirds.key&#39;),<br>            config(&#39;services.thirds.url&#39;),<br>        ));</pre><h3>3. Clear errors</h3><p>Every failure becomes one exception with a message you can act on: a missing key stops before any request, a wrong key says so, and a failed render names the error code. The render() method turns it into a JSON 502 if it reaches the browser.</p><pre>&lt;?php</pre><pre>namespace App\Exceptions;</pre><pre>use Illuminate\Http\Client\ConnectionException;<br>use Illuminate\Http\Client\Response;<br>use RuntimeException;</pre><pre>class ThirdsPdfException extends RuntimeException<br>{<br>    public static function missingKey(): self<br>    {<br>        return new self(&#39;THIRDS_API_KEY is not set, so no request was sent. &#39;<br>            .&#39;Add it to the server environment, then run php artisan config:clear.&#39;);<br>    }</pre><pre>    public static function fromResponse(Response $response): self<br>    {<br>        $status = $response-&gt;status();<br>        $hint = match ($status) {<br>            401 =&gt; &#39; Check THIRDS_API_KEY.&#39;,<br>            409 =&gt; &#39; This retry key was already used for a different document.&#39;,<br>            429 =&gt; &#39; Too many requests. Wait and try again.&#39;,<br>            default =&gt; &#39;&#39;,<br>        };</pre><pre>        return new self(sprintf(&#39;thirds.ai answered %d %s: %s%s (request %s)&#39;,<br>            $status,<br>            $response-&gt;json(&#39;error.code&#39;, &#39;unknown_error&#39;),<br>            $response-&gt;json(&#39;error.message&#39;, &#39;no message&#39;),<br>            $hint,<br>            $response-&gt;json(&#39;error.request_id&#39;, &#39;n/a&#39;),<br>        ), $status);<br>    }</pre><pre>    public static function renderFailed(array $job): self<br>    {<br>        return new self(sprintf(&#39;PDF %s %s: %s/%s. A failed render uses no credit.&#39;,<br>            $job[&#39;id&#39;], $job[&#39;status&#39;], $job[&#39;error&#39;][&#39;category&#39;] ?? &#39;?&#39;, $job[&#39;error&#39;][&#39;code&#39;] ?? &#39;?&#39;));<br>    }</pre><pre>    public static function stillRunning(string $jobId): self<br>    {<br>        return new self(&quot;PDF $jobId is still rendering. Try again: the same retry key picks up the same job.&quot;);<br>    }</pre><pre>    public static function network(ConnectionException $e): self<br>    {<br>        return new self(&#39;Could not reach thirds.ai: &#39;.$e-&gt;getMessage());<br>    }</pre><pre>    /** Laravel calls this when the exception reaches the browser. */<br>    public function render()<br>    {<br>        return response()-&gt;json([&#39;error&#39; =&gt; $this-&gt;getMessage()], 502);<br>    }<br>}</pre><h3>4. The invoice: stream it or store it</h3><p>app/Services/InvoicePdf.php builds the HTML from the Blade view and holds the page options: A4, margins, and a &quot;Page X of Y&quot; footer that the renderer fills in.</p><pre>&lt;?php</pre><pre>namespace App\Services;</pre><pre>use App\Models\Invoice;<br>use Illuminate\Support\Facades\Storage;</pre><pre>class InvoicePdf<br>{<br>    public const OPTIONS = [<br>        &#39;format&#39; =&gt; &#39;A4&#39;,<br>        &#39;margins&#39; =&gt; [&#39;top&#39; =&gt; &#39;16mm&#39;, &#39;right&#39; =&gt; &#39;14mm&#39;, &#39;bottom&#39; =&gt; &#39;18mm&#39;, &#39;left&#39; =&gt; &#39;14mm&#39;],<br>        &#39;display_header_footer&#39; =&gt; true,<br>        &#39;header_template&#39; =&gt; &#39;&lt;span&gt;&lt;/span&gt;&#39;,<br>        &#39;footer_template&#39; =&gt; &#39;&lt;div style=&quot;font-size:8px;width:100%;text-align:center&quot;&gt;&#39;<br>            .&#39;Page &lt;span class=&quot;pageNumber&quot;&gt;&lt;/span&gt; of &lt;span class=&quot;totalPages&quot;&gt;&lt;/span&gt;&lt;/div&gt;&#39;,<br>    ];</pre><pre>    public function __construct(private ThirdsPdf $thirds) {}</pre><pre>    public function bytes(Invoice $invoice): string<br>    {<br>        $html = view(&#39;pdf.invoice&#39;, [&#39;invoice&#39; =&gt; $invoice])-&gt;render();</pre><pre>        return $this-&gt;thirds-&gt;render(<br>            $html,<br>            self::OPTIONS + [&#39;title&#39; =&gt; &quot;Invoice {$invoice-&gt;number}&quot;],<br>            &quot;invoice-{$invoice-&gt;number}&quot;,<br>        );<br>    }</pre><pre>    /** Save the PDF on a filesystem disk and return its path. */<br>    public function store(Invoice $invoice, string $disk = &#39;local&#39;): string<br>    {<br>        $path = &quot;invoices/{$invoice-&gt;number}.pdf&quot;;<br>        Storage::disk($disk)-&gt;put($path, $this-&gt;bytes($invoice));</pre><pre>        return $path;<br>    }</pre><pre>    public function lastJobId(): ?string<br>    {<br>        return $this-&gt;thirds-&gt;lastJobId;<br>    }<br>}</pre><p>The controller streams it to the browser:</p><pre>&lt;?php</pre><pre>namespace App\Http\Controllers;</pre><pre>use App\Models\Invoice;<br>use App\Services\InvoicePdf;</pre><pre>class InvoicePdfController extends Controller<br>{<br>    public function show(Invoice $invoice, InvoicePdf $pdfs)<br>    {<br>        return response($pdfs-&gt;bytes($invoice), 200, [<br>            &#39;Content-Type&#39; =&gt; &#39;application/pdf&#39;,<br>            &#39;Content-Disposition&#39; =&gt; &#39;inline; filename=&quot;invoice-&#39;.$invoice-&gt;number.&#39;.pdf&quot;&#39;,<br>        ]);<br>    }<br>}</pre><pre>Route::get(&#39;/invoices/{invoice:number}/pdf&#39;, [InvoicePdfController::class, &#39;show&#39;]);</pre><p>And an Artisan command stores it, which is the shape you want for a queue job or a nightly run:</p><pre>Artisan::command(&#39;invoice:pdf {number}&#39;, function (string $number, InvoicePdf $pdfs) {<br>    $invoice = Invoice::where(&#39;number&#39;, $number)-&gt;firstOrFail();<br>    try {<br>        $path = $pdfs-&gt;store($invoice);<br>    } catch (ThirdsPdfException $e) {<br>        $this-&gt;error($e-&gt;getMessage());</pre><pre>        return 1;<br>    }<br>    $this-&gt;info(&quot;Saved storage/app/private/$path from job {$pdfs-&gt;lastJobId()}&quot;);<br>})-&gt;purpose(&#39;Render an invoice to PDF and store it&#39;);</pre><h3>5. The Blade view</h3><p>Nothing special: flexbox, grid, a Google font and a long table. display: table-header-group repeats the table header on each page, and break-inside: avoid keeps rows whole.</p><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;700&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;style&gt;<br>  body { font-family: Inter, sans-serif; color: #1f2937; font-size: 12px; margin: 0; }<br>  .top { display: flex; justify-content: space-between; align-items: flex-start; }<br>  .badge { background: #4f46e5; color: #fff; border-radius: 8px; padding: 10px 16px; }<br>  .cards { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin: 24px 0; }<br>  .card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px; }<br>  table { width: 100%; border-collapse: collapse; }<br>  thead { display: table-header-group; }<br>  th { text-align: left; background: #f3f4f6; padding: 8px; }<br>  td { padding: 8px; border-bottom: 1px solid #e5e7eb; }<br>  tr { break-inside: avoid; }<br>  .num { text-align: right; }<br>  .total { display: flex; justify-content: flex-end; gap: 24px; font-size: 16px; font-weight: 700; margin-top: 16px; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;top&quot;&gt;<br>    &lt;div&gt;<br>      &lt;h1 style=&quot;margin:0&quot;&gt;Invoice {{ $invoice-&gt;number }}&lt;/h1&gt;<br>      &lt;p&gt;Issued {{ $invoice-&gt;issued_on-&gt;format(&#39;j F Y&#39;) }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;badge&quot;&gt;Northwind Studio&lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div class=&quot;cards&quot;&gt;<br>    &lt;div class=&quot;card&quot;&gt;&lt;strong&gt;Billed to&lt;/strong&gt;&lt;br&gt;{{ $invoice-&gt;customer }}&lt;/div&gt;<br>    &lt;div class=&quot;card&quot;&gt;&lt;strong&gt;Payment&lt;/strong&gt;&lt;br&gt;Due within 30 days&lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;table&gt;<br>    &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Item&lt;/th&gt;&lt;th class=&quot;num&quot;&gt;Qty&lt;/th&gt;&lt;th class=&quot;num&quot;&gt;Price&lt;/th&gt;&lt;th class=&quot;num&quot;&gt;Amount&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>    &lt;tbody&gt;<br>    @foreach ($invoice-&gt;lines as $line)<br>      &lt;tr&gt;<br>        &lt;td&gt;{{ $line[&#39;item&#39;] }}&lt;/td&gt;<br>        &lt;td class=&quot;num&quot;&gt;{{ $line[&#39;qty&#39;] }}&lt;/td&gt;<br>        &lt;td class=&quot;num&quot;&gt;{{ number_format($line[&#39;price&#39;], 2) }}&lt;/td&gt;<br>        &lt;td class=&quot;num&quot;&gt;{{ number_format($line[&#39;qty&#39;] * $line[&#39;price&#39;], 2) }}&lt;/td&gt;<br>      &lt;/tr&gt;<br>    @endforeach<br>    &lt;/tbody&gt;<br>  &lt;/table&gt;</pre><pre>  &lt;div class=&quot;total&quot;&gt;&lt;span&gt;Total&lt;/span&gt;&lt;span&gt;{{ number_format($invoice-&gt;total(), 2) }}&lt;/span&gt;&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Images and fonts have to be public HTTPS URLs or inline data URIs, because the renderer cannot read your server’s disk. If the logo lives in storage/, either serve it through asset() on a public URL or inline it with base64_encode(file_get_contents(...)).</p><h3>Exact page sizes (the 10 cm question)</h3><p>Pass width and height with a unit instead of format. This label is 100 mm by 150 mm:</p><pre>$invoice = App\Models\Invoice::where(&#39;number&#39;, &#39;INV-1042&#39;)-&gt;first();</pre><pre>$pdf = app(App\Services\ThirdsPdf::class)-&gt;render(<br>    view(&#39;pdf.label&#39;, [&#39;invoice&#39; =&gt; $invoice])-&gt;render(),<br>    [&#39;width&#39; =&gt; &#39;100mm&#39;, &#39;height&#39; =&gt; &#39;150mm&#39;],<br>    &quot;label-{$invoice-&gt;number}&quot;,<br>);</pre><pre>Illuminate\Support\Facades\Storage::put(&quot;labels/{$invoice-&gt;number}.pdf&quot;, $pdf);</pre><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;style&gt;<br>  @page { margin: 0; }<br>  body { margin: 0; font-family: sans-serif; }<br>  .label { box-sizing: border-box; width: 100mm; height: 150mm; padding: 8mm;<br>           display: flex; flex-direction: column; justify-content: space-between; border: 1mm solid #111; }<br>  .to { font-size: 18pt; font-weight: 700; }<br>  .ref { font-size: 28pt; letter-spacing: 2px; text-align: center; border-top: 0.5mm dashed #111; padding-top: 4mm; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;label&quot;&gt;<br>    &lt;div&gt;Ship to&lt;/div&gt;<br>    &lt;div class=&quot;to&quot;&gt;{{ $invoice-&gt;customer }}&lt;/div&gt;<br>    &lt;div class=&quot;ref&quot;&gt;{{ $invoice-&gt;number }}&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>A test that costs nothing</h3><p>Http::fake() covers the service without touching the API. This test checks the PDF response, that two requests send the same retry key, that the signed download does not carry your API key, and that each error reads clearly.</p><pre>&lt;?php</pre><pre>namespace Tests\Feature;</pre><pre>use App\Exceptions\ThirdsPdfException;<br>use App\Models\Invoice;<br>use App\Services\InvoicePdf;<br>use App\Services\ThirdsPdf;<br>use Database\Seeders\InvoiceSeeder;<br>use Illuminate\Foundation\Testing\RefreshDatabase;<br>use Illuminate\Http\Client\Request;<br>use Illuminate\Support\Facades\Http;<br>use Tests\TestCase;</pre><pre>class InvoicePdfTest extends TestCase<br>{<br>    use RefreshDatabase;</pre><pre>    protected function setUp(): void<br>    {<br>        parent::setUp();<br>        $this-&gt;seed(InvoiceSeeder::class);<br>        config([&#39;services.thirds.key&#39; =&gt; &#39;test-key&#39;]);<br>    }</pre><pre>    public function test_it_returns_the_pdf_and_reuses_the_retry_key(): void<br>    {<br>        Http::fake([<br>            &#39;thirds.ai/v1/pdf&#39; =&gt; Http::response([&#39;id&#39; =&gt; &#39;pdf_1&#39;, &#39;status&#39; =&gt; &#39;queued&#39;]),<br>            &#39;thirds.ai/v1/pdf/pdf_1&#39; =&gt; Http::response([<br>                &#39;id&#39; =&gt; &#39;pdf_1&#39;, &#39;status&#39; =&gt; &#39;succeeded&#39;, &#39;download&#39; =&gt; [&#39;url&#39; =&gt; &#39;/v1/downloads/x&#39;],<br>            ]),<br>            &#39;thirds.ai/v1/downloads/*&#39; =&gt; Http::response(&#39;%PDF-1.7 fake&#39;),<br>        ]);</pre><pre>        $this-&gt;get(&#39;/invoices/INV-1042/pdf&#39;)-&gt;assertOk()<br>            -&gt;assertHeader(&#39;Content-Type&#39;, &#39;application/pdf&#39;);<br>        $this-&gt;get(&#39;/invoices/INV-1042/pdf&#39;)-&gt;assertOk();</pre><pre>        $keys = Http::recorded(fn (Request $r) =&gt; $r-&gt;method() === &#39;POST&#39;)<br>            -&gt;map(fn ($pair) =&gt; $pair[0]-&gt;header(&#39;Idempotency-Key&#39;)[0])-&gt;values();<br>        $this-&gt;assertCount(2, $keys);<br>        $this-&gt;assertSame($keys[0], $keys[1]);<br>        $this-&gt;assertStringStartsWith(&#39;invoice-INV-1042-&#39;, $keys[0]);</pre><pre>        // The download request must not carry the API key.<br>        Http::assertSent(fn (Request $r) =&gt; str_contains($r-&gt;url(), &#39;/v1/downloads/&#39;)<br>            &amp;&amp; ! $r-&gt;hasHeader(&#39;Authorization&#39;));<br>    }</pre><pre>    public function test_a_wrong_key_gives_a_clear_502(): void<br>    {<br>        Http::fake([&#39;thirds.ai/*&#39; =&gt; Http::response([&#39;error&#39; =&gt; [<br>            &#39;code&#39; =&gt; &#39;unauthorized&#39;, &#39;message&#39; =&gt; &#39;Invalid API key.&#39;, &#39;request_id&#39; =&gt; &#39;r1&#39;,<br>        ]], 401)]);</pre><pre>        $this-&gt;get(&#39;/invoices/INV-1042/pdf&#39;)-&gt;assertStatus(502)<br>            -&gt;assertJsonPath(&#39;error&#39;, &#39;thirds.ai answered 401 unauthorized: Invalid API key. Check THIRDS_API_KEY. (request r1)&#39;);<br>    }</pre><pre>    public function test_a_missing_key_stops_before_any_request(): void<br>    {<br>        config([&#39;services.thirds.key&#39; =&gt; null]);<br>        Http::fake();</pre><pre>        $this-&gt;expectException(ThirdsPdfException::class);<br>        try {<br>            app(InvoicePdf::class)-&gt;bytes(Invoice::first());<br>        } finally {<br>            Http::assertNothingSent();<br>        }<br>    }</pre><pre>    public function test_a_failed_render_names_the_error_code(): void<br>    {<br>        Http::fake([&#39;thirds.ai/v1/pdf&#39; =&gt; Http::response([<br>            &#39;id&#39; =&gt; &#39;pdf_2&#39;, &#39;status&#39; =&gt; &#39;failed&#39;,<br>            &#39;error&#39; =&gt; [&#39;category&#39; =&gt; &#39;timeout&#39;, &#39;code&#39; =&gt; &#39;render_timeout&#39;],<br>        ])]);</pre><pre>        $this-&gt;expectExceptionMessage(&#39;PDF pdf_2 failed: timeout/render_timeout&#39;);<br>        app(ThirdsPdf::class)-&gt;render(&#39;&lt;p&gt;x&lt;/p&gt;&#39;, [], &#39;test&#39;);<br>    }<br>}</pre><h3>Test results</h3><p>All of this ran in a fresh Laravel 13.37 app on PHP 8.4, with 40 seeded invoice lines.</p><ul><li>php artisan test --filter=InvoicePdfTest: 4 tests, 13 assertions, all passing.</li><li>GET /invoices/INV-1042/pdf through php artisan serve: HTTP 200, application/pdf, 23,510 bytes in about 2 seconds. Two A4 pages, Inter embedded, the table header repeated on page 2, &quot;Page 1 of 2&quot; and &quot;Page 2 of 2&quot; in the footer, and the PDF title set to &quot;Invoice INV-1042&quot;.</li><li>php artisan invoice:pdf INV-1042 straight after: it saved the file from the same job ID, byte for byte identical, and the account history showed no new job.</li><li>With a wrong key: thirds.ai answered 401 unauthorized: The request needs a valid API key in the Authorization header or a signed-in session. Check THIRDS_API_KEY. Through the route, the browser got that message as a JSON 502.</li><li>With no key: THIRDS_API_KEY is not set, so no request was sent. and exit code 1.</li><li>The label: one page measuring 283.92 by 426 points, which is about 100.2 by 150.3 mm. The small difference comes from the browser engine rounding the page to whole pixels.</li></ul><h3>Which one to use</h3><ul><li><strong>Simple documents, no network calls allowed, layouts you can write with tables:</strong> dompdf is fine and stays inside PHP.</li><li><strong>You already run Node and Chrome on your servers:</strong> spatie/laravel-pdf or Browsershot gives you a modern engine you control.</li><li><strong>You do not want a browser or a binary on every host (Laravel Cloud, Vapor, shared hosting):</strong> send the rendered Blade view to a hosted API, as above.</li><li><strong>Snappy:</strong> avoid it for anything new, and never with user supplied HTML.</li></ul><p>The <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=laravel-pdf-dompdf-snappy-alternative">HTML to PDF API page</a> lists the other PDF options, such as landscape, scale and an open password.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ad8f689a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Images, fonts or backgrounds missing from your HTML to PDF? Three causes and how to fix each]]></title>
            <link>https://medium.com/@imvalerian/images-fonts-or-backgrounds-missing-from-your-html-to-pdf-three-causes-and-how-to-fix-each-23606440aaa8?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/23606440aaa8</guid>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 00:21:07 GMT</pubDate>
            <atom:updated>2026-10-21T00:21:07.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>“Image is not shown in the PDF with dompdf”, “adding fonts to the Puppeteer PDF renderer”, “Puppeteer not rendering background colour”, “mPDF full page background”. Each of these questions has tens of thousands of views, and they mostly have the same root cause: <strong>the PDF is made by a program that does not see what your browser sees.</strong> It may run on another machine, from another folder, without your fonts, and with print rules switched on.</p><p>Below are the three causes, what testing each one showed, and a small checker that catches the most common mistake before you send a page to any renderer.</p><h3>1. Images: the renderer can’t reach the file</h3><p>Your browser opens images/mug.jpg relative to the page it loaded. When you hand a renderer an HTML string, there is no page address, so a relative path points at nothing. file:// paths point at a disk the renderer may not have, and localhost or 192.168... addresses point at the renderer&#39;s own machine, not yours.</p><p><strong>dompdf adds two switches of its own.</strong> In dompdf 3.1.6 (per its Options.php):</p><ul><li>isRemoteEnabled is <strong>false</strong> by default, so images and CSS on https:// URLs are not fetched until you turn it on. The comment in the source explains why: with untrusted HTML, remote access lets your server fetch whatever the HTML asks for. Turn it on only for HTML you control, and use allowedRemoteHosts to limit it to your own domains.</li><li>chroot defaults to dompdf&#39;s own install folder. Local images outside it are refused. Point it at your public images folder (never at /), and call setBasePath() so relative paths resolve against that folder.</li></ul><p><strong>The fixes, in order of preference:</strong></p><ol><li>Use a full https:// URL to a public file.</li><li>For small images such as a logo, put the image inline as a data: URI. Nothing has to be fetched.</li><li>If your renderer runs on your own server and supports it, set a base path or a &lt;base href&gt;.</li></ol><p>In a local test with Chrome, the page with images/mug.jpg printed a broken image icon with the alt text; the same page with a full HTTPS URL printed the photo.</p><h3>2. Fonts: your machine has the font, the server doesn’t</h3><p>This one hides well. A test page used the Lobster font for its heading <strong>without loading it</strong>. On the test machine the PDF looked perfect, because Lobster happens to be installed there. On a server without Lobster the heading would quietly fall back to another font. If the PDF looks right on your laptop and wrong in production, this is the first thing to check.</p><p>The fix is to load the font from the page itself: a stylesheet or @font-face rule pointing at a public HTTPS font file (Google Fonts works), with a generic fallback such as cursive or sans-serif. Built in fonts differ between renderers, so check what yours includes; the thirds.ai renderer, for example, lists Liberation Sans, Serif and Mono for Latin text plus families for other scripts (<a href="https://thirds.ai/docs/pdf-and-image-options?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=html-to-pdf-missing-images-fonts-backgrounds">PDF and image options</a>). If you drive Chrome yourself, wait until the page&#39;s fonts have loaded before you print.</p><p>When the fixed page was sent to the hosted renderer, pdffonts showed Lobster embedded in the PDF, loaded from the Google Fonts stylesheet.</p><h3>3. Backgrounds: print mode drops them</h3><p>Browsers print without background colours and images unless told otherwise, to save ink. Puppeteer’s and Playwright’s page.pdf() follow that: their background option is off by default. Tested with Playwright 1.63 driving Chrome 155:</p><ul><li>The page with no print rule and the default print_background=False: no cream page, no teal header and no yellow box. Only the text, the logo mark and the broken image came out.</li><li>The same page with this CSS rule, still with print_background=False: every background printed.</li></ul><pre>* { -webkit-print-color-adjust: exact; print-color-adjust: exact; }</pre><p>So you can fix it in the page (the rule above) or in the call (printBackground: true in Puppeteer, print_background=True in Playwright). Doing both does no harm.</p><p><strong>A background that covers the whole page</strong> needs the page margins gone, otherwise you get a white frame. Set @page { margin: 0; } (or zero margins in your renderer&#39;s options), then give body the colour and a minimum height of one page, for example min-height: 297mm for A4. mPDF has its own page background options in its documentation; mPDF was not tested here.</p><h3>A checker for the image mistakes</h3><p>This script lists every asset address in a page that a renderer on another machine can’t load: relative paths, file://, plain http://, protocol relative // links, localhost and private network hosts. It runs on Node 18 with no packages, so you can put it in a test or a build step.</p><pre>// Finds the asset addresses in an HTML page that a PDF renderer on another machine can&#39;t load:<br>// relative paths, file:// and http:// links, localhost and private network hosts.<br>// Node 18+, no packages:  node asset-check.mjs page.html<br>import { readFile } from &quot;node:fs/promises&quot;;</pre><pre>const PRIVATE_HOST = /^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|0\.0\.0\.0|\[?::1\]?)/i;</pre><pre>export function findAssetProblems(html) {<br>  const found = [];<br>  // src=&quot;...&quot; and href=&quot;...&quot; on tags that load something, plus url(https://medium.com/...) in CSS.<br>  const attr = /&lt;(img|script|link|source|video|audio|iframe)\b[^&gt;]*?\b(src|href|srcset)\s*=\s*[&quot;&#39;]([^&quot;&#39;]+)[&quot;&#39;]/gi;<br>  const css = /url\(\s*[&quot;&#39;]?([^&quot;&#39;)]+)[&quot;&#39;]?\s*\)/gi;<br>  for (const m of html.matchAll(attr)) {<br>    if (m[1].toLowerCase() === &quot;link&quot; &amp;&amp; !/rel\s*=\s*[&quot;&#39;]?(stylesheet|preload|icon)/i.test(m[0])) continue;<br>    const urls = m[2].toLowerCase() === &quot;srcset&quot; ? m[3].split(&quot;,&quot;).map((s) =&gt; s.trim().split(/\s+/)[0]) : [m[3]];<br>    for (const url of urls) found.push({ tag: m[1].toLowerCase(), url });<br>  }<br>  for (const m of html.matchAll(css)) found.push({ tag: &quot;css url()&quot;, url: m[1] });</pre><pre>  const problems = [];<br>  for (const { tag, url } of found) {<br>    const u = url.trim();<br>    if (u.startsWith(&quot;data:&quot;) || u.startsWith(&quot;#&quot;)) continue; // inline data is always fine<br>    let reason = null;<br>    if (u.startsWith(&quot;file:&quot;)) reason = &quot;file:// points at a disk the renderer can&#39;t see&quot;;<br>    else if (u.startsWith(&quot;http://&quot;)) reason = &quot;plain <a href="http://;/">http://;</a> hosted renderers expect public https:// addresses&quot;;<br>    else if (u.startsWith(&quot;//&quot;)) reason = &quot;protocol relative; write https:// in full&quot;;<br>    else if (!/^[a-z][a-z0-9+.-]*:/i.test(u)) reason = &quot;relative path; there is no folder next to the HTML on the renderer&quot;;<br>    else if (u.startsWith(&quot;https://&quot;)) {<br>      const host = u.slice(8).split(/[/:?#]/)[0];<br>      if (PRIVATE_HOST.test(host) || !host.includes(&quot;.&quot;)) reason = &quot;private or local host; the renderer can&#39;t reach it&quot;;<br>    }<br>    if (reason) problems.push({ tag, url: u, reason });<br>  }<br>  return problems;<br>}</pre><pre>if (import.meta.url === `file://${process.argv[1]}`) {<br>  const file = process.argv[2];<br>  if (!file) {<br>    console.error(&quot;Usage: node asset-check.mjs page.html&quot;);<br>    process.exit(2);<br>  }<br>  const problems = findAssetProblems(await readFile(file, &quot;utf8&quot;));<br>  for (const p of problems) console.log(`${p.tag}: ${p.url}\n  ${p.reason}`);<br>  console.log(problems.length ? `${problems.length} problem(s) in ${file}` : `No asset problems in ${file}`);<br>  process.exit(problems.length ? 1 : 0);<br>}</pre><p>On the broken sample page it found images/mug.jpg. On a test string with seven different mistakes it found all seven, including a relative image hidden in a srcset and one in a CSS url(), and it ignored an ordinary link to another page.</p><h3>Putting it together</h3><p>Here is the checker in front of a hosted renderer: it refuses to send a page with an unreachable asset, then asks for the PDF with backgrounds on. It uses the <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=html-to-pdf-missing-images-fonts-backgrounds">thirds.ai HTML to PDF API</a>.</p><pre>// Checks a page&#39;s assets, then turns it into a PDF with backgrounds on, through the thirds.ai API.<br>// Node 18+, no packages:  THIRDS_API_KEY=... node render-pdf.mjs page.fixed.html out.pdf<br>import { createHash } from &quot;node:crypto&quot;;<br>import { readFile, writeFile } from &quot;node:fs/promises&quot;;<br>import { findAssetProblems } from &quot;./asset-check.mjs&quot;;</pre><pre>const [input, output = &quot;out.pdf&quot;] = process.argv.slice(2);<br>const KEY = process.env.THIRDS_API_KEY;<br>if (!input) {<br>  console.error(&quot;Usage: node render-pdf.mjs page.html out.pdf&quot;);<br>  process.exit(2);<br>}<br>if (!KEY) {<br>  console.error(&quot;Set THIRDS_API_KEY in your environment first.&quot;);<br>  process.exit(1);<br>}</pre><pre>const html = await readFile(input, &quot;utf8&quot;);<br>const problems = findAssetProblems(html);<br>if (problems.length) {<br>  // Stop before sending. Depending on the renderer, an asset it can&#39;t load fails the job or leaves a blank.<br>  for (const p of problems) console.error(`${p.tag}: ${p.url} (${p.reason})`);<br>  process.exit(1);<br>}</pre><pre>const body = {<br>  html,<br>  pdf: { format: &quot;A4&quot;, print_background: true, margins: { top: &quot;0mm&quot;, right: &quot;0mm&quot;, bottom: &quot;0mm&quot;, left: &quot;0mm&quot; } },<br>};<br>const headers = { Authorization: `Bearer ${KEY}`, &quot;Content-Type&quot;: &quot;application/json&quot; };</pre><pre>async function call(path, payload) {<br>  const h = payload ? { ...headers, &quot;Idempotency-Key&quot;: &quot;page-&quot; + createHash(&quot;sha256&quot;).update(JSON.stringify(payload)).digest(&quot;hex&quot;).slice(0, 32) } : headers;<br>  const res = await fetch(&quot;https://thirds.ai&quot; + path, { method: payload ? &quot;POST&quot; : &quot;GET&quot;, headers: h, body: payload &amp;&amp; JSON.stringify(payload) });<br>  const json = await res.json().catch(() =&gt; ({}));<br>  if (!res.ok) throw new Error(`${res.status} ${json.error?.code ?? &quot;&quot;}: ${json.error?.message ?? res.statusText}`);<br>  return json;<br>}</pre><pre>try {<br>  let job = await call(&quot;/v1/pdf&quot;, body);<br>  while (job.status === &quot;queued&quot; || job.status === &quot;running&quot;) {<br>    await new Promise((r) =&gt; setTimeout(r, 1000));<br>    job = await call(`/v1/pdf/${job.id}`);<br>  }<br>  if (job.status !== &quot;succeeded&quot;) throw new Error(`${job.status}: ${JSON.stringify(job.error)}`);<br>  const pdf = Buffer.from(await (await fetch(&quot;https://thirds.ai&quot; + job.download.url)).arrayBuffer()); // signed, 15 minutes<br>  await writeFile(output, pdf);<br>  console.log(`Saved ${output} (${pdf.length} bytes)`);<br>} catch (err) {<br>  console.error(&quot;Failed:&quot;, err.message);<br>  process.exit(1);<br>}</pre><pre>THIRDS_API_KEY=your_key node render-pdf.mjs page.fixed.html out.pdf</pre><p>What the test run produced:</p><ul><li>The broken page was stopped before any request, with the reason printed.</li><li>The fixed page became a one page A4 PDF with the cream page background, the teal header and the yellow box, the logo from the data URI, the photo from its HTTPS URL, and the Lobster heading embedded.</li><li>Running it again sent the same request with the same idempotency key and got the identical file back without a new render. A wrong key stops with 401 unauthorized, and a missing key stops before any request.</li></ul><h3>Quick checklist</h3><ul><li>Every image, font and stylesheet is a full https:// URL or inline data.</li><li>No font is assumed to be installed: load it, and give a generic fallback.</li><li>Backgrounds: print-color-adjust: exact in the CSS, or the background option on in your renderer.</li><li>Full page colour: zero page margins, colour on body, minimum height of one page.</li><li>dompdf only: isRemoteEnabled for trusted HTML, chroot and setBasePath() for local images.</li></ul><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23606440aaa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to save an HTML canvas chart as a PNG or a PDF, in the browser and on a server]]></title>
            <link>https://medium.com/@imvalerian/how-to-save-an-html-canvas-chart-as-a-png-or-a-pdf-in-the-browser-and-on-a-server-8f3cb7349beb?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f3cb7349beb</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 01:56:52 GMT</pubDate>
            <atom:updated>2026-10-20T01:56:52.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>“How do I capture an HTML canvas as a PNG or a PDF?” is one of the most visited canvas questions on Stack Overflow. The answer depends on where the chart needs to end up:</p><ul><li><strong>The person looking at the page wants a copy.</strong> Do it in the browser. The canvas already holds the picture, so toDataURL() gives you a PNG with no library and no server.</li><li><strong>The chart has to leave the browser without anyone clicking.</strong> A weekly email, a PDF report from a cron job, a Slack post. Then the chart has to be drawn somewhere without a person, which usually means running a headless browser on your server, or sending the page to a hosted renderer.</li></ul><p>This piece shows both, with code that was run and tested. The chart is Chart.js 4.5.1, but the same steps work for any library that draws to a canvas.</p><h3>In the browser: toDataURL</h3><p>Two details catch people out. A chart canvas is transparent, so the PNG has no background unless you paint one. And on a high density screen the canvas is bigger than it looks: Chart.js draws at the device pixel ratio, so an 800 by 420 chart is a 1600 by 840 canvas on a 2x display. That is good for sharpness; just expect the bigger file.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;title&gt;Download the chart&lt;/title&gt;<br>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js&quot;&gt;&lt;/script&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div style=&quot;width:800px;height:420px&quot;&gt;&lt;canvas id=&quot;c&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;<br>&lt;button id=&quot;png&quot;&gt;Download PNG&lt;/button&gt;<br>&lt;p id=&quot;out&quot;&gt;&lt;/p&gt;<br>&lt;script&gt;<br>const chart = new Chart(document.getElementById(&quot;c&quot;), {<br>  type: &quot;bar&quot;,<br>  data: { labels: [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;], datasets: [{ label: &quot;Orders&quot;, data: [42, 51, 48], backgroundColor: &quot;#2563eb&quot; }] },<br>  options: { animation: false, maintainAspectRatio: false },<br>});</pre><pre>// In the browser you don&#39;t need any service: the canvas already is an image.<br>// A white background is drawn behind it first, otherwise the PNG is transparent.<br>function chartAsPng(canvas) {<br>  const copy = document.createElement(&quot;canvas&quot;);<br>  copy.width = canvas.width;<br>  copy.height = canvas.height;<br>  const ctx = copy.getContext(&quot;2d&quot;);<br>  ctx.fillStyle = &quot;#fff&quot;;<br>  ctx.fillRect(0, 0, copy.width, copy.height);<br>  ctx.drawImage(canvas, 0, 0);<br>  return copy.toDataURL(&quot;image/png&quot;);<br>}</pre><pre>document.getElementById(&quot;png&quot;).onclick = () =&gt; {<br>  const a = document.createElement(&quot;a&quot;);<br>  a.href = chartAsPng(chart.canvas);<br>  a.download = &quot;chart.png&quot;;<br>  a.click();<br>};</pre><pre>// Used by the test only: shows what the function returns.<br>const url = chartAsPng(chart.canvas);<br>document.getElementById(&quot;out&quot;).textContent = `${url.slice(0, 22)} ${url.length} chars ${chart.canvas.width}x${chart.canvas.height}`;<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In headless Chrome this returned a data:image/png URL for an 800 by 420 canvas at 1x, and 1600 by 840 at 2x.</p><p>If the user wants a PDF instead, the simplest honest answer is still the browser’s own print dialog with a print stylesheet. Libraries that paint the page into a canvas and then slice it into PDF pages (html2canvas with jsPDF) give you a picture of the page, not real text, and they cut through lines at page edges.</p><h3>On a server: render the chart page with JavaScript turned on</h3><p>When there is no browser in front of a person, you need something that runs the chart’s JavaScript. You can install headless Chrome with Puppeteer or Playwright and keep it patched, or send the page to an HTML renderer. The script below does the second with the <a href="https://thirds.ai/html-to-image?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=canvas-chart-to-png-pdf">thirds.ai HTML to image API</a> and its PDF twin, in Node 18 with no packages. It makes a 1200 by 630 PNG of the chart and an A4 PDF report with the same chart above a table.</p><p>Three things make a chart render reliably on any server side renderer, not only this one:</p><ol><li><strong>Turn animation off.</strong> Otherwise the capture can happen halfway through the bars growing.</li><li><strong>Tell the renderer when you are done.</strong> Here that is data-thirds-render-ready=&quot;true&quot; on the &lt;html&gt; element. Give it a value: in testing, an empty attribute was never picked up, and the render failed after the two second wait with javascript_readiness_timeout. Failed renders are not charged.</li><li><strong>Put the library inline or pin its version.</strong> The script downloads Chart.js once and puts it inline, so the render never waits on a CDN and the same request always gives the same picture.</li></ol><pre>// Draw a Chart.js chart on a server and save it as a PNG and as a PDF report, with no headless browser<br>// to install. The chart HTML runs in thirds.ai&#39;s renderer with JavaScript turned on.<br>// Node 18+, no packages:  THIRDS_API_KEY=... node chart-to-png-and-pdf.mjs<br>import { createHash } from &quot;node:crypto&quot;;<br>import { writeFile } from &quot;node:fs/promises&quot;;</pre><pre>const API = &quot;https://thirds.ai&quot;;<br>const KEY = process.env.THIRDS_API_KEY;<br>if (!KEY) {<br>  console.error(&quot;Set THIRDS_API_KEY in your environment first.&quot;);<br>  process.exit(1);<br>}</pre><pre>// Chart.js goes inline in the page, so the render never waits on a CDN and every render<br>// (and its retry key) uses exactly this library version.<br>const CHART_JS = &quot;https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js&quot;;<br>const chartJs = (await (await fetch(CHART_JS)).text()).replaceAll(&quot;&lt;/script&quot;, &quot;&lt;\\/script&quot;);</pre><pre>const sales = { labels: [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;May&quot;, &quot;Jun&quot;], online: [42, 51, 48, 63, 71, 80], shop: [30, 28, 35, 33, 39, 41] };</pre><pre>// The chart page. Two things matter: animation is off, so the first frame is the final one,<br>// and the page sets data-thirds-render-ready=&quot;true&quot; on &lt;html&gt; when the chart is drawn.<br>function chartPage({ width, height }) {<br>  return `&lt;!doctype html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;script&gt;${chartJs}&lt;/script&gt;<br>&lt;style&gt;html,body{margin:0;background:#fff;font-family:&quot;Liberation Sans&quot;,sans-serif}<br>.wrap{width:${width}px;height:${height}px;padding:32px;box-sizing:border-box}&lt;/style&gt;&lt;/head&gt;<br>&lt;body&gt;&lt;div class=&quot;wrap&quot;&gt;&lt;canvas id=&quot;c&quot;&gt;&lt;/canvas&gt;&lt;/div&gt;&lt;script&gt;<br>new Chart(document.getElementById(&quot;c&quot;), {<br>  type: &quot;bar&quot;,<br>  data: { labels: ${JSON.stringify(sales.labels)}, datasets: [<br>    { label: &quot;Online&quot;, data: ${JSON.stringify(sales.online)}, backgroundColor: &quot;#2563eb&quot; },<br>    { label: &quot;Shop&quot;, data: ${JSON.stringify(sales.shop)}, backgroundColor: &quot;#f59e0b&quot; } ] },<br>  options: { animation: false, responsive: true, maintainAspectRatio: false,<br>    scales: { y: { beginAtZero: true, suggestedMax: 90 } },<br>    plugins: { title: { display: true, text: &quot;Orders per month&quot;, font: { size: 22 } } } }<br>});<br>// With animation off the chart is fully drawn here. The marker needs a value: an empty one is not seen.<br>document.documentElement.setAttribute(&quot;data-thirds-render-ready&quot;, &quot;true&quot;);<br>&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;`;<br>}</pre><pre>// For the PDF, the same chart sits in a printable report with a table under it.<br>function reportPage() {<br>  const rows = sales.labels.map((m, i) =&gt; `&lt;tr&gt;&lt;td&gt;${m}&lt;/td&gt;&lt;td&gt;${sales.online[i]}&lt;/td&gt;&lt;td&gt;${sales.shop[i]}&lt;/td&gt;&lt;td&gt;${sales.online[i] + sales.shop[i]}&lt;/td&gt;&lt;/tr&gt;`).join(&quot;&quot;);<br>  return chartPage({ width: 700, height: 380 }).replace(&#39;&lt;div class=&quot;wrap&quot;&gt;&#39;, &#39;&lt;h1 style=&quot;margin:0 0 4px;font-size:24px&quot;&gt;Half year orders&lt;/h1&gt;&lt;p style=&quot;margin:0 0 16px;color:#555&quot;&gt;January to June 2026&lt;/p&gt;&lt;div class=&quot;wrap&quot;&gt;&#39;)<br>    .replace(&quot;&lt;/div&gt;&lt;script&gt;&quot;, `&lt;/div&gt;&lt;style&gt;td,th{padding:6px 8px;border-bottom:1px solid #e2e8f0}&lt;/style&gt;&lt;table style=&quot;width:700px;border-collapse:collapse;margin-top:16px;font-size:13px&quot;&gt;&lt;thead&gt;&lt;tr style=&quot;background:#f1f5f9&quot;&gt;&lt;th align=&quot;left&quot;&gt;Month&lt;/th&gt;&lt;th align=&quot;left&quot;&gt;Online&lt;/th&gt;&lt;th align=&quot;left&quot;&gt;Shop&lt;/th&gt;&lt;th align=&quot;left&quot;&gt;Total&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;${rows}&lt;/tbody&gt;&lt;/table&gt;&lt;script&gt;`);<br>}</pre><pre>async function call(path, body) {<br>  const headers = { Authorization: `Bearer ${KEY}`, &quot;Content-Type&quot;: &quot;application/json&quot; };<br>  // The same request always gets the same key, so a retry returns the first file instead of a new one.<br>  if (body) headers[&quot;Idempotency-Key&quot;] = &quot;chart-&quot; + createHash(&quot;sha256&quot;).update(JSON.stringify(body)).digest(&quot;hex&quot;).slice(0, 32);<br>  const res = await fetch(API + path, { method: body ? &quot;POST&quot; : &quot;GET&quot;, headers, body: body &amp;&amp; JSON.stringify(body) });<br>  const json = await res.json().catch(() =&gt; ({}));<br>  if (!res.ok) throw new Error(`${res.status} ${json.error?.code ?? &quot;&quot;}: ${json.error?.message ?? res.statusText}`);<br>  return json;<br>}</pre><pre>async function render(kind, body, file) {<br>  let job = await call(`/v1/${kind}`, body);<br>  while (job.status === &quot;queued&quot; || job.status === &quot;running&quot;) {<br>    await new Promise((r) =&gt; setTimeout(r, 1000));<br>    job = await call(`/v1/${kind}/${job.id}`);<br>  }<br>  if (job.status !== &quot;succeeded&quot;) throw new Error(`${job.id} ${job.status}: ${JSON.stringify(job.error)}`);<br>  const res = await fetch(API + job.download.url); // signed link, no key needed, valid for 15 minutes<br>  const bytes = Buffer.from(await res.arrayBuffer());<br>  await writeFile(file, bytes);<br>  console.log(`${file}: ${bytes.length} bytes`);<br>}</pre><pre>try {<br>  await render(&quot;image&quot;, {<br>    html: chartPage({ width: 1200, height: 630 }),<br>    javascript: { mode: &quot;enabled&quot; },<br>    image: { format: &quot;png&quot;, width: 1200, height: 630 },<br>  }, &quot;chart.png&quot;);<br>  await render(&quot;pdf&quot;, {<br>    html: reportPage(),<br>    javascript: { mode: &quot;enabled&quot; },<br>    viewport: { width: 800, height: 1100, device_scale_factor: 2 }, // a sharper chart bitmap in the PDF<br>    pdf: { format: &quot;A4&quot;, margins: { top: &quot;18mm&quot;, right: &quot;16mm&quot;, bottom: &quot;18mm&quot;, left: &quot;16mm&quot; }, title: &quot;Half year orders&quot; },<br>  }, &quot;report.pdf&quot;);<br>} catch (err) {<br>  console.error(&quot;Failed:&quot;, err.message);<br>  process.exit(1);<br>}</pre><p>Run it:</p><pre>THIRDS_API_KEY=your_key node chart-to-png-and-pdf.mjs</pre><p>What the test run produced:</p><ul><li>chart.png: 1200 by 630, the grouped bars, legend and title as in the browser.</li><li>report.pdf: one A4 page with the heading, the chart and a six row table. device_scale_factor: 2 in the viewport keeps the chart sharp when you zoom in on the PDF, because a canvas is always a bitmap.</li><li>Running the script a second time sent the same requests with the same idempotency keys and got the same two files back, byte for byte, without new renders.</li><li>A wrong key stops with 401 unauthorized, and a missing key stops before any request.</li></ul><h3>Which one to use</h3><ul><li><strong>A button on a dashboard:</strong> toDataURL() in the browser. Nothing to host and nothing to pay for.</li><li><strong>Scheduled reports and emails, a few a day or a few thousand:</strong> a renderer that runs JavaScript. Self hosting Chrome is fine if you already run it; a hosted API saves you installing and updating a browser on the server.</li><li><strong>Lots of charts with no interaction:</strong> consider drawing them as SVG on the server (many chart libraries can), which needs no browser at all.</li></ul><p>The <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=canvas-chart-to-png-pdf">HTML to PDF API page</a> lists the PDF options used above.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f3cb7349beb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating App Store screenshots across languages and device sizes]]></title>
            <link>https://medium.com/@imvalerian/automating-app-store-screenshots-across-languages-and-device-sizes-2553e33fba91?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/2553e33fba91</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[app-store]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 01:31:29 GMT</pubDate>
            <atom:updated>2026-10-20T01:31:29.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p><strong>Short answer:</strong> split the job in two. Capture raw app screens per language with your UI tests (fastlane snapshot, XCUITest or Maestro), and generate the marketing screenshots (frame, headline, background) from one design with the captions as data. Then a release is one loop: for each language, send the captions and that language’s raw screens, and get back every device size in one request. Pin the design version so a release can be regenerated byte for byte later.</p><p>For 8 languages and 4 sizes that is 8 requests and 32 images per screen, with no manual work in a design tool.</p><h3>Why it gets painful</h3><ul><li><strong>The number multiplies.</strong> Screens x languages x sizes grows fast, and every caption edit means redoing the lot.</li><li><strong>Captions overflow.</strong> German is longer than English, Japanese needs a different font. A layout that fits one language breaks in another.</li><li><strong>Sizes are not just scaled.</strong> An iPad screenshot has a different shape from an iPhone one, so it needs its own arrangement, not a stretched copy.</li></ul><h3>The setup</h3><ol><li><strong>One design per screen, with placeholders</strong> for the headline, subline and the raw screen image. Give each text box a fixed height and let the text shrink to fit, so long translations stay inside the box instead of failing or spilling.</li><li><strong>A saved size per extra device.</strong> The design’s own canvas is the iPhone size; an iPad size is saved on the same design with its own layout tweaks.</li><li><strong>A caption file per language</strong>, kept next to your app’s other localised strings.</li></ol><h3>The script</h3><pre>// Framed, captioned App Store screenshots for every language and device size.<br>// One request per language; each request returns every size. Node 18+.<br>// Usage: THIRDS_API_KEY=... SHOT_TEMPLATE_ID=tpl_... SHOT_TEMPLATE_VERSION=2 node app-store-screenshots.mjs<br>import { mkdir, writeFile } from &#39;node:fs/promises&#39;;<br>import { createHash } from &#39;node:crypto&#39;;</pre><pre>// &#39;original&#39; is the design&#39;s own canvas (iPhone, 1320x2868 here); &#39;ipad-13&#39; is a size<br>// saved on the same design. Add more saved sizes, or a custom size such as &#39;1242x2688&#39;.<br>const SIZES = [&#39;original&#39;, &#39;ipad-13&#39;];</pre><pre>// One entry per language: the captions and the raw capture for that language<br>// (for example from your UI tests). Screen images must be on a public HTTPS address.<br>const languages = {<br>  en: { headline: &#39;Plan your week in a minute&#39;, subline: &#39;Drag tasks onto days and see what fits.&#39;, screenshot: &#39;https://thirds.ai/gallery/campaign-report.webp&#39; },<br>  // de: { headline: &#39;Deine Woche in einer Minute&#39;, subline: &#39;Aufgaben auf Tage ziehen und sehen, was passt.&#39;, screenshot: &#39;https://cdn.example/de/1.png&#39; },<br>  // ja: { headline: &#39;1分で1週間の計画&#39;, subline: &#39;タスクを日付にドラッグするだけ。&#39;, screenshot: &#39;https://cdn.example/ja/1.png&#39; },<br>};</pre><pre>const API = &#39;https://thirds.ai&#39;;<br>// Pin the design version so a later edit in the editor never changes a release&#39;s screenshots.<br>const VERSION = Number(process.env.SHOT_TEMPLATE_VERSION || 1);<br>const headers = { Authorization: `Bearer ${process.env.THIRDS_API_KEY}`, &#39;Content-Type&#39;: &#39;application/json&#39; };<br>await mkdir(&#39;screenshots&#39;, { recursive: true });</pre><pre>for (const [lang, captions] of Object.entries(languages)) {<br>  const body = JSON.stringify({ template_id: process.env.SHOT_TEMPLATE_ID, version: VERSION, format: &#39;png&#39;, sizes: SIZES, data: { lang, ...captions } });<br>  // Same request, same key: a re-run replays the pack instead of paying again.<br>  // New captions or a new version give a new key (the API refuses a reused key with a different request).<br>  const key = `shots-${lang}-${createHash(&#39;sha256&#39;).update(body).digest(&#39;hex&#39;).slice(0, 16)}`;<br>  const res = await fetch(`${API}/v1/image-packs`, { method: &#39;POST&#39;, headers: { ...headers, &#39;Idempotency-Key&#39;: key }, body });<br>  let pack = await res.json();<br>  if (!res.ok) throw new Error(`${lang}: ${JSON.stringify(pack.error)}`);<br>  while (pack.state === &#39;queued&#39; || pack.state === &#39;running&#39;) {<br>    await new Promise((r) =&gt; setTimeout(r, 3000));<br>    pack = await (await fetch(`${API}/v1/image-packs/${pack.id}`, { headers })).json();<br>  }<br>  for (const m of pack.members) {<br>    if (m.state !== &#39;succeeded&#39;) { console.log(lang, m.size_id, &#39;failed&#39;, m.error?.code); continue; }<br>    const png = Buffer.from(await (await fetch(API + m.download_url)).arrayBuffer());<br>    await writeFile(`screenshots/${lang}-${m.size_id}-${m.width}x${m.height}.png`, png);<br>    console.log(lang, m.size_id, `${m.width}x${m.height}`, &#39;saved&#39;);<br>  }<br>}</pre><p>Run it with THIRDS_API_KEY=... SHOT_TEMPLATE_ID=tpl_... SHOT_TEMPLATE_VERSION=2 node app-store-screenshots.mjs. Uncomment the other languages and point their screenshot at your captured screens.</p><p>Two details that matter in a release pipeline:</p><ul><li><strong>Pin the version.</strong> Editing the design later creates a new version, but a release that asks for version 2 keeps getting version 2. You can regenerate an old release exactly.</li><li><strong>Derive the retry key from the request.</strong> The Idempotency-Key is a hash of the request body, so re-running the script after a crash replays what already finished instead of making it again. A fixed key such as shots-en breaks as soon as anything changes, because the API refuses a reused key with a different request. That exact failure showed up while testing this script, which is why it hashes the body.</li></ul><h3>What the test produced</h3><p>With English captions and both sizes, one request returned a 1320 x 2868 iPhone screenshot and a 2064 x 2752 iPad 13 inch screenshot. The first version of the test design failed with a layout overflow error because its text boxes had no fixed height; giving them a height and shrink to fit fixed it, which is the same thing that protects long translations.</p><h3>Upload</h3><p>The files come out named &lt;lang&gt;-&lt;size&gt;-&lt;width&gt;x&lt;height&gt;.png. fastlane deliver expects one folder per locale, so a small rename step (en to en-US, de to de-DE) lets fastlane deliver upload the lot.</p><p>To design the frame and captions without code, there is a <a href="https://thirds.ai/tools/app-store-screenshot-generator?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=localized-app-store-screenshots">free App Store screenshot generator</a> and an <a href="https://thirds.ai/gallery/app-store-screenshot?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=localized-app-store-screenshots">App Store screenshot template</a>; the <a href="https://thirds.ai/docs/api-reference/image-packs?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=localized-app-store-screenshots">image packs reference</a> covers sizes, presets and the response fields used above.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2553e33fba91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to export a popup to PDF exactly as it looks on screen, without clipping]]></title>
            <link>https://medium.com/@imvalerian/how-to-export-a-popup-to-pdf-exactly-as-it-looks-on-screen-without-clipping-35aec2e19ba5?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/35aec2e19ba5</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 01:04:12 GMT</pubDate>
            <atom:updated>2026-10-20T01:04:12.313Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p><strong>Short answer:</strong> clipping happens for two reasons. The popup scrolls inside a fixed height box, so only the visible part gets captured, and the PDF is laid out on a paper sized page that is narrower or shorter than the popup. Fix both: copy the popup into a standalone page where every scrolling box is allowed to grow to its full content, measure its real width and height, and print it to a PDF page of exactly that size with zero margins. The code below does this in two small pieces, one in the browser and one on your server.</p><h3>Why the PDF does not match the screen</h3><ul><li><strong>Inner scrolling.</strong> A popup with max-height and overflow: auto only shows part of its content. A screenshot or print of it shows that part and nothing else.</li><li><strong>Fixed or centred positioning.</strong> position: fixed plus transform: translate(-50%, -50%) places the popup relative to the window. On a printed page that maths changes and the popup gets pushed off the edge.</li><li><strong>Paper size.</strong> A 520 px wide popup laid out on an A4 page with default margins is squeezed or cut. A long popup gets split across pages.</li><li><strong>Screen only styles.</strong> PDFs are made with print media, so anything inside @media screen (often your colours and borders) silently disappears, and background colours are dropped unless you ask to keep them.</li></ul><h3>Step 1: collect the popup in the browser</h3><p>This function copies the element, keeps your stylesheet rules (including the screen only ones), lets inner scrolling boxes grow, takes the popup out of its fixed position, and measures it off screen.</p><pre>// Runs in the browser. Turns one element (a popup, a modal, a card) into a standalone<br>// HTML page plus its full size, so a PDF of it matches the screen with nothing clipped.<br>function elementToPdfPayload(el) {<br>  const css = [];<br>  for (const sheet of document.styleSheets) {<br>    let rules;<br>    try { rules = sheet.cssRules; } catch { if (sheet.href) css.push(`@import url(https://medium.com/&quot;$%7Bsheet.href%7D&quot;);`); continue; } // cross origin sheet<br>    for (const rule of rules) {<br>      // A PDF is made with print media, so screen only rules would be dropped. Keep them.<br>      if (rule instanceof CSSMediaRule &amp;&amp; /^\s*(only\s+)?screen\s*$/i.test(rule.media.mediaText)) {<br>        for (const inner of rule.cssRules) css.push(inner.cssText);<br>      } else {<br>        css.push(rule.cssText);<br>      }<br>    }<br>  }<br>  const clone = el.cloneNode(true);<br>  // A popup usually scrolls inside a fixed height box. Let every scrolling box grow to its content.<br>  const originals = [el, ...el.querySelectorAll(&#39;*&#39;)];<br>  const copies = [clone, ...clone.querySelectorAll(&#39;*&#39;)];<br>  originals.forEach((node, i) =&gt; {<br>    const s = getComputedStyle(node);<br>    if (/(auto|scroll|hidden)/.test(s.overflowY) &amp;&amp; node.scrollHeight &gt; node.clientHeight) {<br>      copies[i].style.setProperty(&#39;max-height&#39;, &#39;none&#39;, &#39;important&#39;);<br>      copies[i].style.setProperty(&#39;height&#39;, &#39;auto&#39;, &#39;important&#39;);<br>      copies[i].style.setProperty(&#39;overflow&#39;, &#39;visible&#39;, &#39;important&#39;);<br>    }<br>  });<br>  // Take the popup out of its fixed or centred position.<br>  clone.style.setProperty(&#39;position&#39;, &#39;static&#39;, &#39;important&#39;);<br>  clone.style.setProperty(&#39;transform&#39;, &#39;none&#39;, &#39;important&#39;);<br>  clone.style.setProperty(&#39;margin&#39;, &#39;0&#39;, &#39;important&#39;);<br>  const width = Math.ceil(el.getBoundingClientRect().width);<br>  // Measure the grown clone off screen at the same width, then take it out again.<br>  const probe = document.createElement(&#39;div&#39;);<br>  probe.style.cssText = `position:absolute;left:-100000px;top:0;width:${width}px`;<br>  probe.appendChild(clone);<br>  document.body.appendChild(probe);<br>  const height = Math.ceil(clone.getBoundingClientRect().height) + 2;<br>  probe.remove();<br>  // Relative image and font paths keep working through &lt;base&gt;. The renderer only loads public<br>  // HTTPS assets, so the base is added only when the page itself is served over HTTPS.<br>  const base = location.protocol === &#39;https:&#39; ? `&lt;base href=&quot;${location.href}&quot;&gt;` : &#39;&#39;;<br>  const html = `&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;${base}&lt;style&gt;<br>    html, body { margin: 0; width: ${width}px; background: ${getComputedStyle(document.body).backgroundColor}; }<br>    * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }<br>    ${css.join(&#39;\n&#39;)}<br>  &lt;/style&gt;&lt;/head&gt;&lt;body&gt;${clone.outerHTML}&lt;/body&gt;&lt;/html&gt;`;<br>  return { html, width, height };<br>}<br>// In your click handler:<br>// fetch(&#39;/api/element-pdf&#39;, { method: &#39;POST&#39;, headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>//   body: JSON.stringify(elementToPdfPayload(document.querySelector(&#39;#quote-popup&#39;))) })</pre><p>Cross origin stylesheets cannot be read from script, so they are pulled in with @import instead. Images and fonts need to be on public HTTPS addresses for the renderer to load them; relative paths work because the function adds a &lt;base&gt; tag when the page is served over HTTPS.</p><h3>Step 2: print it at its own size on the server</h3><p>Keep your API key on the server. This takes the payload from step 1 and asks for a single page PDF exactly the size of the popup, with backgrounds kept.</p><pre>// Server side (Node 18+): one tall page exactly the size of the element, no margins.<br>// Keep the key on the server. Call makeElementPdf({ html, width, height }) from your route.<br>export async function makeElementPdf({ html, width, height }) {<br>  const headers = { Authorization: `Bearer ${process.env.THIRDS_API_KEY}`, &#39;Content-Type&#39;: &#39;application/json&#39; };<br>  const res = await fetch(&#39;https://thirds.ai/v1/pdf&#39;, {<br>    method: &#39;POST&#39;,<br>    headers,<br>    body: JSON.stringify({<br>      html,<br>      viewport: { width: Math.max(320, width), height: 720 }, // lay out at the on screen width<br>      pdf: { width: `${width}px`, height: `${height}px`, margins: { top: &#39;0px&#39;, right: &#39;0px&#39;, bottom: &#39;0px&#39;, left: &#39;0px&#39; }, print_background: true },<br>    }),<br>  });<br>  let job = await res.json();<br>  if (!res.ok) throw new Error(JSON.stringify(job.error));<br>  while (job.status === &#39;queued&#39; || job.status === &#39;running&#39;) {<br>    await new Promise((r) =&gt; setTimeout(r, 1500));<br>    job = await (await fetch(`https://thirds.ai/v1/pdf/${job.id}`, { headers })).json();<br>  }<br>  if (job.status !== &#39;succeeded&#39;) throw new Error(`${job.status} ${JSON.stringify(job.error)}`);<br>  const file = await fetch(`https://thirds.ai${job.download.url}`);<br>  return Buffer.from(await file.arrayBuffer());<br>}</pre><p>Wire it to a route (for example POST /api/element-pdf) and return the buffer with Content-Type: application/pdf.</p><h3>What the test showed</h3><p>The two pieces were run together against a test page with a centred, fixed position popup: a 520 px wide quote whose body was capped at 320 px with overflow-y: auto, holding 25 rows and a total underneath, with its colours set inside @media screen.</p><ul><li>On screen the scroll box showed 338 of its 997 px of content.</li><li>The collector returned a page 520 px wide and 1065 px tall.</li><li>The PDF came back as one page of exactly that size, with all 25 rows, the total line at the bottom, and the screen only colours intact.</li></ul><h3>Common snags</h3><ul><li><strong>Web fonts look different.</strong> Load them from a public HTTPS URL in your CSS so the renderer can fetch them; local or blob URLs will not load.</li><li><strong>Very tall popups.</strong> A single page can be tall, but if you want A4 pages instead, drop the custom width and height, use format: &#39;A4&#39;, and add break-inside: avoid to rows as you would for any multi page document.</li><li><strong>Canvas and video.</strong> A &lt;canvas&gt; copies as an empty box. Swap it for an &lt;img&gt; of canvas.toDataURL() in the clone before sending.</li><li><strong>Builder apps.</strong> In Bubble or similar tools, run the collector from a “run JavaScript” action and send the result to a backend workflow or API connector call that holds the key.</li></ul><p>The <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=export-popup-to-pdf-without-clipping">HTML to PDF API page</a> lists the other PDF options (custom page sizes in px, in, cm or mm, margins, print_background, scale and landscape).</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35aec2e19ba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to give every page its own Open Graph image, generated automatically]]></title>
            <link>https://medium.com/@imvalerian/how-to-give-every-page-its-own-open-graph-image-generated-automatically-b175c46f2253?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/b175c46f2253</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[open-graph]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 00:37:04 GMT</pubDate>
            <atom:updated>2026-10-20T00:37:04.116Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p><strong>Short answer:</strong> social platforms read one tag, og:image, from the HTML their crawler fetches, and the crawler does not run your JavaScript. So you cannot swap the image in the browser. You need a real image file per page, at a stable public URL, written into the server rendered &lt;head&gt;. The simplest dependable way is to generate that image when the page&#39;s content is saved (not when someone shares it), store it, and put its URL in the meta tags. Change the file name when the content changes so cached previews refresh.</p><h3>Why the dynamic image does not show up</h3><ul><li><strong>Crawlers do not run scripts.</strong> Facebook, LinkedIn, Slack, iMessage and X fetch the raw HTML. If your meta tags are set by client side code, or by a single page app after load, they see the default image or nothing.</li><li><strong>The URL is not public or not direct.</strong> og:image must be an absolute HTTPS URL that returns the image itself, with no login and no redirect chain to a page.</li><li><strong>Caching.</strong> Platforms cache the image by URL, sometimes for weeks. Updating the file behind the same URL often has no visible effect. A new URL does.</li><li><strong>Size.</strong> 1200 x 630 px is the safe choice for a large preview card on every major platform.</li></ul><h3>Generate the image when the content is saved</h3><p>The script below takes one product, renders a 1200 x 630 PNG from a saved design with the product’s name and summary filled in, stores it under a name that includes a short hash of the content, and prints the meta tags for the product page.</p><pre>// Make one Open Graph image per product when the product is saved, store it,<br>// and print the meta tags for the product page. Node 18+.<br>// Usage: THIRDS_API_KEY=... OG_TEMPLATE_ID=tpl_... node og-image-per-product.mjs<br>import { mkdir, writeFile } from &#39;node:fs/promises&#39;;<br>import { createHash } from &#39;node:crypto&#39;;</pre><pre>const product = {<br>  slug: &#39;linen-apron-sage&#39;,<br>  name: &#39;Linen apron, sage&#39;,<br>  summary: &#39;Stonewashed linen with deep pockets and an adjustable neck strap.&#39;,<br>  url: &#39;https://shop.example/products/linen-apron-sage&#39;,<br>};</pre><pre>const data = {<br>  site_name: &#39;Hearth &amp; Loom&#39;,<br>  page_title: product.name,<br>  description: product.summary,<br>  site_url: &#39;shop.example&#39;,<br>};<br>// The file name changes when the content changes, so platforms that cache by URL pick up the new image.<br>const version = createHash(&#39;sha256&#39;).update(JSON.stringify(data)).digest(&#39;hex&#39;).slice(0, 10);</pre><pre>const headers = { Authorization: `Bearer ${process.env.THIRDS_API_KEY}`, &#39;Content-Type&#39;: &#39;application/json&#39; };<br>const res = await fetch(&#39;https://thirds.ai/v1/image&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: { ...headers, &#39;Idempotency-Key&#39;: `og-${product.slug}-${version}` },<br>  body: JSON.stringify({ template_id: process.env.OG_TEMPLATE_ID, data, image: { format: &#39;png&#39; }, filename: `og-${product.slug}` }),<br>});<br>let job = await res.json();<br>if (!res.ok) throw new Error(JSON.stringify(job.error));<br>while (job.status === &#39;queued&#39; || job.status === &#39;running&#39;) {<br>  await new Promise((r) =&gt; setTimeout(r, 1500));<br>  job = await (await fetch(`https://thirds.ai/v1/image/${job.id}`, { headers })).json();<br>}<br>if (job.status !== &#39;succeeded&#39;) throw new Error(`${job.status} ${JSON.stringify(job.error)}`);</pre><pre>// The download link lasts 15 minutes, so copy the file to storage you control (here: ./public/og).<br>const png = Buffer.from(await (await fetch(`https://thirds.ai${job.download.url}`)).arrayBuffer());<br>await mkdir(&#39;public/og&#39;, { recursive: true });<br>const file = `og/${product.slug}-${version}.png`;<br>await writeFile(`public/${file}`, png);</pre><pre>console.log(`&lt;meta property=&quot;og:title&quot; content=&quot;${product.name}&quot;&gt;<br>&lt;meta property=&quot;og:description&quot; content=&quot;${product.summary}&quot;&gt;<br>&lt;meta property=&quot;og:url&quot; content=&quot;${product.url}&quot;&gt;<br>&lt;meta property=&quot;og:image&quot; content=&quot;https://shop.example/${file}&quot;&gt;<br>&lt;meta property=&quot;og:image:width&quot; content=&quot;1200&quot;&gt;<br>&lt;meta property=&quot;og:image:height&quot; content=&quot;630&quot;&gt;<br>&lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;`);</pre><p>Run it with THIRDS_API_KEY=... OG_TEMPLATE_ID=tpl_... node og-image-per-product.mjs. In a real app, call the same code from whatever runs when a product or post is saved: a CMS webhook, a database trigger, or a backend workflow.</p><p>What it does for you:</p><ul><li><strong>Stable and cache friendly.</strong> The file name includes a hash of the text on the card, so a title change gives a new URL and platforms fetch the new image, while an unchanged product keeps its URL.</li><li><strong>No double work.</strong> The same hash goes into the Idempotency-Key, so saving a product twice without changing the text returns the existing image instead of making a new one.</li><li><strong>Your storage, your URL.</strong> The download link from the API lasts 15 minutes, so the script copies the file to public/og/. Swap that for S3, R2, Supabase storage or your platform&#39;s file store.</li></ul><p>When this was run against the live API it produced a 1200 x 630 PNG for the “Linen apron, sage” product.</p><h3>Put the tags in the server rendered head</h3><p>Use the printed tags in the page template your server sends. In Next.js that is generateMetadata; in a static site it is the page&#39;s front matter; in Bubble it is the page&#39;s SEO settings with a dynamic image field pointing at the stored file. Then check the result with the platforms&#39; own tools (the Facebook Sharing Debugger and LinkedIn Post Inspector both show what their crawler sees and let you refresh the cache).</p><h3>The design</h3><p>You need one design with placeholders for the text. You can build one in the <a href="https://thirds.ai/tools/open-graph-image-generator?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=dynamic-open-graph-image-per-page">free Open Graph image generator</a> or start from the <a href="https://thirds.ai/gallery/open-graph-card?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=dynamic-open-graph-image-per-page">Open Graph card template</a>, then save it to get the template ID used above.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b175c46f2253" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn an order paid webhook into a PDF receipt in Zapier]]></title>
            <link>https://medium.com/@imvalerian/turn-an-order-paid-webhook-into-a-pdf-receipt-in-zapier-1100276f038e?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/1100276f038e</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[zapier]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 00:09:09 GMT</pubDate>
            <atom:updated>2026-10-20T00:09:09.417Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>When your shop or form sends an “order paid” webhook, a Zap can turn it into a PDF receipt with line items, tax and a Paid stamp, and hand it to the next step, such as Gmail or Google Drive. This recipe uses only Zapier’s own building blocks, plus a small test script that replays the whole thing with curl and a mocked payload, so you can check your design before you connect a real shop.</p><p><strong>1. Trigger: Webhooks by Zapier &gt; Catch Raw Hook.</strong> Copy the URL into your shop’s webhook settings for paid orders. Catch Raw Hook keeps the body as one string, so line items arrive intact instead of being flattened into comma lists. The code below expects a payload shaped like this one:</p><pre>{<br>  &quot;event&quot;: &quot;order.paid&quot;,<br>  &quot;order&quot;: {<br>    &quot;number&quot;: &quot;1047&quot;,<br>    &quot;paid_at&quot;: &quot;2026-10-18T14:05:12Z&quot;,<br>    &quot;currency&quot;: &quot;GBP&quot;,<br>    &quot;customer&quot;: {&quot;name&quot;: &quot;Tomasz Wilk&quot;, &quot;email&quot;: &quot;tomasz.wilk@example.com&quot;},<br>    &quot;payment&quot;: {&quot;brand&quot;: &quot;Mastercard&quot;, &quot;last4&quot;: &quot;0921&quot;},<br>    &quot;tax_rate&quot;: 0.2,<br>    &quot;lines&quot;: [<br>      {&quot;title&quot;: &quot;Ceramic pour-over set, sand&quot;, &quot;quantity&quot;: 1, &quot;unit_price&quot;: 3800},<br>      {&quot;title&quot;: &quot;Single-origin beans, 250 g&quot;, &quot;quantity&quot;: 2, &quot;unit_price&quot;: 1150},<br>      {&quot;title&quot;: &quot;Paper filters, pack of 100&quot;, &quot;quantity&quot;: 1, &quot;unit_price&quot;: 450}<br>    ]<br>  }<br>}</pre><p><strong>2. Code by Zapier &gt; Run JavaScript.</strong> Add one Input Data field, raw_body, mapped to the trigger&#39;s Raw Body. Paste the code below and change BUSINESS (your name, address, email, note, footer and Template ID). It turns prices in pence or cents into pounds or dollars, works out line totals, subtotal, tax and total, and gives you body, idempotency_key, receipt_number and customer_email.</p><pre>// Code by Zapier (JavaScript) step for a &quot;Catch Raw Hook&quot; trigger.<br>// Input Data: raw_body = the trigger&#39;s Raw Body.<br>// Output: body (the JSON to send to thirds.ai), idempotency_key, receipt_number, customer_email.<br>// Prices in the payload are in pence/cents; this turns them into pounds/dollars.<br>// Business details below are yours to change.<br>const BUSINESS = {<br>  business_name: &#39;Your shop name&#39;,<br>  business_address: &#39;1 High Street, Your Town AB1 2CD&#39;,<br>  business_email: &#39;hello@yourshop.example&#39;,<br>  note: &#39;Thanks for your order. Keep this receipt for returns within 30 days.&#39;,<br>  footer: &#39;Your shop name Ltd, 1 High Street, Your Town AB1 2CD&#39;,<br>  template_id: &#39;tpl_PASTE_YOUR_TEMPLATE_ID&#39;,<br>};</pre><pre>const order = JSON.parse(inputData.raw_body).order;<br>const money = minor =&gt; Math.round(minor) / 100;<br>const items = order.lines.slice(0, 12).map(l =&gt; ({<br>  description: String(l.title).slice(0, 120),<br>  quantity: l.quantity,<br>  amount: money(l.unit_price * l.quantity), // the receipt design shows line totals<br>}));<br>const subtotal = money(order.lines.reduce((s, l) =&gt; s + l.unit_price * l.quantity, 0));<br>const tax = Math.round(subtotal * order.tax_rate * 100) / 100;<br>const receiptNumber = `R-${order.number}`;</pre><pre>output = {<br>  receipt_number: receiptNumber,<br>  customer_email: order.customer.email,<br>  // Same order gives the same key, so a Zapier replay never pays twice.<br>  idempotency_key: `zap-receipt-${order.number}`,<br>  body: JSON.stringify({<br>    template_id: BUSINESS.template_id,<br>    filename: `receipt-${order.number}`,<br>    data: {<br>      business_name: BUSINESS.business_name,<br>      business_address: BUSINESS.business_address,<br>      business_email: BUSINESS.business_email,<br>      customer_name: order.customer.name,<br>      customer_email: order.customer.email,<br>      receipt_number: receiptNumber,<br>      paid_on: order.paid_at.slice(0, 10), // YYYY-MM-DD<br>      payment_method: `${order.payment.brand} ending ${order.payment.last4}`,<br>      stamp: &#39;Paid&#39;,<br>      items,<br>      subtotal,<br>      tax_label: `VAT ${Math.round(order.tax_rate * 100)}%`,<br>      tax,<br>      total: Math.round((subtotal + tax) * 100) / 100,<br>      note: BUSINESS.note,<br>      footer: BUSINESS.footer,<br>    },<br>  }),<br>};</pre><p><strong>3. Webhooks by Zapier &gt; Custom Request.</strong> Method POST, URL https://thirds.ai/v1/pdf, Data: map body from step 2. Headers: Authorization = Bearer YOUR_API_KEY, Content-Type = application/json, Idempotency-Key = map idempotency_key. The answer usually already says status: succeeded.</p><p><strong>4. Filter by Zapier.</strong> Only continue if Status (text) exactly matches succeeded. For very large files, use Paths instead: on queued or running, add Delay by Zapier (a few seconds) and a GET Custom Request to https://thirds.ai/v1/pdf/ plus the Id, with the same Authorization header.</p><p><strong>5. Gmail &gt; Send Email (or Google Drive &gt; Upload File).</strong> In the attachment field, type https://thirds.ai and then map Download Url right after it. Zapier fetches the PDF from that signed link (no key needed, valid 15 minutes).</p><p><strong>Test it before you connect a shop.</strong> Save the payload above as zapier-receipt-mock-payload.json and the code as zapier-receipt-code-step.js, then run THIRDS_API_KEY=... TEMPLATE_ID=tpl_... ./zapier-receipt-test.sh. It runs the Code step in Node with the mocked payload, sends the same request as step 3 with curl, and saves the PDF.</p><pre>#!/usr/bin/env bash<br># Replays the Zap with curl: mocked webhook payload -&gt; Code step -&gt; render -&gt; download.<br># Usage: THIRDS_API_KEY=... TEMPLATE_ID=tpl_... ./zapier-receipt-test.sh<br>set -euo pipefail<br>cd &quot;$(dirname &quot;$0&quot;)&quot;<br># 1. Code by Zapier step, run in node with the same inputData Zapier gives it.<br>node -e &#39;<br>const fs=require(&quot;fs&quot;); const inputData={raw_body: fs.readFileSync(&quot;zapier-receipt-mock-payload.json&quot;,&quot;utf8&quot;)}; let output;<br>eval(fs.readFileSync(&quot;zapier-receipt-code-step.js&quot;,&quot;utf8&quot;));<br>const b=JSON.parse(output.body); b.template_id=process.env.TEMPLATE_ID||b.template_id; output.body=JSON.stringify(b);<br>fs.writeFileSync(&quot;/tmp/zap-step.json&quot;, JSON.stringify(output));&#39;<br>BODY=$(node -p &#39;require(&quot;/tmp/zap-step.json&quot;).body&#39;)<br>IDEM=$(node -p &#39;require(&quot;/tmp/zap-step.json&quot;).idempotency_key&#39;)<br># 2. Webhooks by Zapier, Custom Request: POST https://thirds.ai/v1/pdf<br>curl -sS -X POST https://thirds.ai/v1/pdf \<br>  -H &quot;Authorization: Bearer $THIRDS_API_KEY&quot; -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Idempotency-Key: $IDEM&quot; --data-binary &quot;$BODY&quot; -o /tmp/zap-job.json<br>STATUS=$(node -p &#39;require(&quot;/tmp/zap-job.json&quot;).status&#39;)<br>ID=$(node -p &#39;require(&quot;/tmp/zap-job.json&quot;).id&#39;)<br># 3. Only while it is still rendering: Delay by Zapier, then GET the status again.<br>for i in 1 2 3 4 5 6 7 8 9 10; do<br>  [ &quot;$STATUS&quot; = queued ] || [ &quot;$STATUS&quot; = running ] || break<br>  sleep 3<br>  curl -sS &quot;https://thirds.ai/v1/pdf/$ID&quot; -H &quot;Authorization: Bearer $THIRDS_API_KEY&quot; -o /tmp/zap-job.json<br>  STATUS=$(node -p &#39;require(&quot;/tmp/zap-job.json&quot;).status&#39;)<br>done<br>[ &quot;$STATUS&quot; = succeeded ] || { echo &quot;render $STATUS: $(node -p &#39;JSON.stringify(require(&quot;/tmp/zap-job.json&quot;).error)&#39;)&quot;; exit 1; }<br># 4. The file: Gmail or Drive steps take https://thirds.ai + download.url as the attachment.<br>URL=&quot;https://thirds.ai$(node -p &#39;require(&quot;/tmp/zap-job.json&quot;).download.url&#39;)&quot;<br>curl -sS &quot;$URL&quot; -o zapier-webhook-receipt.sample.pdf<br>echo &quot;ok $ID -&gt; zapier-webhook-receipt.sample.pdf&quot;</pre><p><strong>How it was tested.</strong> That test script was run against the live API with the payload above. The prices came out in pounds, the line total for 2 x £11.50 was £23.00, the subtotal £65.50, VAT at 20% £13.10, the total £78.60 and the paid date 2026–10–18, all correct on the PDF. It has not been built as a real Zap, so check each step’s mapping in Zapier’s test panel.</p><p><strong>Good to know</strong></p><ol><li>The payment receipt design shows line totals, so amount is quantity times unit price, not the unit price.</li><li>A Zapier replay sends the same Idempotency-Key, so the same order is never charged twice.</li><li>The key in a Custom Request header is visible to anyone who can edit the Zap. If you would rather keep it in a Zapier connection, the <a href="https://thirds.ai/integrations/zapier?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-zapier-receipts">thirds.ai Zapier app</a> does steps 3 to 5 for you; it is private for now and you join it from an invite link.</li><li>Each finished PDF costs one credit, a failed one costs nothing, and a free thirds.ai account gets 50 credits a month.</li></ol><p>Start from the <a href="https://thirds.ai/gallery/payment-receipt?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-zapier-receipts">Payment receipt design</a>.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1100276f038e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make a PDF certificate for each row in Google Sheets with Apps Script]]></title>
            <link>https://medium.com/@imvalerian/make-a-pdf-certificate-for-each-row-in-google-sheets-with-apps-script-8f806de7857f?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f806de7857f</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 22:07:12 GMT</pubDate>
            <atom:updated>2026-10-19T17:23:02.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>Course certificates are a good fit for a spreadsheet: one row per learner, and a PDF for each row. This guide adds a Certificates menu to Google Sheets. Pick Certificates &gt; Make PDFs for new rows, and each new row gets a PDF certificate saved in Drive, a link to it in the sheet and, if you want, an email to the learner with the PDF attached. Rows that already have a link are skipped, so you can run it as often as you like.</p><p><strong>1. Set up the sheet.</strong> Make a sheet named Learners with these headers in row 1: learner, email, course, date, certificate, status. Write the date the way you want it printed, for example 18 October 2026.</p><p><strong>2. Pick the design.</strong> On thirds.ai, open the <a href="https://thirds.ai/gallery/completion-certificate?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-sheets-certificates">Portrait course certificate</a>, save it and copy its Template ID. Make an API key.</p><p><strong>3. Paste the script.</strong> In the sheet, open Extensions &gt; Apps Script, delete the sample code, paste the script below and save.</p><pre>/**<br> * Google Sheets: make a PDF certificate for each row with thirds.ai,<br> * save it to Drive, and (optionally) email it.<br> *<br> * Sheet &quot;Learners&quot;, row 1 headers: learner | email | course | date | certificate | status<br> * Script properties (Project Settings &gt; Script properties):<br> *   THIRDS_API_KEY  your key (starts with thirds_sk_)<br> *   TEMPLATE_ID     tpl_... of your saved certificate design<br> *   ISSUER          the name printed as the issuer<br> *   FOLDER_ID       (optional) Drive folder for the PDFs; blank saves to My Drive<br> *   SEND_EMAIL      (optional) &quot;yes&quot; to email each learner their PDF<br> * Each finished PDF costs one credit; a failed one is free.<br> *<br> * Apps Script stops a run at 6 minutes. This script stops starting new rows after<br> * about 4.5 minutes so the current row can finish. Rows already marked Done (or<br> * with a certificate link) are skipped, so run the menu again (or use the<br> * optional time-driven trigger) to continue the batch. The sheet is updated<br> * before any email is sent, so a rerun never double-sends.<br> */<br><br>var API = &#39;https://thirds.ai&#39;;<br>var RUN_BUDGET_MS = 4.5 * 60 * 1000;<br>var POLL_TIMEOUT_MS = 60000;<br><br>function onOpen() {<br>  SpreadsheetApp.getUi().createMenu(&#39;Certificates&#39;)<br>    .addItem(&#39;Make PDFs for new rows&#39;, &#39;makeCertificates&#39;)<br>    .addItem(&#39;Install continue trigger (every 10 min)&#39;, &#39;installContinueTrigger&#39;)<br>    .addToUi();<br>}<br><br>function makeCertificates() {<br>  var started = Date.now();<br>  var props = PropertiesService.getScriptProperties();<br>  var key = props.getProperty(&#39;THIRDS_API_KEY&#39;);<br>  var templateId = props.getProperty(&#39;TEMPLATE_ID&#39;);<br>  if (!key || !templateId) throw new Error(&#39;Set THIRDS_API_KEY and TEMPLATE_ID in Script properties.&#39;);<br>  var issuer = props.getProperty(&#39;ISSUER&#39;) || &#39;Your organisation&#39;;<br>  var folderId = props.getProperty(&#39;FOLDER_ID&#39;);<br>  var folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder();<br>  var sendEmail = (props.getProperty(&#39;SEND_EMAIL&#39;) || &#39;&#39;).toLowerCase() === &#39;yes&#39;;<br><br>  var sheet = SpreadsheetApp.getActive().getSheetByName(&#39;Learners&#39;);<br>  var values = sheet.getDataRange().getDisplayValues();<br>  var head = values[0].map(function (h) { return String(h).trim().toLowerCase(); });<br>  var col = function (name) {<br>    var i = head.indexOf(name);<br>    if (i &lt; 0) throw new Error(&#39;Missing column: &#39; + name);<br>    return i;<br>  };<br>  var c = {learner: col(&#39;learner&#39;), email: col(&#39;email&#39;), course: col(&#39;course&#39;), date: col(&#39;date&#39;),<br>           certificate: col(&#39;certificate&#39;), status: col(&#39;status&#39;)};<br><br>  for (var r = 1; r &lt; values.length; r++) {<br>    if (Date.now() - started &gt; RUN_BUDGET_MS) {<br>      // Leave remaining rows for the next run (menu or trigger).<br>      break;<br>    }<br>    var row = values[r];<br>    if (!row[c.learner]) continue;<br>    var statusText = String(row[c.status] || &#39;&#39;);<br>    if (row[c.certificate] || /^Done\b/i.test(statusText)) continue;<br>    var rowNumber = r + 1;<br>    try {<br>      sheet.getRange(rowNumber, c.status + 1).setValue(&#39;In progress&#39;);<br>      SpreadsheetApp.flush();<br><br>      var job = callApi_(key, &#39;post&#39;, &#39;/v1/pdf&#39;, {<br>        template_id: templateId,<br>        data: {issuer: issuer, learner: row[c.learner], course: row[c.course], date: row[c.date]},<br>        filename: &#39;certificate-&#39; + rowNumber<br>      }, &#39;sheets-cert-&#39; + sheet.getSheetId() + &#39;-&#39; + rowNumber + &#39;-&#39; + row[c.email]);<br>      var deadline = Date.now() + POLL_TIMEOUT_MS;<br>      while (job.status === &#39;queued&#39; || job.status === &#39;running&#39;) {<br>        if (Date.now() &gt; deadline) throw new Error(&#39;still &#39; + job.status + &#39;, run again to pick it up&#39;);<br>        Utilities.sleep(2000);<br>        job = callApi_(key, &#39;get&#39;, &#39;/v1/pdf/&#39; + job.id);<br>      }<br>      if (job.status !== &#39;succeeded&#39;) throw new Error(job.status + &#39; &#39; + JSON.stringify(job.error));<br>      // The signed link needs no key and lasts 15 minutes.<br>      var pdf = UrlFetchApp.fetch(API + job.download.url).getBlob()<br>        .setName(&#39;Certificate - &#39; + row[c.learner] + &#39;.pdf&#39;);<br>      var file = folder.createFile(pdf);<br><br>      // Write the sheet before email so a timeout mid-send never double-sends on rerun.<br>      sheet.getRange(rowNumber, c.certificate + 1).setValue(file.getUrl());<br>      sheet.getRange(rowNumber, c.status + 1).setValue(&#39;Done &#39; + job.id);<br>      SpreadsheetApp.flush();<br><br>      if (sendEmail &amp;&amp; row[c.email]) {<br>        MailApp.sendEmail({to: row[c.email], subject: &#39;Your certificate for &#39; + row[c.course],<br>          body: &#39;Hi &#39; + row[c.learner] + &#39;,\n\nWell done on finishing the course. Your certificate is attached.&#39;,<br>          attachments: [pdf]});<br>      }<br>    } catch (e) {<br>      sheet.getRange(rowNumber, c.status + 1).setValue(&#39;Error: &#39; + e.message);<br>      SpreadsheetApp.flush();<br>    }<br>  }<br>}<br><br>/** Optional: keep processing remaining rows every 10 minutes until the sheet is done. */<br>function installContinueTrigger() {<br>  var triggers = ScriptApp.getProjectTriggers();<br>  for (var i = 0; i &lt; triggers.length; i++) {<br>    if (triggers[i].getHandlerFunction() === &#39;makeCertificates&#39;) {<br>      ScriptApp.deleteTrigger(triggers[i]);<br>    }<br>  }<br>  ScriptApp.newTrigger(&#39;makeCertificates&#39;).timeBased().everyMinutes(10).create();<br>}<br><br>function callApi_(key, method, path, body, idemKey) {<br>  var options = {method: method, muteHttpExceptions: true, headers: {Authorization: &#39;Bearer &#39; + key}};<br>  if (body) {<br>    options.contentType = &#39;application/json&#39;;<br>    options.payload = JSON.stringify(body);<br>    // Same row and same data gives the same key, so running the menu twice never pays twice.<br>    options.headers[&#39;Idempotency-Key&#39;] = idemKey;<br>  }<br>  var res = UrlFetchApp.fetch(API + path, options);<br>  var json = JSON.parse(res.getContentText());<br>  if (res.getResponseCode() &gt;= 400) throw new Error(res.getResponseCode() + &#39; &#39; + (json.error ? json.error.code + &#39;: &#39; + json.error.message : &#39;&#39;));<br>  return json;<br>}</pre><p><strong>4. Add the settings.</strong> In Apps Script, open Project Settings (the gear) &gt; Script properties and add THIRDS_API_KEY and TEMPLATE_ID. Optional: ISSUER (the name printed as the issuer), FOLDER_ID (a Drive folder ID; blank saves to My Drive) and SEND_EMAIL set to yes.</p><p>5. Run it. Reload the sheet and a Certificates menu appears. The first run asks you to allow the script to read the sheet, make files in Drive, connect to an external service and (with SEND_EMAIL) send email as you. Then pick Certificates &gt; Make PDFs for new rows. For a long list, run it again later or use Certificates &gt; Install continue trigger (every 10 min); finished rows are skipped.</p><p>How it was tested. The updated file passed a Node syntax check with Apps Script stubs: already-done rows were skipped, the certificate link and Done status were written before any email, and only unfinished rows were emailed. It has not been run in real Google Apps Script, which needs a Google account to authorise it, so try it on a test sheet first.</p><p><strong>Good to know</strong></p><ol><li>Script properties keep the key out of the code, but anyone who can edit the script can read them. Share the sheet as a viewer or commenter if that matters.</li><li>Every request uses muteHttpExceptions, so a bad row writes Error: ... in its status cell and the next row still runs.</li><li>The retry key is the sheet, the row and the email, so running the menu twice never charges twice for the same learner.</li><li>Each finished PDF costs one credit, a failed one costs nothing, and a free thirds.ai account gets 50 credits a month. Gmail and Drive have their own daily limits; check them before a big batch.</li></ol><p>Update (19 Oct 2026). A reader pointed out that Apps Script stops a run at 6 minutes and that the email went out before the sheet was updated. The script now stops starting new rows after about 4.5 minutes, skips rows already marked Done (or that already have a certificate link), writes the Drive link and Done status before any email, shortens the per-row poll timeout to 60 seconds, and adds an optional Certificates &gt; Install continue trigger menu item that reruns every 10 minutes.</p><p>Want one certificate without a sheet? Try the <a href="https://thirds.ai/tools/certificate-generator?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-sheets-certificates">free certificate maker</a>.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f806de7857f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make an invoice PDF for every Airtable record with the Scripting extension]]></title>
            <link>https://medium.com/@imvalerian/make-an-invoice-pdf-for-every-airtable-record-with-the-scripting-extension-c9e6860a5c2e?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e6860a5c2e</guid>
            <category><![CDATA[airtable]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[invoice]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 21:41:01 GMT</pubDate>
            <atom:updated>2026-10-18T21:41:01.573Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>If your invoices live in Airtable, you can turn each invoice record into a PDF and attach it to the same record without leaving the base. This guide uses Airtable’s Scripting extension and one script. For every record in a view that has no file in its attachment field yet, the script sends the invoice details to a saved invoice design on thirds.ai, waits for the PDF and attaches it to the record.</p><p>Line items come from one long text field, one line per item, written as Description | 120.00. The script adds them up, works out the tax from a tax rate field and fills in the totals, so the PDF always matches the record.</p><p><strong>1. Pick the invoice design.</strong> On thirds.ai, open the <a href="https://thirds.ai/gallery/client-invoice?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-airtable-invoices">Client invoice design</a>, save it to your account and copy its Template ID. Change the colours, logo and currency there; the script only fills it in. Then make an API key and keep it for this base only.</p><p><strong>2. Add the fields.</strong> In your Invoices table, add: Invoice number (text), Client name, Client email, Issued on (date), Items (long text), Tax rate (percent or number), Invoice PDF (attachment) and PDF status (text). An Items cell looks like this:</p><pre>Site survey and measured drawings | 1250.00<br>Planning drawings, two rounds | 980.00<br>Printing, A1 boards x4 | 64.50</pre><p><strong>3. Paste the script.</strong> Open Extensions, add Scripting and paste the script below. Open its settings panel (the gear), pick the table, the view and each field, and fill in the key, the Template ID, your business name and email, the payment terms and the payment note. {number} in the note becomes the invoice number.</p><pre>// Airtable scripting extension: make one invoice PDF per record with thirds.ai<br>// and attach it to the record. Each finished PDF costs one credit; a failed one is free.<br>//<br>// Table fields used (rename them in the settings panel):<br>//   Invoice number (text), Client name (text), Client email (email),<br>//   Issued on (date), Items (long text, one line per item: &quot;Description | 120.00&quot;),<br>//   Tax rate (percent or number, e.g. 20 for 20%), Invoice PDF (attachment), PDF status (text)<br>// Records that already have a file in Invoice PDF are skipped.<br><br>const settings = input.config({<br>    title: &#39;Invoice PDFs with thirds.ai&#39;,<br>    description: &#39;Fills a saved thirds.ai invoice design with each record and attaches the PDF.&#39;,<br>    items: [<br>        input.config.text(&#39;apiKey&#39;, {label: &#39;thirds.ai API key&#39;, description: &#39;Starts with thirds_sk_. Anyone who can edit this extension can see it, so use a key made only for this base.&#39;}),<br>        input.config.text(&#39;templateId&#39;, {label: &#39;Template ID&#39;, description: &#39;tpl_... of your saved invoice design&#39;}),<br>        input.config.text(&#39;businessName&#39;, {label: &#39;Your business name&#39;}),<br>        input.config.text(&#39;businessEmail&#39;, {label: &#39;Your business email&#39;}),<br>        input.config.text(&#39;paymentTerms&#39;, {label: &#39;Payment terms&#39;, description: &#39;e.g. Payment is due within 14 days.&#39;}),<br>        input.config.text(&#39;paymentNote&#39;, {label: &#39;Payment note&#39;, description: &#39;e.g. bank details. {number} becomes the invoice number.&#39;}),<br>        input.config.table(&#39;table&#39;, {label: &#39;Invoices table&#39;}),<br>        input.config.view(&#39;view&#39;, {label: &#39;View to process&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;numberField&#39;, {label: &#39;Invoice number&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;clientField&#39;, {label: &#39;Client name&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;emailField&#39;, {label: &#39;Client email&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;dateField&#39;, {label: &#39;Issued on&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;itemsField&#39;, {label: &#39;Items&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;taxField&#39;, {label: &#39;Tax rate&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;pdfField&#39;, {label: &#39;Invoice PDF (attachment)&#39;, parentTable: &#39;table&#39;}),<br>        input.config.field(&#39;statusField&#39;, {label: &#39;PDF status (text)&#39;, parentTable: &#39;table&#39;}),<br>    ],<br>});<br><br>const API = &#39;https://thirds.ai&#39;;<br>// remoteFetchAsync runs the request from Airtable&#39;s servers, so the browser&#39;s CORS rules do not apply.<br>const send = typeof remoteFetchAsync === &#39;function&#39; ? remoteFetchAsync : fetch;<br><br>function round2(n) { return Math.round(n * 100) / 100; }<br><br>function parseItems(text) {<br>    const items = [];<br>    for (const line of (text || &#39;&#39;).split(&#39;\n&#39;)) {<br>        if (!line.trim()) continue;<br>        const cut = line.lastIndexOf(&#39;|&#39;);<br>        if (cut &lt; 0) throw new Error(`Item line has no &quot;|&quot;: ${line}`);<br>        const description = line.slice(0, cut).trim();<br>        const amount = Number(line.slice(cut + 1).replace(/[^0-9.\-]/g, &#39;&#39;));<br>        if (!description || !Number.isFinite(amount)) throw new Error(`Cannot read item line: ${line}`);<br>        items.push({description, amount: round2(amount)});<br>    }<br>    if (items.length &lt; 1 || items.length &gt; 12) throw new Error(&#39;An invoice needs 1 to 12 item lines.&#39;);<br>    return items;<br>}<br><br>async function api(method, path, body, idemKey) {<br>    const headers = {Authorization: `Bearer ${settings.apiKey.trim()}`};<br>    if (body) { headers[&#39;Content-Type&#39;] = &#39;application/json&#39;; headers[&#39;Idempotency-Key&#39;] = idemKey; }<br>    const res = await send(API + path, {method, headers, body: body ? JSON.stringify(body) : undefined});<br>    const json = await res.json();<br>    if (res.status &gt;= 400) throw new Error(`${res.status} ${json.error ? json.error.code + &#39;: &#39; + json.error.message : &#39;&#39;}`);<br>    return json;<br>}<br><br>async function makeInvoice(record) {<br>    const number = record.getCellValueAsString(settings.numberField);<br>    const items = parseItems(record.getCellValueAsString(settings.itemsField));<br>    let rate = Number(record.getCellValue(settings.taxField) || 0);<br>    if (settings.taxField.type === &#39;percent&#39;) rate = rate * 100; // percent fields store 0.2 for 20%<br>    const subtotal = round2(items.reduce((s, i) =&gt; s + i.amount, 0));<br>    const tax = round2(subtotal * rate / 100);<br>    const data = {<br>        business_name: settings.businessName,<br>        business_email: settings.businessEmail,<br>        client_name: record.getCellValueAsString(settings.clientField),<br>        client_email: record.getCellValueAsString(settings.emailField),<br>        invoice_number: number,<br>        issued_on: record.getCellValue(settings.dateField), // date fields give YYYY-MM-DD<br>        items, subtotal, tax, total: round2(subtotal + tax),<br>        payment_terms: settings.paymentTerms,<br>        payment_note: settings.paymentNote.replace(&#39;{number}&#39;, number),<br>    };<br>    // Same invoice number and same data gives the same key, so a re-run never pays twice.<br>    let job = await api(&#39;POST&#39;, &#39;/v1/pdf&#39;, {template_id: settings.templateId.trim(), data, filename: `invoice-${number}`}, `airtable-invoice-${number}`);<br>    const deadline = Date.now() + 120000;<br>    while (job.status === &#39;queued&#39; || job.status === &#39;running&#39;) {<br>        if (Date.now() &gt; deadline) throw new Error(`still ${job.status}, run the script again to pick it up`);<br>        await new Promise(r =&gt; setTimeout(r, 2000));<br>        job = await api(&#39;GET&#39;, `/v1/pdf/${job.id}`);<br>    }<br>    if (job.status !== &#39;succeeded&#39;) throw new Error(`${job.status}: ${JSON.stringify(job.error)}`);<br>    // Airtable copies the file from this signed link (no key needed, valid 15 minutes).<br>    await settings.table.updateRecordAsync(record, {<br>        [settings.pdfField.id]: [{url: API + job.download.url, filename: `invoice-${number}.pdf`}],<br>        [settings.statusField.id]: `Done ${job.id}`,<br>    });<br>    return job.id;<br>}<br><br>const query = await settings.view.selectRecordsAsync({fields: [<br>    settings.numberField, settings.clientField, settings.emailField, settings.dateField,<br>    settings.itemsField, settings.taxField, settings.pdfField]});<br>const todo = query.records.filter(r =&gt; !(r.getCellValue(settings.pdfField) || []).length);<br>output.text(`${todo.length} invoice(s) to make.`);<br>for (const record of todo) {<br>    try {<br>        const id = await makeInvoice(record);<br>        output.text(`Made ${record.getCellValueAsString(settings.numberField)} (${id})`);<br>    } catch (e) {<br>        output.text(`Skipped ${record.getCellValueAsString(settings.numberField)}: ${e.message}`);<br>        await settings.table.updateRecordAsync(record, {[settings.statusField.id]: `Error: ${e.message}`.slice(0, 500)});<br>    }<br>}</pre><p><strong>4. Run it.</strong> Click Run. Each record gets its PDF in Invoice PDF and Done pdf_... in PDF status. A record with a problem gets Error: ... in PDF status and the others carry on.</p><p><strong>How it was tested.</strong> The script file was run unchanged against the live API in a Node harness that mocks Airtable’s input.config, table, view, records and output, with two records: one new and one that already had a PDF. The record with a PDF was skipped, 1,250.00 was parsed, a percent field value of 0.2 was read as 20%, and the totals in the PDF matched: £2,294.50 plus £458.90 tax gives £2,753.40. The attachment was written as {url, filename}. It has not been run inside a real Airtable base, so try it on a copy of your table first.</p><p><strong>Good to know</strong></p><ol><li>The key sits in the extension’s settings, so anyone who can edit the extension can read it. Use a key made only for this base, and delete it on thirds.ai if it leaks.</li><li>The script uses remoteFetchAsync, so the call goes out from Airtable&#39;s servers and the browser&#39;s CORS rules do not get in the way.</li><li>Airtable copies the PDF from a signed link that works for 15 minutes, so the file stays on the record after the link ends.</li><li>Running it twice is safe: the retry key is the invoice number, so the same invoice with the same details is never charged twice. If you edit an invoice that already has a PDF, clear Invoice PDF and change the invoice number (or add a suffix such as -v2) before you run it again.</li><li>Each finished PDF costs one credit, a failed one costs nothing, and a free thirds.ai account gets 50 credits a month.</li></ol><p>More on <a href="https://thirds.ai/use-cases/invoices?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-airtable-invoices">invoice PDFs from your data</a>.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e6860a5c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate a PDF from HTML in Next.js: one API route and one button]]></title>
            <link>https://medium.com/@imvalerian/generate-a-pdf-from-html-in-next-js-one-api-route-and-one-button-11b0fbd445e5?source=rss-df4724dbd262------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b0fbd445e5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Valerian]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 21:11:50 GMT</pubDate>
            <atom:updated>2026-10-18T21:11:50.062Z</atom:updated>
            <content:encoded><![CDATA[<p>Drafted with AI help. (Disclosure: I’m connected to thirds.ai.)</p><p>Running a headless browser inside a Next.js app is the usual way to make PDFs, and it is also the usual way to get a slow cold start, a huge deploy and a function that times out. This guide keeps the PDF work off your server. A route handler builds the HTML, sends it to an HTML to PDF API and streams the PDF back, and a small client component turns that into a download.</p><p><strong>1. Keep the key on the server.</strong> Put THIRDS_API_KEY in .env.local and read it only in the route handler. Never prefix it with NEXT_PUBLIC_, or it ends up in the browser bundle.</p><p><strong>2. Build the HTML on the server, not in the browser.</strong> The route takes invoice data, not HTML. If the route accepted any HTML, anyone could use it to make documents on your account. Escape every value before it goes into the markup.</p><p><strong>3. Add print rules.</strong> tr { break-inside: avoid; } keeps a row from splitting across pages, and a footer template with pageNumber and totalPages adds page numbers:</p><pre>pdf: {<br>  format: &#39;A4&#39;,<br>  margins: { top: &#39;18mm&#39;, right: &#39;14mm&#39;, bottom: &#39;18mm&#39;, left: &#39;14mm&#39; },<br>  display_header_footer: true,<br>  header_template: &#39;&lt;span&gt;&lt;/span&gt;&#39;,<br>  footer_template: &quot;&lt;span style=&#39;font-size:9px;width:100%;text-align:center&#39;&gt;&lt;span class=&#39;pageNumber&#39;&gt;&lt;/span&gt; / &lt;span class=&#39;totalPages&#39;&gt;&lt;/span&gt;&lt;/span&gt;&quot;,<br>}</pre><p><strong>4. The route</strong> (app/api/invoice-pdf/route.ts, full file below). It posts { html, filename, pdf } to https://thirds.ai/v1/pdf with an Idempotency-Key, waits for succeeded (polling GET /v1/pdf/{id} only if the job is still queued or running), then fetches the file from download.url and returns it with Content-Type: application/pdf. The key is the invoice number plus a hash of the HTML, so a double click never pays twice, and an edited invoice still gets a fresh file.</p><p><strong>5. The button</strong> (app/download-invoice-button.tsx, full file below). It posts the invoice to the route, turns the answer into a blob and clicks a temporary link to save invoice-INV-3308.pdf.</p><p>The route:</p><pre>// app/api/invoice-pdf/route.ts<br>// Next.js App Router API route: builds an invoice page as HTML on the server,<br>// turns it into a PDF with thirds.ai, and sends the PDF back to the browser.<br>// Set THIRDS_API_KEY in .env.local (server only; never prefix it with NEXT_PUBLIC_).<br>// Each finished PDF costs one credit; a failed one is free.<br><br>import { createHash } from &#39;node:crypto&#39;;<br><br>export const runtime = &#39;nodejs&#39;;<br><br>const API = &#39;https://thirds.ai&#39;;<br><br>type Line = { description: string; quantity: number; unitPrice: number };<br>type InvoiceInput = { number: string; customer: string; issuedOn: string; lines: Line[] };<br><br>const esc = (s: unknown) =&gt;<br>  String(s).replace(/[&amp;&lt;&gt;&quot;&#39;]/g, (c) =&gt; ({ &#39;&amp;&#39;: &#39;&amp;amp;&#39;, &#39;&lt;&#39;: &#39;&amp;lt;&#39;, &#39;&gt;&#39;: &#39;&amp;gt;&#39;, &#39;&quot;&#39;: &#39;&amp;quot;&#39;, &quot;&#39;&quot;: &#39;&amp;#39;&#39; })[c]!);<br>const gbp = (n: number) =&gt; new Intl.NumberFormat(&#39;en-GB&#39;, { style: &#39;currency&#39;, currency: &#39;GBP&#39; }).format(n);<br><br>function invoiceHtml(inv: InvoiceInput) {<br>  const rows = inv.lines<br>    .map((l) =&gt; `&lt;tr&gt;&lt;td&gt;${esc(l.description)}&lt;/td&gt;&lt;td class=&quot;n&quot;&gt;${l.quantity}&lt;/td&gt;&lt;td class=&quot;n&quot;&gt;${gbp(l.unitPrice)}&lt;/td&gt;&lt;td class=&quot;n&quot;&gt;${gbp(l.quantity * l.unitPrice)}&lt;/td&gt;&lt;/tr&gt;`)<br>    .join(&#39;&#39;);<br>  const total = inv.lines.reduce((s, l) =&gt; s + l.quantity * l.unitPrice, 0);<br>  return `&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;style&gt;<br>    body { font-family: system-ui, sans-serif; color: #1d232a; margin: 0; }<br>    h1 { font-size: 28px; margin: 0 0 4px; }<br>    table { width: 100%; border-collapse: collapse; margin-top: 24px; }<br>    th, td { padding: 8px 6px; border-bottom: 1px solid #e3e6ea; text-align: left; }<br>    tr { break-inside: avoid; }<br>    .n { text-align: right; } .total td { font-weight: 700; border-bottom: 0; }<br>  &lt;/style&gt;&lt;/head&gt;&lt;body&gt;<br>    &lt;h1&gt;Invoice ${esc(inv.number)}&lt;/h1&gt;<br>    &lt;div&gt;Billed to ${esc(inv.customer)}, issued ${esc(inv.issuedOn)}&lt;/div&gt;<br>    &lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Item&lt;/th&gt;&lt;th class=&quot;n&quot;&gt;Qty&lt;/th&gt;&lt;th class=&quot;n&quot;&gt;Price&lt;/th&gt;&lt;th class=&quot;n&quot;&gt;Amount&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;<br>    &lt;tbody&gt;${rows}&lt;tr class=&quot;total&quot;&gt;&lt;td colspan=&quot;3&quot;&gt;Total&lt;/td&gt;&lt;td class=&quot;n&quot;&gt;${gbp(total)}&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;<br>  &lt;/body&gt;&lt;/html&gt;`;<br>}<br><br>async function thirds(path: string, init: RequestInit = {}) {<br>  const res = await fetch(API + path, {<br>    ...init,<br>    headers: { Authorization: `Bearer ${process.env.THIRDS_API_KEY}`, &#39;Content-Type&#39;: &#39;application/json&#39;, ...init.headers },<br>    cache: &#39;no-store&#39;,<br>  });<br>  const job = await res.json();<br>  if (!res.ok) throw new Error(job.error?.code ?? `HTTP ${res.status}`);<br>  return job;<br>}<br><br>export async function POST(req: Request) {<br>  // Add your own auth check here: this route spends your credits.<br>  const inv = (await req.json()) as InvoiceInput;<br>  if (!inv?.number || !Array.isArray(inv.lines) || inv.lines.length === 0) {<br>    return Response.json({ error: &#39;number and lines are required&#39; }, { status: 400 });<br>  }<br>  const html = invoiceHtml(inv);<br>  // Same invoice and same content gives the same key, so a double click never pays twice.<br>  // An edited invoice gets a new key (the API refuses a reused key with different content).<br>  const idemKey = `next-invoice-${inv.number.replace(/[^ -~]/g, &quot;&quot;)}-${createHash(&#39;sha256&#39;).update(html).digest(&#39;hex&#39;).slice(0, 16)}`;<br>  try {<br>    let job = await thirds(&#39;/v1/pdf&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Idempotency-Key&#39;: idemKey },<br>      body: JSON.stringify({<br>        html,<br>        filename: `invoice-${inv.number}`,<br>        pdf: {<br>          format: &#39;A4&#39;,<br>          margins: { top: &#39;18mm&#39;, right: &#39;14mm&#39;, bottom: &#39;18mm&#39;, left: &#39;14mm&#39; },<br>          display_header_footer: true,<br>          header_template: &#39;&lt;span&gt;&lt;/span&gt;&#39;,<br>          footer_template: &quot;&lt;span style=&#39;font-size:9px;width:100%;text-align:center&#39;&gt;&lt;span class=&#39;pageNumber&#39;&gt;&lt;/span&gt; / &lt;span class=&#39;totalPages&#39;&gt;&lt;/span&gt;&lt;/span&gt;&quot;,<br>        },<br>      }),<br>    });<br>    const deadline = Date.now() + 60_000;<br>    while (job.status === &#39;queued&#39; || job.status === &#39;running&#39;) {<br>      if (Date.now() &gt; deadline) return Response.json({ error: &#39;still rendering&#39;, id: job.id }, { status: 504 });<br>      await new Promise((r) =&gt; setTimeout(r, 1500));<br>      job = await thirds(`/v1/pdf/${job.id}`);<br>    }<br>    if (job.status !== &#39;succeeded&#39;) return Response.json({ error: job.status, detail: job.error }, { status: 502 });<br>    // The signed download link needs no key and lasts 15 minutes.<br>    const file = await fetch(API + job.download.url, { cache: &#39;no-store&#39; });<br>    return new Response(file.body, {<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/pdf&#39;,<br>        &#39;Content-Disposition&#39;: `attachment; filename=&quot;invoice-${encodeURIComponent(inv.number)}.pdf&quot;`,<br>      },<br>    });<br>  } catch (e) {<br>    return Response.json({ error: (e as Error).message }, { status: 502 });<br>  }<br>}</pre><p>The button:</p><pre>// app/download-invoice-button.tsx<br>// Client component: posts the invoice to /api/invoice-pdf and saves the PDF it gets back.<br>&#39;use client&#39;;<br><br>import { useState } from &#39;react&#39;;<br><br>export default function DownloadInvoiceButton({ invoice }: { invoice: object &amp; { number: string } }) {<br>  const [busy, setBusy] = useState(false);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  async function download() {<br>    setBusy(true);<br>    setError(&#39;&#39;);<br>    try {<br>      const res = await fetch(&#39;/api/invoice-pdf&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify(invoice),<br>      });<br>      if (!res.ok) throw new Error((await res.json()).error ?? `HTTP ${res.status}`);<br>      const url = URL.createObjectURL(await res.blob());<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = `invoice-${invoice.number}.pdf`;<br>      a.click();<br>      URL.revokeObjectURL(url);<br>    } catch (e) {<br>      setError((e as Error).message);<br>    } finally {<br>      setBusy(false);<br>    }<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={download} disabled={busy}&gt;{busy ? &#39;Making PDF...&#39; : &#39;Download PDF&#39;}&lt;/button&gt;<br>      {error &amp;&amp; &lt;p role=&quot;alert&quot;&gt;Could not make the PDF: {error}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>6. Protect the route.</strong> It spends credits, so put your normal auth check at the top before anything else.</p><p>The test run on Next.js 16 (App Router, next build and next start) returned a one-page A4 PDF with the footer 1/1 in about two seconds. Each finished PDF costs one credit, a failed one costs nothing, and a free account gets 50 credits a month. More options are on the <a href="https://thirds.ai/html-to-pdf?utm_source=medium&amp;utm_medium=community&amp;utm_campaign=own-content&amp;utm_content=gist-nextjs-html-to-pdf">HTML to PDF page</a>.</p><p>(Disclosure: I’m connected to thirds.ai.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b0fbd445e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>