### Complete PDFEasy Plugin Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/plugins.md A comprehensive example demonstrating the setup of PDFEasy with various plugin options, including custom headers, footers, backgrounds, and page-specific content. ```typescript import pdfeasy from 'pdfeasy' pdfeasy.new({ document: { margins: { top: 50, bottom: 50, left: 50, right: 50 }, size: 'A4' }, plugins: [ { // Run before content rendering onBefore: () => { console.log('Starting PDF generation') }, // Background for every page background: (page) => { // Return a light gray background return '#F5F5F5' // Or return false to skip background }, // Callbacks to render on each page after content page: [ // Footer with page numbers ({ Text }, context, current, total) => { Text(`Page ${current}/${total}`, { fontSize: 10, color: '#999999' }, { x: context.width / 2, y: context.height - 30, widthAnchor: 'center', heightAnchor: 'center' }) }, // Header ({ Text }, context) => { Text('Company Logo Document', { fontSize: 12, bold: true, color: '#000000' }, { x: 50, y: 20 }) }, // Side decoration ({ Text }, context, current) => { if (current === 1) { Text('CONFIDENTIAL', { fontSize: 48, color: '#CCCCCC', opacity: 0.2 }, { x: context.width / 2, y: context.height / 2, widthAnchor: 'center', heightAnchor: 'center' }) } } ], // Run after PDF finalization onAfter: () => { console.log('PDF generation complete') } } ] }) // Add content pdfeasy.add([ { raw: 'Main Document', text: { fontSize: 24, bold: true } }, { lineBreak: { spacing: 10 } }, { raw: 'This document has headers, footers, and page numbers.', text: {} } ]) // Generate PDF pdfeasy.run({ type: 'client', clientEmit: 'blob' }).then(blobUrl => { const iframe = document.querySelector('iframe') iframe.src = blobUrl }) ``` -------------------------------- ### Install Dependencies Source: https://github.com/betterwrite/pdfeasy/blob/main/packages/playground/README.md Install project dependencies using npm, pnpm, or yarn. ```bash # npm npm install # pnpm pnpm install # yarn yarn install ``` -------------------------------- ### Start Playground Development Server Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md Starts the development server for the Nuxt playground application. ```bash # Start playground dev server pnpm play:dev ``` -------------------------------- ### Start Core Package Demo Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md Starts the Vite development server for the core package. This command should be run from the `packages/core` directory after building. ```bash # Start demo (core package vite dev server, port 3000) # Run from packages/core after building pnpm demo ``` -------------------------------- ### Install Dependencies Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md Installs project dependencies using pnpm. Ensure pnpm is installed before running. ```bash # Install deps (pnpm required) pnpm install ``` -------------------------------- ### Start Development Server Source: https://github.com/betterwrite/pdfeasy/blob/main/packages/playground/README.md Start the Nuxt 3 development server on http://localhost:3000 using npm, pnpm, or yarn. ```bash # npm npm run dev # pnpm pnpm run dev # yarn yarn dev ``` -------------------------------- ### Install PDFEasy Source: https://github.com/betterwrite/pdfeasy/blob/main/README.md Install the PDFEasy library using npm. ```shell npm i pdfeasy ``` -------------------------------- ### usePDF() Usage Example - Warning vs. Correct Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/vue-integration.md Demonstrates incorrect usage of usePDF() at the module level (logs warning) and correct usage within a setup function. ```typescript // ❌ This will log a warning const pdf = usePDF() // Called at module level // ✅ This is correct function myComponent() { const pdf = usePDF() // Called inside setup } ``` -------------------------------- ### Install vue-pdfeasy and pdfeasy Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/vue-integration.md Install the necessary packages for Vue 3 integration with PDFEasy. ```bash npm install vue-pdfeasy pdfeasy ``` -------------------------------- ### Complete Nuxt 3 Configuration Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/nuxt-integration.md A full example of the `nuxt.config.ts` file including the 'nuxt-pdfeasy' module and a compatibility date. ```typescript export default defineNuxtConfig({ modules: ['nuxt-pdfeasy'], compatibilityDate: '2024-01-01' }) ``` -------------------------------- ### Example Plugin Implementation Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/configuration.md Demonstrates how to implement a plugin with custom background color, page numbering, and lifecycle hooks for PDF generation. ```typescript pdfeasy.new({ plugins: [ { onBefore: () => { console.log('PDF generation starting') }, background: (page) => { return '#F5F5F5' // Light gray background }, page: [ ({ Text }, context, current, total) => { Text(`Page ${current}/${total}`, {}, { x: context.width / 2, y: context.height - 30, widthAnchor: 'center' } ) } ], onAfter: () => { console.log('PDF generation complete') } } ] }) ``` -------------------------------- ### Install nuxt-pdfeasy and pdfeasy Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/nuxt-integration.md Install the necessary packages for Nuxt 3 integration. This includes both the Nuxt module and the core PDFEasy library. ```bash npm install nuxt-pdfeasy pdfeasy ``` -------------------------------- ### Install Nuxt PDFEasy Module Source: https://github.com/betterwrite/pdfeasy/blob/main/README.md Install the Nuxt PDFEasy module using npm. ```bash npm i nuxt-pdfeasy ``` -------------------------------- ### Complete PDFeasy Utilities Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/utilities.md This comprehensive example demonstrates how to use various utility functions from the PDFeasy library. It covers checking the execution environment, accessing default configurations, retrieving page sizes, testing regular expression patterns for URLs, base64 strings, and hex colors, converting hex to CMYK, and finally, creating and saving a simple PDF document with CMYK color schema. ```typescript import pdfeasy, { isBrowser, pdfDefaults, pageSizes, regex, HEXToCMYK } from 'pdfeasy' // Check environment console.log('Running in browser:', isBrowser) // Get default configuration const defaults = pdfDefaults() console.log('Default text size:', defaults.text.fontSize) // Access page sizes const sizes = pageSizes() const [a4Width, a4Height] = sizes.A4 console.log(`A4: ${a4Width} × ${a4Height} points`) // Test regex patterns console.log(regex().http('https://example.com')) // Has match console.log(regex().base64('iVBORw0KGgo...')) // Has match console.log(regex().hex('#FF0000')) // Has match // Convert colors for print const printColor = HEXToCMYK('#FF0000') console.log('Print color (CMYK):', printColor) // [0, 100, 100, 0] // Use in PDF pdfeasy.new({ document: { size: 'A4' } }) pdfeasy.add([ { raw: 'Print Document', text: { color: '#FF0000' } } ]) pdfeasy.run({ type: 'client', clientEmit: 'save', colorSchema: 'CMYK' }) ``` -------------------------------- ### Registering a Background Plugin Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/plugins.md Example of how to register a plugin to set a solid color or image as the background for each new page. ```typescript import pdfeasy from 'pdfeasy' pdfeasy.new({ plugins: [ { background: (page) => { // Return a color for solid background return '#F0F0F0' // Or return an image URL // return 'https://example.com/background.jpg' }, page: [] } ] }) ``` -------------------------------- ### Vue 3 Setup Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/GUIDE.md Sets up the Vue application to use the PDFeasy plugin. ```typescript import { createApp } from 'vue' import { PDFPlugin } from 'vue-pdfeasy' import App from './App.vue' const app = createApp(App) app.use(PDFPlugin) app.mount('#app') ``` -------------------------------- ### Complete Font Workflow Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/fonts-vfs.md Demonstrates the full process of initializing pdfeasy, registering custom fonts, adding content that uses these fonts, and generating the PDF. Ensure font URLs are accessible. ```typescript import pdfeasy from 'pdfeasy' // Step 1: Initialize PDF pdfeasy.new({ document: { margins: { top: 40, bottom: 40, left: 70, right: 70 }, size: 'A4' }, advanced: { fontsPurge: true, // Only load used fonts backgroundPurge: true } }) // Step 2: Register custom fonts pdfeasy.addFonts([ { name: 'CustomSerif', normal: 'https://cdn.example.com/CustomSerif-Regular.ttf', bold: 'https://cdn.example.com/CustomSerif-Bold.ttf', italic: 'https://cdn.example.com/CustomSerif-Italic.ttf', bolditalic: 'https://cdn.example.com/CustomSerif-BoldItalic.ttf' }, { name: 'CustomSans', normal: 'https://cdn.example.com/CustomSans-Regular.ttf', bold: 'https://cdn.example.com/CustomSans-Bold.ttf', italic: 'https://cdn.example.com/CustomSans-Italic.ttf', bolditalic: 'https://cdn.example.com/CustomSans-BoldItalic.ttf' } ]) // Step 3: Add content using custom fonts pdfeasy.add([ { raw: 'Title in Custom Serif', text: { font: 'CustomSerif', // This font will be loaded fontSize: 24, bold: true // Will use CustomSerif-Bold } }, { raw: 'Body text in Custom Sans', text: { font: 'CustomSans', // This font will also be loaded fontSize: 12 } } // Note: If we had registered a third font but never referenced it, // it would NOT be loaded due to fontsPurge=true ]) // Step 4: Generate PDF // During run(), setExternalFonts() is called automatically: // - Detects fonts: 'CustomSerif' and 'CustomSans' // - Fetches all 8 font files (4 variants × 2 fonts) // - Registers them with PDFKit // - Renders content using the custom fonts pdfeasy.run({ type: 'client', clientEmit: 'blob' }).then(blobUrl => { window.open(blobUrl, '_blank') }) ``` -------------------------------- ### Install Vue PDFEasy Plugin Source: https://github.com/betterwrite/pdfeasy/blob/main/README.md Install the Vue PDFEasy plugin using npm. ```shell npm i vue-pdfeasy ``` -------------------------------- ### PDFEasy Plugin Example: Background Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md An example of a plugin with a `background` hook. This hook runs before each content item and can inject a full-page background image. ```javascript const myPlugin = { background: async (page, pdfKitDoc) => { // Add background image to the current page pdfKitDoc.image('path/to/background.png', 0, 0, { width: pdfKitDoc.page.width, height: pdfKitDoc.page.height }); } }; const pdf = new PDFEasy({ plugins: [myPlugin] }); ``` -------------------------------- ### Install PDFPlugin Globally Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/vue-integration.md Use the PDFPlugin to register a global PDFEasy instance accessible via $pdf. ```typescript import { PDFPlugin } from 'vue-pdfeasy' const app = createApp(App) app.use(PDFPlugin) app.mount('#app') ``` -------------------------------- ### Initialize PDF Document with Options Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/pdfeasy.md Initialize a new PDF document with custom options, including document dimensions, margins, and plugins. This example demonstrates adding a page number to each page. ```typescript pdfeasy.new({ document: { margins: { top: 40, bottom: 40, left: 70, right: 70 }, size: 'A4' }, plugins: [ { page: [ ({ Text }, context, current, total) => { Text(`Page ${current}/${total}`, {}, { x: context.width / 2, y: 50 }) } ] } ] }) ``` -------------------------------- ### PDFEasy Plugin Example: Page Callbacks Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md An example of a plugin with `page` callbacks. These callbacks run after the entire PDF pipeline has finished, allowing for headers, footers, or page numbers to be added to buffered pages. ```javascript const pageNumberPlugin = { page: async (pageNumber, pdfKitDoc) => { // Add page number to the bottom of the page pdfKitDoc.text(`Page ${pageNumber}`, 50, pdfKitDoc.page.height - 50); } }; const pdf = new PDFEasy({ plugins: [pageNumberPlugin] }); ``` -------------------------------- ### Nuxt.js Setup Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/GUIDE.md Configure the nuxt-pdfeasy module in your nuxt.config.ts file. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-pdfeasy'] }) ``` -------------------------------- ### Vitest Test Environment Setup Source: https://github.com/betterwrite/pdfeasy/blob/main/CLAUDE.md Configuration for Vitest tests using `happy-dom` as the test environment. This setup is typically found in `vitest.config.ts`. ```javascript import { defineConfig } from 'vitest/config'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], test: { environment: 'happy-dom', setupFiles: ['./vitest.setup.ts'], coverage: { provider: 'v8', reporter: ['text', 'json', 'html'] } }, }); ``` -------------------------------- ### HTTP Font Registration Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/fonts-vfs.md Illustrates registering fonts directly from HTTP URLs. This method is compatible with both client-side (browser) and server-side environments. ```typescript pdfeasy.addFonts([ { name: 'RemoteFont', normal: 'https://fonts.example.com/RemoteFont-Regular.ttf', bold: 'https://fonts.example.com/RemoteFont-Bold.ttf', italic: 'https://fonts.example.com/RemoteFont-Italic.ttf', bolditalic: 'https://fonts.example.com/RemoteFont-BoldItalic.ttf' } ]) // Works in both client and server modes ``` -------------------------------- ### Generate Image Gallery PDF Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/http-images.md A complete example demonstrating how to create a PDF document with an image gallery by iterating through an array of image URLs and embedding them. ```typescript import pdfeasy from 'pdfeasy' const images = [ 'https://example.com/photo1.jpg', 'https://example.com/photo2.jpg', 'https://example.com/photo3.jpg' ] pdfeasy.new({ document: { margins: { top: 20, bottom: 20, left: 20, right: 20 }, size: 'A4' } }) pdfeasy.add([ { raw: 'Image Gallery', text: { fontSize: 24, bold: true } }, { lineBreak: { spacing: 10 } } ]) // Add images for (let i = 0; i < images.length; i++) { pdfeasy.add([ { raw: images[i], image: { size: { width: 200, height: 200, scale: 1 }, x: 30, y: undefined // Auto position } }, { lineBreak: { spacing: 15 } } ]) } pdfeasy.run({ type: 'client', clientEmit: 'blob' }).then(blobUrl => { window.open(blobUrl, '_blank') }).catch(error => { console.error('Failed to generate PDF:', error) }) ``` -------------------------------- ### runPluginBackground() Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/plugins.md Executes background plugins at the start of each page. It iterates through registered plugins and calls the `background` callback if a new page is detected. The callback can return a color or image URL to set the page background. ```APIDOC ## runPluginBackground() ### Description Executes background plugins at the start of each page. It iterates through registered plugins and calls the `background` callback if a new page is detected. The callback can return a color or image URL to set the page background. ### Method `runPluginBackground(instance: PDFEasy): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **instance** (`PDFEasy`) - Required - PDFEasy instance with plugins ### Request Example ```ts import pdfeasy from 'pdfeasy' pdfeasy.new({ plugins: [ { background: (page) => { // Return a color for solid background return '#F0F0F0' // Or return an image URL // return 'https://example.com/background.jpg' }, page: [] } ] }) ``` ### Response #### Success Response (200) `Promise` #### Response Example ```json // No specific JSON response example, returns a Promise that resolves to void. ``` ### Behavior - Iterates through all registered plugins - For each plugin with a `background` callback: - Checks if `__NEW_PAGE__` flag is true (new page started) - Calls `background(page)` callback - If callback returns a truthy string, calls `setBackground()` to render background - Sets `__NEW_PAGE__` to false after processing ### Background Callback Return Value - Return falsy value to skip background rendering - Return a hex color string (e.g., '#FF0000') to fill page with solid color - Return an image URL or base64 string to render image background ``` -------------------------------- ### Vue App Setup with PDFPlugin Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/vue-integration.md Configure your main Vue application to use the PDFEasy plugin. This involves importing the plugin and calling `app.use()` before mounting the app. ```vue ``` ```ts import { createApp } from 'vue' import { PDFPlugin } from 'vue-pdfeasy' import App from './App.vue' const app = createApp(App) // Install PDFEasy plugin app.use(PDFPlugin) app.mount('#app') ``` -------------------------------- ### Vue 3 PDF Generation Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/README.md Shows how to use the `vue-pdfeasy` composable to generate PDFs within a Vue 3 application. This example generates a PDF and opens it in a new window. ```vue ``` -------------------------------- ### Generate PDF using Global Property $pdf Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/vue-integration.md Example of generating a PDF in a Vue component using the global $pdf property accessed via getCurrentInstance. ```vue ``` -------------------------------- ### Font Purging Example with HTTP Fonts Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/fonts-vfs.md Demonstrates registering multiple font variants from HTTP URLs and adding content that references specific fonts. Only the referenced fonts will be loaded and registered during the run phase. ```typescript pdfeasy.addFonts([ { name: 'Roboto', normal: 'https://cdn.example.com/Roboto-Regular.ttf', bold: 'https://cdn.example.com/Roboto-Bold.ttf', italic: 'https://cdn.example.com/Roboto-Italic.ttf', bolditalic: 'https://cdn.example.com/Roboto-BoldItalic.ttf' }, { name: 'Open Sans', normal: 'https://cdn.example.com/OpenSans-Regular.ttf', bold: 'https://cdn.example.com/OpenSans-Bold.ttf', italic: 'https://cdn.example.com/OpenSans-Italic.ttf', bolditalic: 'https://cdn.example.com/OpenSans-BoldItalic.ttf' } ]) pdfeasy.add([ { raw: 'This uses Roboto', text: { font: 'Roboto' } }, // Note: Open Sans is NOT used, so it won't be loaded ]) // During run(), only Roboto is fetched and registered await setExternalFonts(pdfeasy) ``` -------------------------------- ### Font Variant Resolution Example Source: https://github.com/betterwrite/pdfeasy/blob/main/_autodocs/api-reference/fonts-vfs.md Demonstrates how font families and variants are resolved for styling text. This shows the mapping from style properties to PDFKit font names. ```typescript // When rendering text with bold=true and italic=false: const fontName = resolveFontFamily('Roboto', { bold: true }) // Returns: 'Roboto-Bold' // Then during registration, the variant name is resolved: const registeredName = resolveFontName('Roboto', 'bold') // Returns: 'Roboto-Bold' // PDFKit then uses: doc.font('Roboto-Bold') ``` -------------------------------- ### Generate PDF with Custom Headers and Footers in Nuxt3 Source: https://github.com/betterwrite/pdfeasy/blob/main/packages/nuxt/README.md Example demonstrating how to generate a PDF with custom headers and footers using the PDFEasy module in Nuxt3. This includes adding text content and configuring plugins for page numbering and headers. ```typescript