Print & Templates
Complete guide to NkapBooks Print & Templates — the Template Builder, print templates, print settings, supported print documents, template variables, PDF export, and direct printing.
12. Print & Templates
NkapBooks includes a powerful print template system that lets you design, customize, and generate professional documents — invoices, receipts, quotes, payment vouchers, and more. The system combines a visual Template Builder with a code editor, pre-built templates, and full PDF export and direct printing capabilities.
| Component | Schema / Location | Description |
|---|---|---|
| Print Templates | PrintTemplate schema | Template records that define the layout for each document type |
| Template Builder | /template-builder/:name | Interactive editor with live preview, code editing, and variable hints |
| Print Settings | PrintSettings schema | Global settings for logo, colors, fonts, and display options |
| Supported Documents | Various schemas | All document types that support printing |
| Template Variables | getPrintTemplatePropValues() | Data available to templates at render time |
| PDF Export & Printing | Tauri backend | Generate PDFs and send documents to a physical printer |
| Default Templates | Template files | Built-in templates shipped with NkapBooks |
12.0 Print System Overview
The NkapBooks print system works through three layers:
┌──────────────────────────────────────────────────────────┐
│ 1. Print Template (Vue HTML Template) │
│ Defines the layout using HTML, CSS, and Vue syntax │
├──────────────────────────────────────────────────────────┤
│ 2. Template Variables (doc + print) │
│ Document data and print settings injected at render │
├──────────────────────────────────────────────────────────┤
│ 3. Rendering Engine │
│ Vue compiler → HTML → PDF (via Tauri) or Print │
└──────────────────────────────────────────────────────────┘
How It Works
- A PrintTemplate record stores the Vue HTML template code, the target document type, and the page dimensions
- When you click Print or Save as PDF on a document, NkapBooks:
- Loads the appropriate template (default or custom)
- Fetches the document data and print settings
- Compiles the template using the Vue compiler
- Renders the template with the document data injected as props
- Generates the final HTML with all CSS styles
- Sends the HTML to the Tauri backend for PDF generation or printing
Accessing Print Templates
| Method | Path | Description |
|---|---|---|
| Sidebar | Setup → Print Templates | List view of all templates |
| Direct URL | /list/PrintTemplate/Print Templates | List view via URL |
| Template Builder | /template-builder/:name | Opens editor for a specific template |
| Document Action | Print button on any printable document | Uses the assigned default template |
12.1 Print Templates
A Print Template (PrintTemplate) is a document that stores the HTML/CSS layout used to render printable versions of business documents.
PrintTemplate Schema
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
name | Data | ✅ | — | Unique template name (e.g., "Standard - Sales Invoice") |
type | AutoComplete | ✅ | SalesInvoice | The document type this template is designed for |
template | Text | ✅ | — | Vue HTML template code |
height | Float | — | 29.7 | Page height in centimeters |
width | Float | — | 21 | Page width in centimeters |
isCustom | Check (read-only) | — | true | true for user-created templates, false for built-in |
Template Types
Each template is associated with a specific document type. The available types are:
| Type | Schema Name | Description |
|---|---|---|
| Sales Invoice | SalesInvoice | Customer-facing invoice |
| Sales Quote | SalesQuote | Customer quotation / estimate |
| Purchase Invoice | PurchaseInvoice | Vendor bill |
| Journal Entry | JournalEntry | Journal voucher |
| Payment | Payment | Payment receipt |
| Shipment | Shipment | Delivery note |
| Purchase Receipt | PurchaseReceipt | Goods received note |
| Stock Movement | StockMovement | Internal stock transfer |
| Inventory Adjustment | InventoryAdjustment | Inventory correction |
| POS Session | POSSession | POS shift summary report |
Built-in vs Custom Templates
| Property | Built-in Templates | Custom Templates |
|---|---|---|
isCustom | false | true |
| Can Delete | ❌ No | ✅ Yes |
| Can Edit Name | ❌ No | ✅ Yes |
| Can Edit Type | ❌ No | ✅ Yes |
| Can Edit Template | ❌ No (read-only) | ✅ Yes |
| Auto-Updated | ✅ Updated on app upgrade | ❌ Never overwritten |
Creating a Custom Template
There are three ways to create a custom template:
1. Duplicate an Existing Template
- Open an existing template in the Template Builder
- Click the ⋮ Actions menu → Duplicate
- The duplicate is created with
isCustom: trueand opens for editing - Rename the template and customize the layout
2. Create from Scratch
- Navigate to Setup → Print Templates
- Click + New Print Template
- Enter a Template Name
- Select the Template Type (document type)
- The editor opens with a base starter template
- Write your custom HTML/CSS/Vue code
3. Import a Template File
- Open the Template Builder for any custom template
- Click ⋮ Actions → Select Template File
- Choose an
.htmlfile from your computer - The file contents are loaded into the editor
List View
The Print Template list view shows:
| Column | Description |
|---|---|
name | Template name |
type | Document type (displayed as human-readable label) |
isCustom | Whether this is a custom template |
Clicking a template navigates to the Template Builder at /template-builder/:name.
12.2 Template Builder
The Template Builder is a full-featured template editing environment that combines a live preview, code editor, and variable reference panel in a single page.
Layout
The Template Builder page is divided into three main sections:
┌──────────────────────────────────────────────────────────┐
│ Header: Template Name | Save | Print | PDF | Actions ▼ │
├──────────────────────┬───────────────────────────────────┤
│ │ │
│ Live Preview │ Code Editor │
│ (Scaled paper) │ (Vue/HTML/CSS) │
│ │ │
│ Display Doc │ ─────────────────────────────── │
│ Selector │ Keyboard Shortcuts │
│ │ ─────────────────────────────── │
│ Scale Slider │ Key Hints Panel │
│ │ (Collapsible) │
│ │ │
└──────────────────────┴───────────────────────────────────┘
Header Actions
| Button | Shortcut | Description |
|---|---|---|
| Save | Ctrl+S | Save the template to the database |
| — | Send the current preview to the printer | |
| — | Export the current preview as a PDF file | |
| ⋮ Actions | — | Dropdown with additional actions |
Actions Menu
| Action | Availability | Description |
|---|---|---|
| Print Settings | Always | Opens the Print Settings configuration |
| Set Template Type | Custom templates only | Change the document type for this template |
| Set Print Size | Custom templates only | Set page dimensions (A4, Letter, Legal, Custom) |
| Select Template File | Custom templates only | Import an HTML template file from disk |
| Save Template File | Always | Export the template code as an HTML file |
| Duplicate | Always | Create a custom copy of this template |
| Delete | Custom templates only | Delete this template |
Live Preview Panel (Left)
The left panel shows a scaled paper preview that renders the template in real-time as you edit the code:
| Control | Description |
|---|---|
| Display Doc | Select which document to use for preview data (e.g., a specific invoice) |
| Scale Slider | Adjust the zoom level of the preview (default: 0.6x) |
| Paper Size | Shows the actual page dimensions with proper aspect ratio |
The preview automatically picks the most recent non-cancelled document of the template's type as the initial display document. You can change this to any document using the Link selector.
Code Editor (Right)
The code editor is built on CodeMirror 6 and provides:
| Feature | Description |
|---|---|
| Syntax Highlighting | Vue/HTML syntax highlighting with custom color theme |
| Autocomplete | Context-aware autocompletion for template variables |
| Line Numbers | Gutter with line numbers |
| Search & Replace | Built-in find/replace (Ctrl+F, Ctrl+H) |
| Read-Only Mode | Automatically applied for built-in (non-custom) templates |
The autocomplete system knows all available template variables and provides suggestions as you type inside Vue template expressions ({{ }} and v-bind attributes).
Edit Mode
The Template Builder has two display modes:
| Mode | Description |
|---|---|
| Preview Mode (default) | Side-by-side preview and editor, sidebar visible |
| Edit Mode | Full-width editor with maximized preview, sidebar hidden |
Toggle between modes using the Edit Mode button. When entering edit mode:
- The sidebar is hidden to maximize screen space
- The scale is automatically adjusted to fit the preview optimally
- A toast notification confirms the mode change
Apply changes with Ctrl+Enter to see the preview update.
Key Hints Panel
The Key Hints panel (toggle with the hints button) shows all available template variables organized hierarchically:
| Category | Prefix | Description |
|---|---|---|
| Document Data | doc.* | Fields from the document being printed |
| Print Settings | print.* | Fields from PrintSettings and AccountingSettings |
Each variable is displayed with its key path and current value type (string, object, or array). Click on collapsible items to expand nested objects and arrays.
Page Size Configuration
The Set Print Size dialog supports pre-defined and custom page sizes:
| Size | Width (cm) | Height (cm) |
|---|---|---|
| A4 | 21 | 29.7 |
| Letter | 21.59 | 27.94 |
| Legal | 21.59 | 35.56 |
| Custom | User-defined | User-defined |
Template Syntax
Templates use Vue 3 template syntax with three injected props:
| Prop | Type | Description |
|---|---|---|
doc | Object | Document data (fields, items, totals, party info) |
print | Object | Print settings (logo, company name, colors, address) |
t | Function | Translation function for i18n support |
Example template structure:
<main class="h-full w-full bg-white">
<header class="p-4 flex justify-between border-b">
<h2 class="font-semibold text-2xl" :style="{ color: print.color }">
{{ print.companyName }}
</h2>
<h2 class="font-semibold text-2xl">
{{ doc.name }}
</h2>
</header>
<div class="p-4">
<!-- Your template content here -->
</div>
</main>
Template Compilation Errors
If your template has syntax errors, the preview panel shows a red error screen with:
| Field | Description |
|---|---|
| Error Name | Type of error (e.g., "Template Compilation Error") |
| Error Message | Description of what went wrong |
| Code Frame | The relevant section of template code with the error highlighted |
Common errors include:
- Missing closing tags
- Invalid Vue directive syntax
- Referencing undefined variables (shows as "Invalid Key Error" with hint to check Key Hints)
12.3 Print Settings
The Print Settings (PrintSettings) schema is a singleton document that controls the global appearance of all printed documents. It is configured from Settings → Print tab.
PrintSettings Schema
Default Section
| Field | Type | Description |
|---|---|---|
logo | AttachImage | Company logo image for printed documents |
companyName | Data | Company name displayed on documents |
Contacts Section
| Field | Type | Description |
|---|---|---|
email | Data | Company email address for printed documents |
phone | Data | Company phone number for printed documents |
address | Link → Address | Company address (can create a new address inline) |
Customizations Section
| Field | Type | Default | Description |
|---|---|---|---|
color | Color | #112B42 (Black) | Primary accent color used in templates |
font | Select | Arial | Font family: Arial, Times New Roman, or Courier |
displayLogo | Check | true | Show company logo on invoices |
amountInWords | Check | true | Display grand total in words (e.g., "One Thousand Two Hundred") |
displayTime | Check | true | Show time along with date on invoices |
displayDescription | Check | false | Show item descriptions on invoices |
displaytermsandconditions | Check | false | Show terms and conditions section |
posPrintWidth | Float | 8 | Width (in cm) for POS receipt printing |
termsAndConditions | Text | — | Terms and conditions text displayed on documents |
Available Colors
The color picker provides these pre-defined options:
| Color | Hex Value |
|---|---|
| Red | #f56565 |
| Orange | #ed8936 |
| Yellow | #ecc94b |
| Green | #48bb78 |
| Teal | #38b2ac |
| Blue | #33a1ff |
| Indigo | #667eea |
| Purple | #9f7aea |
| Pink | #ed64a6 |
| Black | #112B42 |
You can also enter any custom hex color value.
How Print Settings Are Used
Print settings values are injected into every template via the print prop. Templates access them as:
| Template Variable | Source Field | Example Output |
|---|---|---|
print.companyName | companyName | "My Business LLC" |
print.color | color | "#33a1ff" |
print.logo | logo | Image data URL |
print.email | email | "info@mybusiness.com" |
print.phone | phone | "+1-555-0123" |
print.displayLogo | displayLogo | true |
print.amountInWords | amountInWords | true |
print.font | font | "Arial" |
print.displayTime | displayTime | true |
print.address | Resolved address | Full address text |
Additionally, key fields from AccountingSettings are merged into the print object:
| Template Variable | Source | Description |
|---|---|---|
print.gstin | AccountingSettings.gstin | GST Identification Number (India) |
print.country | AccountingSettings.country | Country name |
print.currency | AccountingSettings.currency | Default currency |
12.4 Supported Print Documents
The following document types support printing and PDF export. Each type has its own set of template variables reflecting its schema fields.
Transactional Documents
| Document | Schema | Typical Use |
|---|---|---|
| Sales Invoice | SalesInvoice | Customer invoices for goods/services sold |
| Sales Quote | SalesQuote | Quotations/estimates sent to prospects |
| Purchase Invoice | PurchaseInvoice | Vendor bills received for purchases |
| Payment | Payment | Payment receipts for money received or paid |
| Journal Entry | JournalEntry | Journal vouchers for manual accounting entries |
Inventory Documents
| Document | Schema | Typical Use |
|---|---|---|
| Shipment | Shipment | Delivery notes for goods dispatched to customers |
| Purchase Receipt | PurchaseReceipt | Goods received notes from suppliers |
| Stock Movement | StockMovement | Internal stock transfer documents |
| Inventory Adjustment | InventoryAdjustment | Stock correction documents |
POS Documents
| Document | Schema | Typical Use |
|---|---|---|
| POS Session | POSSession | Shift summary report with totals, items sold, and payment breakdown |
Default Template Assignments
Each document type can have a default print template assigned in Settings → Defaults:
| Setting Field | Document Type | Description |
|---|---|---|
salesInvoicePrintTemplate | Sales Invoice | Default template for sales invoices |
salesQuotePrintTemplate | Sales Quote | Default template for sales quotes |
purchaseInvoicePrintTemplate | Purchase Invoice | Default template for purchase invoices |
journalEntryPrintTemplate | Journal Entry | Default template for journal entries |
paymentPrintTemplate | Payment | Default template for payment receipts |
shipmentPrintTemplate | Shipment | Default template for shipments |
purchaseReceiptPrintTemplate | Purchase Receipt | Default template for purchase receipts |
stockMovementPrintTemplate | Stock Movement | Default template for stock movements |
inventoryAdjustmentPrintTemplate | Inventory Adjustment | Default template for inventory adjustments |
posPrintTemplate | POS (Sales Invoice) | Default template for POS receipts |
SalesInvoice type but is specifically optimized for receipt printing with the POS print width setting. POS profiles can also override the default POS print template via the posPrintTemplate field on the POS Profile.12.5 Template Variables
When a template is rendered, NkapBooks collects data from the document, print settings, and related records, then injects it as two top-level props: doc and print.
Document Variables (doc.*)
The exact variables available depend on the document type, but common fields include:
Common Document Fields
| Variable | Type | Description |
|---|---|---|
doc.name | string | Document ID (e.g., "SINV-00042") |
doc.date | string | Formatted document date |
doc.party | string | Customer or supplier name |
doc.entryType | string | Schema name (e.g., "SalesInvoice") |
doc.entryLabel | string | Human-readable schema label (e.g., "Sales Invoice") |
doc.submitted | boolean | Whether the document is submitted |
Financial Fields (Invoices, Payments)
| Variable | Type | Description |
|---|---|---|
doc.grandTotal | string | Formatted grand total amount |
doc.baseGrandTotal | string | Formatted grand total in base currency |
doc.netTotal | string | Formatted net total (before tax) |
doc.outstandingAmount | string | Formatted outstanding/unpaid amount |
doc.totalTax | string | Formatted total tax amount |
doc.totalDiscount | string | Formatted total discount (for invoices) |
doc.grandTotalInWords | string | Grand total spelled out in words |
doc.showHSN | boolean | Whether items have HSN codes (for invoices) |
Items Array (Invoices, Quotes)
| Variable | Type | Description |
|---|---|---|
doc.items | Array | Line items on the document |
doc.items[n].item | string | Item name |
doc.items[n].description | string | Item description |
doc.items[n].quantity | number | Quantity |
doc.items[n].unit | string | Unit of measure |
doc.items[n].rate | string | Formatted unit price |
doc.items[n].amount | string | Formatted line total |
doc.items[n].hsnCode | string | HSN/SAC code (India) |
Tax Summary Array
| Variable | Type | Description |
|---|---|---|
doc.taxes | Array | Tax breakdown |
doc.taxes[n].account | string | Tax account name |
doc.taxes[n].amount | string | Formatted tax amount |
Party Information
| Variable | Type | Description |
|---|---|---|
doc.party.name | string | Party name |
doc.party.phone | string | Party phone number |
doc.party.email | string | Party email address |
doc.party.address | string | Party address |
doc.party.gstin | string | Party GSTIN (India) |
Payment Details
| Variable | Type | Description |
|---|---|---|
doc.paymentDetails | Array | Associated payments |
doc.paymentDetails[n].amount | string | Payment amount |
doc.paymentDetails[n].amountPaid | string | Amount paid |
doc.paymentDetails[n].paymentMethod | string | Payment method used |
doc.paymentDetails[n].outstandingAmount | string | Remaining outstanding |
POS Session Variables
POS Session templates receive additional specialized variables:
| Variable | Type | Description |
|---|---|---|
doc.openedBy | string | User who opened the session |
doc.closedBy | string | User who closed the session |
doc.openingDate | string | Session opening date/time |
doc.closingDate | string | Session closing date/time |
doc.totalInvoiceAmount | string | Total revenue during session |
doc.totalItemsQuantity | number | Total items sold |
doc.sessionAmounts | Array | Per-payment-method breakdown |
doc.sessionAmounts[n].paymentMethod | string | Payment method name |
doc.sessionAmounts[n].openingAmount | string | Opening cash amount |
doc.sessionAmounts[n].closingAmount | string | Closing cash amount |
doc.sessionAmounts[n].expectedAmount | string | Expected amount |
doc.sessionAmounts[n].differenceAmount | string | Cash difference |
doc.itemsSold | Array | Items sold during session |
doc.itemsSold[n].item | string | Item name |
doc.itemsSold[n].quantity | number | Total quantity sold |
doc.itemsSold[n].amount | string | Total revenue for item |
Print Variables (print.*)
| Variable | Type | Description |
|---|---|---|
print.companyName | string | Company name from PrintSettings |
print.logo | string | Logo image data |
print.color | string | Accent color hex value |
print.font | string | Font family name |
print.email | string | Company email |
print.phone | string | Company phone |
print.address | string | Company address |
print.displayLogo | boolean | Whether to show the logo |
print.amountInWords | boolean | Whether to show amount in words |
print.displayTime | boolean | Whether to show time |
print.gstin | string | Company GSTIN (from AccountingSettings) |
print.country | string | Country (from AccountingSettings) |
print.currency | string | Currency (from AccountingSettings) |
Translation Function (t)
Templates can use the t function for internationalized strings:
<p>{{ t`Invoice` }}</p>
<p>{{ t`Amount Due` }}: {{ doc.outstandingAmount }}</p>
This ensures templates work correctly regardless of the user's language setting.
12.6 PDF Export & Printing
NkapBooks uses the Tauri backend to generate PDFs and send documents to the system printer. Both operations work by converting the rendered template HTML into a complete standalone document.
PDF Export
When you click Save as PDF (or trigger it programmatically):
- The template is rendered with document data in the preview panel
- The rendered innerHTML is extracted from the preview container
- A complete HTML document is constructed with all CSS styles embedded
- A save dialog prompts for the file path (default name: document name +
.pdf) - The HTML is sent to the Tauri backend via the
makePDFcommand - The backend generates the PDF using the specified width and height
- A success toast is shown with an option to open the containing folder
Direct Printing
When you click Print:
- The same rendering and HTML construction process occurs
- Instead of saving a file, the HTML is sent to the Tauri
printDocumentcommand - The system print dialog appears for printer selection and settings
- A success or failure toast is shown
HTML Document Construction
The print document includes:
| Component | Description |
|---|---|
| Meta charset | UTF-8 encoding declaration |
| Application CSS | All CSS rules from the application's stylesheets (Tailwind, custom styles) |
| Print CSS | Special @media print rules that reset margins and padding |
| Template HTML | The rendered template content |
The print CSS ensures clean output:
| Rule | Purpose |
|---|---|
margin: 0 on html, body | Remove browser default margins |
@page { margin: 0 } | Remove page margins |
box-sizing: border-box | Consistent sizing model |
Timeout Protection
Both PDF generation and printing have timeout protection:
| Operation | Timeout | Error Message |
|---|---|---|
| PDF Generation | 60 seconds | "PDF generation timed out. Please try again." |
| Printing | 30 seconds | "Print operation timed out. Please try again." |
Loading Feedback
While generating a PDF or printing, a loading toast is displayed:
| Operation | Message |
|---|---|
| PDF Export | "Generating PDF..." |
| Printing | "Preparing document for print..." |
Printing from the Template Builder
The Template Builder provides both Print and PDF buttons in the header:
- PDF Button — Exports the current preview as a PDF file
- Print Button — Sends the current preview to the system printer
Both use the currently selected Display Doc for data and the current template code for layout.
12.7 Default Templates
NkapBooks ships with built-in default templates for the most common document types. These templates are automatically created and updated during the setup process.
Template File Naming Convention
Built-in template files follow this naming pattern:
TemplateName[.SchemaName].template.html
| Pattern | Behavior |
|---|---|
Standard.template.html | Creates templates for SalesInvoice, SalesQuote, and PurchaseInvoice |
Standard.Payment.template.html | Creates a template specifically for Payment documents |
Standard.JournalEntry.template.html | Creates a template specifically for Journal Entry |
When no schema name is specified in the file name, the template is automatically created for three default types: Sales Invoice, Sales Quote, and Purchase Invoice.
Template Update Behavior
During application setup or upgrade, the updatePrintTemplates() function:
- Fetches all template files from the application resources
- Compares the file modification dates with the database records
- Updates only templates where the file is newer than the database record
- Never modifies custom templates (
isCustom: true)
This means:
- Built-in templates are kept up-to-date automatically
- Your custom templates are never overwritten
- New templates added in updates appear automatically
Base Starter Template
When creating a new custom template, the editor starts with a base starter template:
<main class="h-full w-full bg-white">
<header class="p-4 flex justify-between border-b">
<h2
class="font-semibold text-2xl"
:style="{ color: print.color }"
>
{{ print.companyName }}
</h2>
<h2 class="font-semibold text-2xl">
{{ doc.name }}
</h2>
</header>
<div class="p-4 text-gray-600">
Edit the code in the Template Editor on the right
to create your own personalized custom template.
</div>
</main>
This provides a minimal starting point that demonstrates the basic template structure with doc and print variable usage.
Template Resources
Built-in template files are bundled with the application in the templates/ resource directory (configured in tauri.conf.json). The POS print width from Print Settings is passed to the template loader so POS-specific templates can adapt their layout width.
12.8 Workflow & Best Practices
Recommended Workflow
| Step | Action | Description |
|---|---|---|
| 1 | Configure Print Settings | Set logo, company name, color, and font in Settings → Print |
| 2 | Review built-in templates | Open a built-in template to see how it's structured |
| 3 | Duplicate and customize | Duplicate a built-in template to create your customized version |
| 4 | Set as default | Assign your custom template as the default in Settings → Defaults |
| 5 | Test with real data | Use the Display Doc selector to preview with different documents |
| 6 | Export a test PDF | Generate a PDF to verify the final output |
Template Design Tips
| Tip | Description |
|---|---|
| Use Tailwind classes | All Tailwind CSS utilities are available — use p-4, flex, text-lg, etc. |
Use print.color for accents | Bind your accent elements to :style="{ color: print.color }" for consistency |
Use the t function | Wrap all text labels in t`Label` for multi-language support |
| Handle missing data | Use v-if or ` |
| Test at actual size | Set scale to 1.0 in the preview to see the true print size |
| Keep templates simple | Complex JavaScript in templates can cause compilation errors — keep logic minimal |
Use @page CSS | For fine-grained print control, add @page CSS rules in a <style> block |
Exporting and Sharing Templates
| Action | How |
|---|---|
| Export template | Actions → Save Template File (saves as .html) |
| Import template | Actions → Select Template File (loads .html into editor) |
| Share with team | Export the template file and share it; the recipient imports it |
Troubleshooting
| Issue | Solution |
|---|---|
| Preview shows red error | Check the error message — fix syntax errors in the template code |
| "Invalid Key Error" | You're using a variable that doesn't exist — check the Key Hints panel |
| PDF is blank | Ensure the template has a root <main> or <div> element with content |
| Styles not applying | Tailwind classes work; custom CSS must be in an inline <style> block |
| POS receipt too wide/narrow | Adjust posPrintWidth in Settings → Print (default: 8 cm) |
| Template not updating | Built-in templates are read-only — duplicate to create an editable version |
| Print dialog doesn't appear | Check that the Tauri shell plugin is properly configured |