DEV Community

Usama Muhammad
Usama Muhammad

Posted on Fully Autonomous

Sending an invoice PDF to WhatsApp from a web app (Web Share API, html2canvas, jsPDF)

Most of the small businesses using our invoicing app, Tichkuly, don't email their customers. They WhatsApp them. So the one button that really matters in the app is "Send on WhatsApp", and it has to send a real PDF file, not just a link.

The app is a Next.js web app (wrapped for Android too), so everything below happens in the browser. Here's how it works and what tripped us up.

1. Render the invoice to a PDF in the browser

The invoice is already on screen as HTML, laid out as an A4 page (794 × 1123 CSS pixels, which is A4 at 96 dpi). We take a picture of that element with html2canvas and place it on an A4 page with jsPDF:

async function renderPdf(element: HTMLElement, filename: string): Promise<File> {
  // Both libraries are big, so they load only when someone actually makes a PDF.
  const [{ default: html2canvas }, { jsPDF }] = await Promise.all([
    import("html2canvas-pro"),
    import("jspdf"),
  ]);
  const canvas = await html2canvas(element, { scale: 2, useCORS: true, backgroundColor: "#ffffff" });
  const pdf = new jsPDF({ unit: "pt", format: "a4", compress: true });
  const width = pdf.internal.pageSize.getWidth();
  const imageHeight = (canvas.height * width) / canvas.width;
  pdf.addImage(canvas.toDataURL("image/jpeg", 0.5), "JPEG", 0, 0, width, imageHeight, undefined, "FAST");
  return new File([pdf.output("blob")], filename, { type: "application/pdf" });
}
Enter fullscreen mode Exit fullscreen mode

Two details worth copying:

  • html2canvas-pro instead of html2canvas. Tailwind v4 uses oklch() colours, and the original library throws on them. The -pro fork handles them.
  • JPEG at quality 0.5. With scale: 2, text stays sharp, and a page is about a third of the size it is at 0.92. That matters when the file goes over a mobile connection to WhatsApp.

The trade-off: the text in the PDF is an image, so it can't be selected or searched. For a one-page invoice sent to a customer's phone, we found that acceptable. If you need selectable text, build the PDF with jsPDF's text API or pdf-lib instead.

2. Hand the file to WhatsApp with the Web Share API

On phones, navigator.share() can share files, and the share sheet lists WhatsApp, WhatsApp Business, Gmail and the rest:

export async function sharePdf(file: File, text: string) {
  if (!navigator.canShare?.({ files: [file] })) {
    downloadPdf(file); // most desktops: save it, attach by hand
    return false;
  }
  try {
    await navigator.share({ files: [file], title: file.name, text });
  } catch (e) {
    // The user closing the share sheet is not an error.
    if ((e as { name?: string }).name !== "AbortError") throw e;
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Always check navigator.canShare({ files }) first. Plenty of browsers have navigator.share but can't share files, and desktop Chrome on most systems is one of them.

3. The gotcha: make the PDF before the tap

This is the one that cost us a day. navigator.share() must be called during a user activation, right after a tap. Rendering the PDF takes long enough (half a second to a couple of seconds on a cheap Android phone) that by the time it's ready, the activation has expired. Then share() fails with a NotAllowedError.

The fix: make the PDF quietly in the background as soon as the invoice is on screen and saved, and keep it. The tap only shares a file that already exists.

// A moment after the page settles, make the PDF so the first tap can share at once.
useEffect(() => {
  if (!enabled) return; // e.g. unsaved changes
  const timer = setTimeout(() => make().catch(() => {}), 600);
  return () => clearTimeout(timer);
}, [enabled, version]);
Enter fullscreen mode Exit fullscreen mode

version is a string that changes whenever the invoice content changes, so an edited invoice never sends a stale PDF. make() returns the cached file if the version matches.

4. A link as well as the file

Some people prefer a WhatsApp message with a link they can open later. So after the PDF is made, we also upload a copy under the document's private share token, and the message carries https://.../i/<token>. The upload runs in the background and never blocks the share. We also track which version is online, so an older upload that finishes late doesn't overwrite a newer one.

What we'd do differently

  • If we needed text you can select or search, we'd build the PDF from data with pdf-lib rather than taking a picture of HTML.
  • Multi-page documents need care. We lay long ones out as separate A4 page elements and render each one, so a table row is never cut across two pages.

You can try the in-browser version without signing up in our free invoice generator. It makes the PDF on your device, and nothing is uploaded. If you just want blank Word or Excel templates, they're free on GitHub.

Questions about any of this are welcome in the comments.

Top comments (0)