DEV Community

György Gulyás
György Gulyás

Posted on Originally published at sahifa.dev

Generating ZATCA-ready invoice PDFs from HTML

If you sell to customers in Saudi Arabia, your invoices fall under ZATCA's e-invoicing rules (FATOORA). A lot of the rules are about the XML and the integration with ZATCA's platform. But every invoice also ends up as a document a person reads: a PDF attached to an email, or a printed receipt in a box. That document needs the QR code, correct Arabic text and usually a bilingual layout.

This guide covers that document side. It is not legal advice, and the official source is always ZATCA's e-invoicing pages.

Phase 1 and phase 2 in one paragraph

Phase 1 (generation), in force since 4 December 2021, requires invoices to be generated electronically. Simplified tax invoices (B2C) carry a QR code with five fields. Phase 2 (integration) is rolled out in waves by taxpayer size. Invoices are produced as signed UBL 2.1 XML and reported to (B2C) or cleared by (B2B) ZATCA, and the QR code gets more fields, including the invoice hash and signature. If you are in phase 2, your e-invoicing solution produces the QR value from the signed XML; your document only has to print it.

The phase 1 QR code: TLV in Base64

The QR value is Base64 of a byte sequence of TLV records. Each record has a one-byte tag, a one-byte length in bytes, then the UTF-8 value:

Tag Field
1 Seller name
2 VAT registration number
3 Invoice timestamp (ISO 8601)
4 Invoice total, with VAT
5 VAT total

The classic bug: using the character count as the length. An Arabic seller name like شركة المثال is 11 characters but 21 bytes in UTF-8. Always count bytes.

// Phase 1 ZATCA QR value (Base64 of TLV records)
export function zatcaQr({ seller, vatNumber, timestamp, total, vat }) {
  const fields = [seller, vatNumber, timestamp, total, vat];
  const parts = fields.map((value, i) => {
    const bytes = Buffer.from(String(value), 'utf8');
    if (bytes.length > 255) throw new Error(`Field ${i + 1} is longer than 255 bytes`);
    return Buffer.concat([Buffer.from([i + 1, bytes.length]), bytes]);
  });
  return Buffer.concat(parts).toString('base64');
}

const qr = zatcaQr({
  seller: 'شركة المثال للتجارة',
  vatNumber: '399999999900003',   // ZATCA's documented test VAT number
  timestamp: '2026-09-27T10:15:00Z',
  total: '1150.00',
  vat: '150.00',
});
Enter fullscreen mode Exit fullscreen mode

Turn it into an image with any QR library. Inline SVG keeps the PDF sharp at any zoom:

import QRCode from 'qrcode';
const svg = await QRCode.toString(qr, { type: 'svg', margin: 0, errorCorrectionLevel: 'M' });
Enter fullscreen mode Exit fullscreen mode

Test it by decoding: Base64 → bytes → read tag, length, value until the end. A decoder is ten lines in any language, and it catches length bugs immediately.

The invoice template

A simplified tax invoice typically shows, among other things: the seller's name, address and VAT number, the invoice number and date, the items with quantities and prices, the VAT amount and total, and the QR code. Customers in Saudi Arabia expect Arabic, often next to English. HTML handles bilingual layouts well:

<html dir="rtl" lang="ar">
<head>
<meta charset="utf-8">
<style>
  @page { size: A4; margin: 14mm; }
  body { font: 11pt/1.5 'Noto Naskh Arabic', 'Amiri', serif; color: #222; }
  .en  { font-family: 'Noto Sans', sans-serif; color: #555; font-size: 9pt; }
  table { width: 100%; border-collapse: collapse; }
  th, td { padding: 6px; border-bottom: 1px solid #ddd; text-align: start; }
  .num { text-align: end; font-variant-numeric: tabular-nums; }
  .qr svg { width: 110px; height: 110px; }
</style>
</head>
<body>
  <h1>فاتورة ضريبية مبسطة <span class="en" lang="en" dir="ltr">Simplified tax invoice</span></h1>
  <p>الرقم الضريبي <span class="en" lang="en">VAT no.</span>: <bdi dir="ltr">399999999900003</bdi></p>
  <table>
    <thead>
      <tr><th>الصنف <span class="en">Item</span></th><th class="num">الكمية <span class="en">Qty</span></th>
          <th class="num">السعر <span class="en">Price</span></th><th class="num">الإجمالي <span class="en">Total</span></th></tr>
    </thead>
    <tbody>
      <tr><td>عطر عود ملكي 100 مل</td><td class="num">1</td><td class="num">1,000.00</td><td class="num">1,000.00</td></tr>
    </tbody>
  </table>
  <p class="num">ضريبة القيمة المضافة 15% <span class="en">VAT</span>: <bdi dir="ltr">150.00 SAR</bdi></p>
  <p class="num"><b>الإجمالي <span class="en">Total</span>: <bdi dir="ltr">1,150.00 SAR</bdi></b></p>
  <div class="qr"><!-- the SVG from QRCode.toString() --></div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

What makes it hold up:

  • text-align: start / end instead of left / right, so the layout works in both directions.
  • Every number, VAT number and amount is in <bdi dir="ltr">, so it never flips inside Arabic text.
  • The English labels are small <span>s with their own font. They sit next to the Arabic instead of being mixed into the same sentence.

Printing it

Render the HTML with a browser engine, which shapes Arabic and applies the bidi rules exactly like the browser. With Playwright:

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'load' });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', printBackground: true, preferCSSPageSize: true });
await browser.close();
Enter fullscreen mode Exit fullscreen mode

On a server, install Arabic fonts in the image (fonts-noto-core, fonts-hosny-amiri on Debian/Ubuntu). Otherwise you get empty boxes.

Or use a hosted API. For Saudi invoices, check where the service processes the data. Invoices contain customer names, addresses and amounts, and many companies in the Kingdom, fintechs in particular, need that data to stay in the country.

Disclosure: I'm affiliated with Sahifa, an HTML-to-PDF API that runs in Jeddah with Arabic fonts preinstalled. Examples in five languages: github.com/gyorgy-gulyas/sahifa-examples. It is also on RapidAPI, with a free plan of 50 requests a month.

const res = await fetch('https://api.sahifa.dev/v3/convert/pdf', {
  method: 'POST',
  headers: {
    Authorization: 'Basic ' + Buffer.from(`api:${process.env.SAHIFA_API_KEY}`).toString('base64'),
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ source: html, format: 'A4' }),
});
const pdf = Buffer.from(await res.arrayBuffer());
Enter fullscreen mode Exit fullscreen mode

Checklist

  • [ ] QR value: TLV with lengths in bytes, Base64; decode it in a unit test.
  • [ ] Phase 2: print the QR value your e-invoicing solution produced, don't generate your own.
  • [ ] dir="rtl" on <html>, <bdi dir="ltr"> around every number, VAT number and IBAN.
  • [ ] Arabic fonts installed where the PDF is rendered.
  • [ ] text-align: start/end and logical CSS properties, so the template works in both directions.
  • [ ] Know where your PDF service processes customer data.

Questions or edge cases with ZATCA documents? Leave them in the comments.

Top comments (0)