Beautiful pdf components, built on Takumi and Forme. 100% Free, Zero config, one command setup.
feat: implement theme support in PDF previews and update configuration for improved rendering
Aniket-508f8add5a1b7dd
diff --git a/components/component-preview.tsx b/components/component-preview.tsxindex 3530046..1b975e1 100644--- a/components/component-preview.tsx+++ b/components/component-preview.tsx@@ -5,12 +5,14 @@ import { PdfPreview } from "@/components/pdf-preview-wrapper";import { cn } from "@/lib/utils";import { DEFAULT_BASE } from "@/registry/bases";import type { BaseName } from "@/registry/bases";+import type { PdfcnTheme } from "@/registry/themes";export const ComponentPreview = ({base = DEFAULT_BASE,name,src,title,+ theme,children,className,hideCode = false,@@ -19,6 +21,7 @@ export const ComponentPreview = ({name?: string;src?: string;title?: string;+ theme?: PdfcnTheme;children?: ReactNode;className?: string;hideCode?: boolean;@@ -26,7 +29,12 @@ export const ComponentPreview = ({<>{children}{name ? (- <PdfPreview base={base} name={name} className={cn("mt-4", className)} />+ <PdfPreview+ base={base}+ name={name}+ theme={theme}+ className={cn("mt-4", className)}+ />) : null}{hideCode ? null : (<ComponentSource base={base} name={name} src={src} title={title} />diff --git a/components/pdf-preview.tsx b/components/pdf-preview.tsxindex ca50f14..efab0f5 100644--- a/components/pdf-preview.tsx+++ b/components/pdf-preview.tsx@@ -3,9 +3,9 @@import { createElement, useEffect, useRef, useState } from "react";import { replacePreviewImageSources } from "@/examples/preview-assets";-import { getTakumiPreviewOptions } from "@/examples/preview-config";import { cn } from "@/lib/utils";import type { BaseName } from "@/registry/bases";+import type { PdfcnTheme } from "@/registry/themes";const TAKUMI_WASM_PATH = "/takumi_pdf_wasm_bg.wasm";const PREVIEW_LOGO_PATH = "/favicon.png";@@ -15,6 +15,7 @@ let takumiWasmReady: Promise<unknown> | undefined;interface PdfPreviewProps {base: BaseName;name: string;+ theme?: PdfcnTheme;className?: string;height?: React.CSSProperties["height"];}@@ -66,6 +67,7 @@ const assertPdfHasPages = (pdfBytes: Uint8Array) => {export const PdfPreview = ({base,name,+ theme,className,height = 640,}: PdfPreviewProps) => {@@ -84,29 +86,76 @@ export const PdfPreview = ({let pdfBytes: Uint8Array;if (base === "takumi") {+ if (theme) {+ const [+ { InvoiceClassicDocument },+ { default: initialize, render },+ { fromJsx },+ images,+ ] = await Promise.all([+ import("@/registry/bases/takumi/blocks/invoice-classic/invoice-classic"),+ import("takumi-pdf"),+ import("@takumi-rs/helpers/jsx"),+ loadPreviewLogo(),+ ]);++ await initializeTakumi(initialize);+ const { node, stylesheets } = await fromJsx(+ createElement(InvoiceClassicDocument, { theme })+ );+ const { getTakumiPreviewOptions } =+ await import("@/examples/preview-config");+ const buffer = await render(node, {+ ...getTakumiPreviewOptions(name),+ images,+ stylesheets,+ });+ pdfBytes = new Uint8Array(buffer);+ } else {+ const [+ { demos },+ { default: initialize, render },+ { fromJsx },+ { getTakumiPreviewOptions },+ images,+ ] = await Promise.all([+ import("@/examples/__index__"),+ import("takumi-pdf"),+ import("@takumi-rs/helpers/jsx"),+ import("@/examples/preview-config"),+ loadPreviewLogo(),+ ]);+ const Demo = demos.takumi[name];+ if (!Demo) {+ throw new Error(`Unknown Takumi demo: ${name}`);+ }++ await initializeTakumi(initialize);+ const { node, stylesheets } = await fromJsx(createElement(Demo));+ const buffer = await render(node, {+ ...getTakumiPreviewOptions(name),+ images,+ stylesheets,+ });+ pdfBytes = new Uint8Array(buffer);+ }+ } else if (theme) {const [- { demos },- { default: initialize, render },- { fromJsx },- images,+ { InvoiceClassicDocument },+ { renderSerializedDoc },+ { serialize },] = await Promise.all([- import("@/examples/__index__"),- import("takumi-pdf"),- import("@takumi-rs/helpers/jsx"),- loadPreviewLogo(),+ import("@/registry/bases/forme/blocks/invoice-classic/invoice-classic"),+ import("@formepdf/core/browser"),+ import("@formepdf/react"),]);- const Demo = demos.takumi[name];- if (!Demo) {- throw new Error(`Unknown Takumi demo: ${name}`);- }- await initializeTakumi(initialize);- const { node, stylesheets } = await fromJsx(createElement(Demo));- const buffer = await render(node, {- ...getTakumiPreviewOptions(name),- images,- stylesheets,- });+ const document = replacePreviewImageSources(+ serialize(createElement(InvoiceClassicDocument, { theme }))+ );+ const buffer = await renderSerializedDoc(+ document as unknown as Record<string, unknown>+ );pdfBytes = new Uint8Array(buffer);} else {const [{ demos }, { renderSerializedDoc }, { serialize }] =@@ -120,10 +169,6 @@ export const PdfPreview = ({throw new Error(`Unknown Forme demo: ${name}`);}- // Serialize with the same @formepdf/react instance that created the- // demo primitives. renderDocument() dynamically imports a second- // serializer instance, whose strict Page identity check can drop all- // pages when bundled by Next.js.const document = replacePreviewImageSources(serialize(createElement(Demo)));@@ -159,7 +204,7 @@ export const PdfPreview = ({URL.revokeObjectURL(nextPdfUrl);}};- }, [base, name]);+ }, [base, name, theme]);return (<divdiff --git a/components/theme-preview.tsx b/components/theme-preview.tsxindex e48ad67..7ec4ebd 100644--- a/components/theme-preview.tsx+++ b/components/theme-preview.tsx@@ -1,7 +1,8 @@"use client";-import { createElement, useEffect, useRef, useState } from "react";+import { useState } from "react";+import { PdfPreview } from "@/components/pdf-preview-wrapper";import {Select,SelectContent,@@ -9,52 +10,11 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";-import { replacePreviewImageSources } from "@/examples/preview-assets";-import { getTakumiPreviewOptions } from "@/examples/preview-config";import { cn } from "@/lib/utils";import type { BaseName } from "@/registry/bases";import { THEMES } from "@/registry/themes";import type { RegistryThemeName } from "@/registry/themes";-const TAKUMI_WASM_PATH = "/takumi_pdf_wasm_bg.wasm";-const PREVIEW_LOGO_PATH = "/favicon.png";--let takumiWasmReady: Promise<unknown> | undefined;--const startTakumi = async (- initialize: (input: { module_or_path: string }) => Promise<unknown>-) => {- try {- return await initialize({ module_or_path: TAKUMI_WASM_PATH });- } catch (error) {- takumiWasmReady = undefined;- throw error;- }-};--const initializeTakumi = (- initialize: (input: { module_or_path: string }) => Promise<unknown>-) => {- takumiWasmReady ??= startTakumi(initialize);- return takumiWasmReady;-};--const loadPreviewLogo = async () => {- const response = await fetch(PREVIEW_LOGO_PATH);- if (!response.ok) {- throw new Error(`Unable to load preview logo (${response.status})`);- }-- return {- sources: [- {- data: await response.arrayBuffer(),- src: PREVIEW_LOGO_PATH,- },- ],- };-};-const THEMES_OPTIONS = [{ label: "Professional", value: "professional" },{ label: "Modern", value: "modern" },@@ -82,110 +42,8 @@ export const ThemePreview = ({}: ThemePreviewProps) => {const [selectedTheme, setSelectedTheme] =useState<RegistryThemeName>("professional");- const [pdfUrl, setPdfUrl] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);- const containerRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- let cancelled = false;- let nextPdfUrl: string | undefined;- setPdfUrl(null);- setError(null);- (async () => {- try {- const theme = THEMES.find((t) => t.name === selectedTheme)?.theme;-- if (base === "takumi") {- const [- { InvoiceClassicDocument },- { default: initialize, render },- { fromJsx },- images,- ] = await Promise.all([- import("@/registry/bases/takumi/blocks/invoice-classic/invoice-classic"),- import("takumi-pdf"),- import("@takumi-rs/helpers/jsx"),- loadPreviewLogo(),- ]);-- await initializeTakumi(initialize);- const { node, stylesheets } = await fromJsx(- createElement(InvoiceClassicDocument, { theme })- );- const buffer = await render(node, {- ...getTakumiPreviewOptions(name),- images,- stylesheets,- });- const pdfBytes = new Uint8Array(buffer);-- const source = new TextDecoder("latin1").decode(pdfBytes);- const pageCounts = [...source.matchAll(/\/Count\s+(\d+)/g)].map(- (match) => Number(match[1])- );- if (pageCounts.length > 0 && Math.max(...pageCounts) === 0) {- throw new Error("PDF renderer returned a document with no pages");- }-- nextPdfUrl = URL.createObjectURL(- new Blob([pdfBytes as BlobPart], { type: "application/pdf" })- );- } else {- const [- { InvoiceClassicDocument },- { renderSerializedDoc },- { serialize },- ] = await Promise.all([- import("@/registry/bases/forme/blocks/invoice-classic/invoice-classic"),- import("@formepdf/core/browser"),- import("@formepdf/react"),- ]);-- const document = replacePreviewImageSources(- serialize(createElement(InvoiceClassicDocument, { theme }))- );- const buffer = await renderSerializedDoc(- document as unknown as Record<string, unknown>- );- const pdfBytes = new Uint8Array(buffer);-- const source = new TextDecoder("latin1").decode(pdfBytes);- const pageCounts = [...source.matchAll(/\/Count\s+(\d+)/g)].map(- (match) => Number(match[1])- );- if (pageCounts.length > 0 && Math.max(...pageCounts) === 0) {- throw new Error("PDF renderer returned a document with no pages");- }-- nextPdfUrl = URL.createObjectURL(- new Blob([pdfBytes as BlobPart], { type: "application/pdf" })- );- }-- if (cancelled) {- URL.revokeObjectURL(nextPdfUrl);- return;- }- setPdfUrl(nextPdfUrl);- } catch (renderError) {- if (!cancelled) {- setError(- renderError instanceof Error- ? renderError.message- : "Failed to render PDF"- );- }- }- })();-- return () => {- cancelled = true;- if (nextPdfUrl) {- URL.revokeObjectURL(nextPdfUrl);- }- };- }, [base, name, selectedTheme]);+ const theme = THEMES.find((t) => t.name === selectedTheme)?.theme;return (<div className={cn("not-prose", className)}>@@ -200,7 +58,7 @@ export const ThemePreview = ({value={selectedTheme}onValueChange={(v) => setSelectedTheme(v as RegistryThemeName)}>- <SelectTrigger className="h-8 w-[140px] bg-background text-sm font-medium">+ <SelectTrigger className="h-8 w-35 bg-background text-sm font-medium"><SelectValue placeholder="Theme" /></SelectTrigger><SelectContent>@@ -212,36 +70,13 @@ export const ThemePreview = ({</SelectContent></Select></div>- <div- ref={containerRef}- className="overflow-hidden rounded-b-lg border bg-muted/30"- style={{ minHeight: height }}- >- {error ? (- <div- className="flex items-center justify-center p-8 text-sm text-muted-foreground"- style={{ minHeight: height }}- >- {error}- </div>- ) : null}- {!error && !pdfUrl ? (- <div- className="flex items-center justify-center p-8 text-sm text-muted-foreground"- style={{ minHeight: height }}- >- Rendering PDF…- </div>- ) : null}- {pdfUrl ? (- <iframe- className="block w-full bg-background"- src={`${pdfUrl}#toolbar=1&navpanes=0`}- style={{ height }}- title={`${name} PDF preview`}- />- ) : null}- </div>+ <PdfPreview+ base={base}+ name={name}+ theme={theme}+ height={height}+ className="rounded-none rounded-b-lg border"+ /></div>);};diff --git a/content/docs/(root)/index.mdx b/content/docs/(root)/index.mdxindex 20545a9..f0ccaa5 100644--- a/content/docs/(root)/index.mdx+++ b/content/docs/(root)/index.mdx@@ -21,15 +21,6 @@ Most PDF component setups are either too opinionated or too scattered. pdfcn is- **Start Fast:** Run one command and render your first document with production-ready defaults.- **Choose Your Engine:** Use the same component API with Takumi or Forme, then drop to raw renderer APIs when needed.-## Two Rendering Bases--Every component and block ships in two implementations:--- [Takumi](https://takumi.kane.tw/docs/pdf) — JSX and Tailwind-style classes rendered to paged, selectable-text PDFs with WebAssembly.-- [Forme](https://docs.formepdf.com) — React PDF primitives rendered with a page-native layout engine and first-class browser support.--The public props and variants follow pdfcn; only the renderer-specific primitives differ.-## Features<div className="not-prose grid gap-4 sm:grid-cols-2 mt-4">diff --git a/content/docs/themes/blueprint.mdx b/content/docs/themes/blueprint.mdxindex aa38bd1..4d4aee7 100644--- a/content/docs/themes/blueprint.mdx+++ b/content/docs/themes/blueprint.mdx@@ -3,10 +3,12 @@ title: "Blueprint"description: "Dark slate with cyan accent, monospace headings, technical precision."---+import { blueprintTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-classic"- theme="blueprint"+ theme={blueprintTheme}hideCode/>diff --git a/content/docs/themes/corporate.mdx b/content/docs/themes/corporate.mdxindex 3ccb7dc..bbadc75 100644--- a/content/docs/themes/corporate.mdx+++ b/content/docs/themes/corporate.mdx@@ -3,10 +3,12 @@ title: "Corporate"description: "Blue-gray palette, Lato sans-serif, structured and dependable."---+import { corporateTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-corporate"- theme="corporate"+ theme={corporateTheme}hideCode/>diff --git a/content/docs/themes/elegant.mdx b/content/docs/themes/elegant.mdxindex 97b1563..aebbf14 100644--- a/content/docs/themes/elegant.mdx+++ b/content/docs/themes/elegant.mdx@@ -3,10 +3,12 @@ title: "Elegant"description: "Warm cream whites, amber/gold accent, classic editorial combination."---+import { elegantTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-creative"- theme="elegant"+ theme={elegantTheme}hideCode/>diff --git a/content/docs/themes/executive.mdx b/content/docs/themes/executive.mdxindex 9aa0d39..3b79750 100644--- a/content/docs/themes/executive.mdx+++ b/content/docs/themes/executive.mdx@@ -3,10 +3,12 @@ title: "Executive"description: "Deep navy palette, Merriweather serif headings, premium boardroom aesthetic."---+import { executiveTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-corporate"- theme="executive"+ theme={executiveTheme}hideCode/>diff --git a/content/docs/themes/forest.mdx b/content/docs/themes/forest.mdxindex 7fafbb2..843e708 100644--- a/content/docs/themes/forest.mdx+++ b/content/docs/themes/forest.mdx@@ -3,7 +3,14 @@ title: "Forest"description: "Natural deep greens, Merriweather headings, earthy and trustworthy."----<ComponentPreview base="forme" name="invoice-classic" theme="forest" hideCode />+import { forestTheme } from "@/registry/themes";++<ComponentPreview+ base="forme"+ name="invoice-classic"+ theme={forestTheme}+ hideCode+/>## Installationdiff --git a/content/docs/themes/minimal.mdx b/content/docs/themes/minimal.mdxindex 1b727ee..ab68ad8 100644--- a/content/docs/themes/minimal.mdx+++ b/content/docs/themes/minimal.mdx@@ -3,10 +3,12 @@ title: "Minimal"description: "Courier headings, zinc neutrals, maximum whitespace."---+import { minimalTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-minimal"- theme="minimal"+ theme={minimalTheme}hideCode/>diff --git a/content/docs/themes/modern.mdx b/content/docs/themes/modern.mdxindex e5ff45d..c7d9d86 100644--- a/content/docs/themes/modern.mdx+++ b/content/docs/themes/modern.mdx@@ -3,7 +3,14 @@ title: "Modern"description: "All-Helvetica typography, slate-cool neutrals with subtle violet accent."----<ComponentPreview base="forme" name="invoice-modern" theme="modern" hideCode />+import { modernTheme } from "@/registry/themes";++<ComponentPreview+ base="forme"+ name="invoice-modern"+ theme={modernTheme}+ hideCode+/>## Installationdiff --git a/content/docs/themes/professional.mdx b/content/docs/themes/professional.mdxindex eb8a2ab..12cb256 100644--- a/content/docs/themes/professional.mdx+++ b/content/docs/themes/professional.mdx@@ -3,10 +3,12 @@ title: "Professional"description: "Serif headings, refined zinc/slate palette, formal document feel."---+import { professionalTheme } from "@/registry/themes";+<ComponentPreviewbase="forme"name="invoice-classic"- theme="professional"+ theme={professionalTheme}hideCode/>diff --git a/content/docs/themes/vivid.mdx b/content/docs/themes/vivid.mdxindex ba6ea2c..c35d9b9 100644--- a/content/docs/themes/vivid.mdx+++ b/content/docs/themes/vivid.mdx@@ -3,7 +3,14 @@ title: "Vivid"description: "Deep violet palette, Nunito rounded sans-serif, playful but professional."----<ComponentPreview base="forme" name="invoice-creative" theme="vivid" hideCode />+import { vividTheme } from "@/registry/themes";++<ComponentPreview+ base="forme"+ name="invoice-creative"+ theme={vividTheme}+ hideCode+/>## Installationdiff --git a/next.config.mjs b/next.config.mjsindex 5767a82..64ee84d 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -9,9 +9,6 @@ const { ROUTES } = await jiti.import("./constants/routes");/** @type {import('next').NextConfig} */const nextConfig = {devIndicators: false,- experimental: {- viewTransition: true,- },headers() {const link = [`<${ROUTES.API_CATALOG}>; rel="api-catalog"`,