mbingpdf v0.1.0

Packages

React

Show an mbingpdf document on screen in a React app, and make the PDF file from the same definition.

npm install mbingpdf @mbingpdf/react

Preview

import { useMemo } from "react";
import { Document, Page, Text } from "mbingpdf";
import { PdfPreview } from "@mbingpdf/react";

function InvoicePreview({ invoice }) {
  const document = useMemo(
    () => Document(Page({ size: "A4", margin: 36 }, Text(`Invoice ${invoice.number}`))),
    [invoice],
  );
  return <PdfPreview document={document} />;
}

PdfPreview draws the pages exactly as the PDF will have them: the same line breaks, the same page breaks. Pages take the width of the element around them, so the preview is readable on a phone. Each page is drawn only when it comes near the screen, so long documents open at once. Links work, both to the web and within the document.

The document is laid out again whenever the document prop changes. Build it with useMemo, as above, so that happens only when the data changes.

Prop
documentThe document to show
gapSpace between pages in CSS pixels; default 16
debugOutline every element's box
pageLabelWhat a screen reader calls each page: (page, pages) => string; default Page 1 of 3. The page's text follows it
className, styleFor the element around all pages
pageClassName, pageStyleFor each page; the default is a white sheet with a light shadow
onLayoutCalled with { pages } after each layout
onErrorCalled when the document cannot be laid out; without it the message is shown in place

The file

import { usePdf } from "@mbingpdf/react";

function DownloadButton({ document }) {
  const pdf = usePdf(document);
  return (
    <button disabled={pdf.loading} onClick={() => pdf.download("invoice.pdf")}>
      Download
    </button>
  );
}

usePdf(document, options?) returns { bytes, url, error, loading, make, download }. url can be the href of a link or the src of an <iframe>; bytes can be uploaded to a server. The options are those of render().

To make a file without a hook, call render() from mbingpdf and pass the bytes to downloadPdf(bytes, filename).

With usePdf(document, { lazy: true }) nothing is made until pdf.download(name) or pdf.make() is called: for a large document that should not be rendered again on every change. make() gives the bytes.

Notes

MIT licence.

Edit this page on GitHub