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.

ComponentSchema / LocationDescription
Print TemplatesPrintTemplate schemaTemplate records that define the layout for each document type
Template Builder/template-builder/:nameInteractive editor with live preview, code editing, and variable hints
Print SettingsPrintSettings schemaGlobal settings for logo, colors, fonts, and display options
Supported DocumentsVarious schemasAll document types that support printing
Template VariablesgetPrintTemplatePropValues()Data available to templates at render time
PDF Export & PrintingTauri backendGenerate PDFs and send documents to a physical printer
Default TemplatesTemplate filesBuilt-in templates shipped with NkapBooks
Print Templates are accessible from the sidebar under Setup → Print Templates. The Template Builder opens when you click on any template in the list. Print Settings are configured in Settings → Print tab. Default print template assignments per document type are configured in Settings → Defaults tab.

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

  1. A PrintTemplate record stores the Vue HTML template code, the target document type, and the page dimensions
  2. 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

MethodPathDescription
SidebarSetup → Print TemplatesList view of all templates
Direct URL/list/PrintTemplate/Print TemplatesList view via URL
Template Builder/template-builder/:nameOpens editor for a specific template
Document ActionPrint button on any printable documentUses 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

FieldTypeRequiredDefaultDescription
nameDataUnique template name (e.g., "Standard - Sales Invoice")
typeAutoCompleteSalesInvoiceThe document type this template is designed for
templateTextVue HTML template code
heightFloat29.7Page height in centimeters
widthFloat21Page width in centimeters
isCustomCheck (read-only)truetrue for user-created templates, false for built-in

Template Types

Each template is associated with a specific document type. The available types are:

TypeSchema NameDescription
Sales InvoiceSalesInvoiceCustomer-facing invoice
Sales QuoteSalesQuoteCustomer quotation / estimate
Purchase InvoicePurchaseInvoiceVendor bill
Journal EntryJournalEntryJournal voucher
PaymentPaymentPayment receipt
ShipmentShipmentDelivery note
Purchase ReceiptPurchaseReceiptGoods received note
Stock MovementStockMovementInternal stock transfer
Inventory AdjustmentInventoryAdjustmentInventory correction
POS SessionPOSSessionPOS shift summary report

Built-in vs Custom Templates

PropertyBuilt-in TemplatesCustom Templates
isCustomfalsetrue
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
Important: Built-in templates are read-only and are automatically updated when you upgrade NkapBooks. If you want to customize a built-in template, use the Duplicate action to create an editable custom copy.

Creating a Custom Template

There are three ways to create a custom template:

1. Duplicate an Existing Template

  1. Open an existing template in the Template Builder
  2. Click the ⋮ Actions menu → Duplicate
  3. The duplicate is created with isCustom: true and opens for editing
  4. Rename the template and customize the layout

2. Create from Scratch

  1. Navigate to Setup → Print Templates
  2. Click + New Print Template
  3. Enter a Template Name
  4. Select the Template Type (document type)
  5. The editor opens with a base starter template
  6. Write your custom HTML/CSS/Vue code

3. Import a Template File

  1. Open the Template Builder for any custom template
  2. Click ⋮ ActionsSelect Template File
  3. Choose an .html file from your computer
  4. The file contents are loaded into the editor

List View

The Print Template list view shows:

ColumnDescription
nameTemplate name
typeDocument type (displayed as human-readable label)
isCustomWhether 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

ButtonShortcutDescription
SaveCtrl+SSave the template to the database
PrintSend the current preview to the printer
PDFExport the current preview as a PDF file
⋮ ActionsDropdown with additional actions

Actions Menu

ActionAvailabilityDescription
Print SettingsAlwaysOpens the Print Settings configuration
Set Template TypeCustom templates onlyChange the document type for this template
Set Print SizeCustom templates onlySet page dimensions (A4, Letter, Legal, Custom)
Select Template FileCustom templates onlyImport an HTML template file from disk
Save Template FileAlwaysExport the template code as an HTML file
DuplicateAlwaysCreate a custom copy of this template
DeleteCustom templates onlyDelete 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:

ControlDescription
Display DocSelect which document to use for preview data (e.g., a specific invoice)
Scale SliderAdjust the zoom level of the preview (default: 0.6x)
Paper SizeShows 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:

FeatureDescription
Syntax HighlightingVue/HTML syntax highlighting with custom color theme
AutocompleteContext-aware autocompletion for template variables
Line NumbersGutter with line numbers
Search & ReplaceBuilt-in find/replace (Ctrl+F, Ctrl+H)
Read-Only ModeAutomatically 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:

ModeDescription
Preview Mode (default)Side-by-side preview and editor, sidebar visible
Edit ModeFull-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:

CategoryPrefixDescription
Document Datadoc.*Fields from the document being printed
Print Settingsprint.*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:

SizeWidth (cm)Height (cm)
A42129.7
Letter21.5927.94
Legal21.5935.56
CustomUser-definedUser-defined

Template Syntax

Templates use Vue 3 template syntax with three injected props:

PropTypeDescription
docObjectDocument data (fields, items, totals, party info)
printObjectPrint settings (logo, company name, colors, address)
tFunctionTranslation 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>
Tip: Templates support all Tailwind CSS utility classes from the application's stylesheet. Use them for layout, spacing, typography, and colors. The full application CSS is injected into the print document automatically.

Template Compilation Errors

If your template has syntax errors, the preview panel shows a red error screen with:

FieldDescription
Error NameType of error (e.g., "Template Compilation Error")
Error MessageDescription of what went wrong
Code FrameThe 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

FieldTypeDescription
logoAttachImageCompany logo image for printed documents
companyNameDataCompany name displayed on documents

Contacts Section

FieldTypeDescription
emailDataCompany email address for printed documents
phoneDataCompany phone number for printed documents
addressLink → AddressCompany address (can create a new address inline)

Customizations Section

FieldTypeDefaultDescription
colorColor#112B42 (Black)Primary accent color used in templates
fontSelectArialFont family: Arial, Times New Roman, or Courier
displayLogoChecktrueShow company logo on invoices
amountInWordsChecktrueDisplay grand total in words (e.g., "One Thousand Two Hundred")
displayTimeChecktrueShow time along with date on invoices
displayDescriptionCheckfalseShow item descriptions on invoices
displaytermsandconditionsCheckfalseShow terms and conditions section
posPrintWidthFloat8Width (in cm) for POS receipt printing
termsAndConditionsTextTerms and conditions text displayed on documents

Available Colors

The color picker provides these pre-defined options:

ColorHex 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 VariableSource FieldExample Output
print.companyNamecompanyName"My Business LLC"
print.colorcolor"#33a1ff"
print.logologoImage data URL
print.emailemail"info@mybusiness.com"
print.phonephone"+1-555-0123"
print.displayLogodisplayLogotrue
print.amountInWordsamountInWordstrue
print.fontfont"Arial"
print.displayTimedisplayTimetrue
print.addressResolved addressFull address text

Additionally, key fields from AccountingSettings are merged into the print object:

Template VariableSourceDescription
print.gstinAccountingSettings.gstinGST Identification Number (India)
print.countryAccountingSettings.countryCountry name
print.currencyAccountingSettings.currencyDefault 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

DocumentSchemaTypical Use
Sales InvoiceSalesInvoiceCustomer invoices for goods/services sold
Sales QuoteSalesQuoteQuotations/estimates sent to prospects
Purchase InvoicePurchaseInvoiceVendor bills received for purchases
PaymentPaymentPayment receipts for money received or paid
Journal EntryJournalEntryJournal vouchers for manual accounting entries

Inventory Documents

DocumentSchemaTypical Use
ShipmentShipmentDelivery notes for goods dispatched to customers
Purchase ReceiptPurchaseReceiptGoods received notes from suppliers
Stock MovementStockMovementInternal stock transfer documents
Inventory AdjustmentInventoryAdjustmentStock correction documents

POS Documents

DocumentSchemaTypical Use
POS SessionPOSSessionShift 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 FieldDocument TypeDescription
salesInvoicePrintTemplateSales InvoiceDefault template for sales invoices
salesQuotePrintTemplateSales QuoteDefault template for sales quotes
purchaseInvoicePrintTemplatePurchase InvoiceDefault template for purchase invoices
journalEntryPrintTemplateJournal EntryDefault template for journal entries
paymentPrintTemplatePaymentDefault template for payment receipts
shipmentPrintTemplateShipmentDefault template for shipments
purchaseReceiptPrintTemplatePurchase ReceiptDefault template for purchase receipts
stockMovementPrintTemplateStock MovementDefault template for stock movements
inventoryAdjustmentPrintTemplateInventory AdjustmentDefault template for inventory adjustments
posPrintTemplatePOS (Sales Invoice)Default template for POS receipts
The POS print template uses the 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

VariableTypeDescription
doc.namestringDocument ID (e.g., "SINV-00042")
doc.datestringFormatted document date
doc.partystringCustomer or supplier name
doc.entryTypestringSchema name (e.g., "SalesInvoice")
doc.entryLabelstringHuman-readable schema label (e.g., "Sales Invoice")
doc.submittedbooleanWhether the document is submitted

Financial Fields (Invoices, Payments)

VariableTypeDescription
doc.grandTotalstringFormatted grand total amount
doc.baseGrandTotalstringFormatted grand total in base currency
doc.netTotalstringFormatted net total (before tax)
doc.outstandingAmountstringFormatted outstanding/unpaid amount
doc.totalTaxstringFormatted total tax amount
doc.totalDiscountstringFormatted total discount (for invoices)
doc.grandTotalInWordsstringGrand total spelled out in words
doc.showHSNbooleanWhether items have HSN codes (for invoices)

Items Array (Invoices, Quotes)

VariableTypeDescription
doc.itemsArrayLine items on the document
doc.items[n].itemstringItem name
doc.items[n].descriptionstringItem description
doc.items[n].quantitynumberQuantity
doc.items[n].unitstringUnit of measure
doc.items[n].ratestringFormatted unit price
doc.items[n].amountstringFormatted line total
doc.items[n].hsnCodestringHSN/SAC code (India)

Tax Summary Array

VariableTypeDescription
doc.taxesArrayTax breakdown
doc.taxes[n].accountstringTax account name
doc.taxes[n].amountstringFormatted tax amount

Party Information

VariableTypeDescription
doc.party.namestringParty name
doc.party.phonestringParty phone number
doc.party.emailstringParty email address
doc.party.addressstringParty address
doc.party.gstinstringParty GSTIN (India)

Payment Details

VariableTypeDescription
doc.paymentDetailsArrayAssociated payments
doc.paymentDetails[n].amountstringPayment amount
doc.paymentDetails[n].amountPaidstringAmount paid
doc.paymentDetails[n].paymentMethodstringPayment method used
doc.paymentDetails[n].outstandingAmountstringRemaining outstanding

POS Session Variables

POS Session templates receive additional specialized variables:

VariableTypeDescription
doc.openedBystringUser who opened the session
doc.closedBystringUser who closed the session
doc.openingDatestringSession opening date/time
doc.closingDatestringSession closing date/time
doc.totalInvoiceAmountstringTotal revenue during session
doc.totalItemsQuantitynumberTotal items sold
doc.sessionAmountsArrayPer-payment-method breakdown
doc.sessionAmounts[n].paymentMethodstringPayment method name
doc.sessionAmounts[n].openingAmountstringOpening cash amount
doc.sessionAmounts[n].closingAmountstringClosing cash amount
doc.sessionAmounts[n].expectedAmountstringExpected amount
doc.sessionAmounts[n].differenceAmountstringCash difference
doc.itemsSoldArrayItems sold during session
doc.itemsSold[n].itemstringItem name
doc.itemsSold[n].quantitynumberTotal quantity sold
doc.itemsSold[n].amountstringTotal revenue for item
VariableTypeDescription
print.companyNamestringCompany name from PrintSettings
print.logostringLogo image data
print.colorstringAccent color hex value
print.fontstringFont family name
print.emailstringCompany email
print.phonestringCompany phone
print.addressstringCompany address
print.displayLogobooleanWhether to show the logo
print.amountInWordsbooleanWhether to show amount in words
print.displayTimebooleanWhether to show time
print.gstinstringCompany GSTIN (from AccountingSettings)
print.countrystringCountry (from AccountingSettings)
print.currencystringCurrency (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):

  1. The template is rendered with document data in the preview panel
  2. The rendered innerHTML is extracted from the preview container
  3. A complete HTML document is constructed with all CSS styles embedded
  4. A save dialog prompts for the file path (default name: document name + .pdf)
  5. The HTML is sent to the Tauri backend via the makePDF command
  6. The backend generates the PDF using the specified width and height
  7. A success toast is shown with an option to open the containing folder

Direct Printing

When you click Print:

  1. The same rendering and HTML construction process occurs
  2. Instead of saving a file, the HTML is sent to the Tauri printDocument command
  3. The system print dialog appears for printer selection and settings
  4. A success or failure toast is shown

HTML Document Construction

The print document includes:

ComponentDescription
Meta charsetUTF-8 encoding declaration
Application CSSAll CSS rules from the application's stylesheets (Tailwind, custom styles)
Print CSSSpecial @media print rules that reset margins and padding
Template HTMLThe rendered template content

The print CSS ensures clean output:

RulePurpose
margin: 0 on html, bodyRemove browser default margins
@page { margin: 0 }Remove page margins
box-sizing: border-boxConsistent sizing model

Timeout Protection

Both PDF generation and printing have timeout protection:

OperationTimeoutError Message
PDF Generation60 seconds"PDF generation timed out. Please try again."
Printing30 seconds"Print operation timed out. Please try again."

Loading Feedback

While generating a PDF or printing, a loading toast is displayed:

OperationMessage
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:

  1. PDF Button — Exports the current preview as a PDF file
  2. 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
PatternBehavior
Standard.template.htmlCreates templates for SalesInvoice, SalesQuote, and PurchaseInvoice
Standard.Payment.template.htmlCreates a template specifically for Payment documents
Standard.JournalEntry.template.htmlCreates 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:

  1. Fetches all template files from the application resources
  2. Compares the file modification dates with the database records
  3. Updates only templates where the file is newer than the database record
  4. 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

StepActionDescription
1Configure Print SettingsSet logo, company name, color, and font in Settings → Print
2Review built-in templatesOpen a built-in template to see how it's structured
3Duplicate and customizeDuplicate a built-in template to create your customized version
4Set as defaultAssign your custom template as the default in Settings → Defaults
5Test with real dataUse the Display Doc selector to preview with different documents
6Export a test PDFGenerate a PDF to verify the final output

Template Design Tips

TipDescription
Use Tailwind classesAll Tailwind CSS utilities are available — use p-4, flex, text-lg, etc.
Use print.color for accentsBind your accent elements to :style="{ color: print.color }" for consistency
Use the t functionWrap all text labels in t`Label` for multi-language support
Handle missing dataUse v-if or `
Test at actual sizeSet scale to 1.0 in the preview to see the true print size
Keep templates simpleComplex JavaScript in templates can cause compilation errors — keep logic minimal
Use @page CSSFor fine-grained print control, add @page CSS rules in a <style> block

Exporting and Sharing Templates

ActionHow
Export templateActions → Save Template File (saves as .html)
Import templateActions → Select Template File (loads .html into editor)
Share with teamExport the template file and share it; the recipient imports it

Troubleshooting

IssueSolution
Preview shows red errorCheck 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 blankEnsure the template has a root <main> or <div> element with content
Styles not applyingTailwind classes work; custom CSS must be in an inline <style> block
POS receipt too wide/narrowAdjust posPrintWidth in Settings → Print (default: 8 cm)
Template not updatingBuilt-in templates are read-only — duplicate to create an editable version
Print dialog doesn't appearCheck that the Tauri shell plugin is properly configured