Skip to content

PDF documents

An app makes a PDF file, such as an invoice, a quote or a report, from a React component of its data, the way it writes its emails. The component is built from the components of React PDF (@react-pdf/renderer), and Protobase renders it to the bytes of a PDF file with React PDF’s renderer.

A document is definePdf: a name and a React component whose props are the document’s data, with React PDF’s <Document> at its root. @protobase/server brings React PDF; the project adds React for its JSX, which a project with a UI has already:

Terminal window
bun add react
bun add -d @types/react
documents/repair-quote.tsx
import { definePdf } from '@protobase/server'
import { Document, Page, StyleSheet, Text, View } from '@protobase/server/pdf'
export type RepairQuote = { number: string; customer: string; bike: string; problem: string; estimate: string }
const styles = StyleSheet.create({
page: { padding: 48, fontSize: 11, fontFamily: 'Helvetica' },
heading: { fontSize: 20, fontFamily: 'Helvetica-Bold', marginBottom: 16 },
row: { flexDirection: 'row', justifyContent: 'space-between', borderBottom: '1pt solid #e4e4e7', paddingVertical: 6 },
})
// The document's data is the component's props: `render` takes exactly these.
const RepairQuoteDocument = ({ number, customer, bike, problem, estimate }: RepairQuote) => (
<Document title={`Quote ${number}`}>
<Page size="A4" style={styles.page}>
<Text style={styles.heading}>Quote {number}</Text>
<Text>For {customer}</Text>
<View style={styles.row}>
<Text>
{bike}: {problem}
</Text>
<Text>{estimate}</Text>
</View>
</Page>
</Document>
)
export const repairQuote = definePdf({ name: 'repair-quote', component: RepairQuoteDocument })
definePdf option
name Names the document.
component The document, a React component of the data with a <Document> at its root.

The definition that comes back has one method, typed by the component’s props: render(data) gives the bytes of the PDF file, a Uint8Array. An email’s attachment and a Response take them as they are.

React and React PDF’s renderer are loaded on the first document rendered, not when the app starts.

@protobase/server/pdf exports React PDF’s components, typed as @react-pdf/renderer types them: Document, Page, View, Text, Link, Image, ImageBackground, Note, Canvas, the form fields FieldSet, TextInput, Checkbox, Select and List, and Svg with its shapes (G, Path, Rect, Line, Circle, Ellipse, Polygon, Polyline, Tspan, Defs, Stop, ClipPath, Marker, LinearGradient, RadialGradient). StyleSheet.create types a document’s styles. React PDF’s documentation explains each component and the styles they take: components, styling.

Importing them loads nothing of React PDF: they are only the names its renderer knows its elements by.

  • Fonts: text is set in the PDF standard fonts, Helvetica (the default), Times-Roman and Courier, each with its bold and italic faces, such as Helvetica-Bold, chosen with the fontFamily style. They write the characters of Windows-1252, the Latin script of Western European languages, the euro sign included.
  • Documents cannot use fonts of their own, nor scripts beyond Windows-1252, because registering a font with React PDF’s renderer is not implemented.
  • Images: the renderer fetches an <Image> whose src is a URL, and reads one whose src is a file path, on the server. Give it the image’s bytes, as a Buffer or a data: URI, or an address the app chose, never one a user typed.

An API function may answer with the file, for the browser to show or save:

functions/repair-quote.ts
import { defineFunction } from '@protobase/server'
import { repairQuote } from '../documents/repair-quote'
// GET /api/functions/repair-quote/7: the repair's quote as a PDF file, which the browser shows or saves.
export default defineFunction({ roles: ['desk'] }, async (request, { records }) => {
const id = Number(new URL(request.url).pathname.slice(1))
const { record: repair } = await records.get('repairs', id)
const { record: customer } = await records.get('customers', repair.customer_id as number)
const number = repair.number as string
const pdf = await repairQuote.render({
number,
customer: customer.name as string,
bike: repair.bike as string,
problem: repair.problem as string,
estimate: `${repair.currency} ${repair.estimate}`,
})
return new Response(pdf, { headers: { 'content-type': 'application/pdf', 'content-disposition': `inline; filename="quote-${number}.pdf"` } })
})

A job renders it to send by mail, so the email goes out after the write that asked for it committed, and a message the server refuses is retried. A write hook enqueues such a job rather than rendering in the write’s transaction, as for email:

jobs/email-repair-quote.ts
import { FatalJobError, type JobRun } from '@protobase/server'
import { repairQuote } from '../documents/repair-quote'
// Emails the customer their repair's quote, the PDF attached as it was rendered.
export default (async ({ repairId }, { db, mail }) => {
if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
const repair = await db
.selectFrom('repairs')
.innerJoin('customers', 'customers.id', 'repairs.customer_id')
.select(['repairs.number', 'repairs.bike', 'repairs.problem', 'repairs.estimate', 'repairs.currency', 'customers.name', 'customers.email'])
.where('repairs.id', '=', repairId)
.executeTakeFirst()
if (!repair?.email) return
const pdf = await repairQuote.render({
number: repair.number,
customer: repair.name,
bike: repair.bike,
problem: repair.problem,
estimate: `${repair.currency} ${repair.estimate}`,
})
await mail.send({
to: repair.email,
subject: `Quote ${repair.number} for your ${repair.bike}`,
text: `Hi ${repair.name}, the quote for your ${repair.bike} is attached.`,
attachments: [{ filename: `quote-${repair.number}.pdf`, content: pdf, contentType: 'application/pdf' }],
})
}) satisfies JobRun<{ repairId: number }>
protobase.config.ts
import { defineConfig } from '@protobase/config'
export default defineConfig({
jobs: {
// jobs/email-repair-quote.ts
'email-repair-quote': { description: "Emails a customer their repair's quote as a PDF.", arguments: { repairId: 'integer' } },
},
})

A template’s send takes the same attachment as its fourth argument, and so does a function’s personalMail, to send it from someone’s own mailbox.

A bundle gets @protobase/server/pdf from the serve runtime, as it gets @protobase/server, whose definePdf renders with the runtime’s own React PDF. A served config imports React PDF’s components from @protobase/server/pdf: @react-pdf/renderer is a dependency of @protobase/server that the runtime does not hand to a bundle, so importing it fails the build.