@devoy/pharmnex-pdf-generator
v0.4.1
Published
JSON-driven PDF generators for Pharmnex documents.
Maintainers
Readme
@devoy/pharmnex-pdf-generator
Business document PDFs
Version 0.4.1 adds configurable receipt spacing and currency labels to the opt-in 80mm thermal output introduced in 0.4.0. The unified document API supports Sales Invoice, Purchase Order, Purchase
Receive, Purchase Bill, Purchase Credit Note, Payment Made, Sales Return, Sales Credit Note,
and Payment Receive. Existing Half A4, Full A4, and Sales Invoice behavior remains unchanged.
Purchase and Sales Credit Note types
Both credit-note PDFs dynamically select their rows and columns from credit_note_type.
Damaged Goods and Returned Goods are one combined type.
import {
CREDIT_NOTE_TYPES,
createDocumentPdfDefinition,
} from '@devoy/pharmnex-pdf-generator/documents';
createDocumentPdfDefinition('sales_credit_note', {
...salesCreditNote,
credit_note_type: CREDIT_NOTE_TYPES.EXCESS_PAYMENT,
sales_credit_notes_excess_payments: [{
payment_receive: { payment_receive_number: 'RCPT-1001', cash_handed: 600 },
excess_amount: 100,
}],
});| Constant | Value | Purchase data | Sales data |
| --- | ---: | --- | --- |
| DAMAGED_OR_RETURNED_GOODS | 1 | credit_note_products | sales_credit_notes_damage_returns |
| EXCESS_PAYMENT | 2 | credit_note_excess_bills | sales_credit_notes_excess_payments |
| ADVANCE_PAYMENT | 3 | payment_amount | total_credit_amount |
Existing numeric and snake-case backend payloads remain supported. Invalid type values are
rejected instead of being silently rendered as Advance Payment. Complete Purchase and Sales
examples are in docs/business-documents.md.
import { createPurchaseOrderPdfDefinition } from '@devoy/pharmnex-pdf-generator/documents';
const definition = createPurchaseOrderPdfDefinition(purchaseOrder, {
documentSize: 'half', // or 'full'
watermark: true,
});Browser:
import { downloadDocumentPdf } from '@devoy/pharmnex-pdf-generator/documents/browser';
downloadDocumentPdf('purchase_order', purchaseOrder, {
pdfMake,
documentSize: 'half',
watermark: true,
});Sales Invoice is available through the same API as sales_invoice; existing
downloadInvoicePdf, createInvoicePdfDefinition, and Node invoice functions remain
backward compatible.
Node.js:
import { createDocumentPdfBuffer } from '@devoy/pharmnex-pdf-generator/documents/node';
const buffer = await createDocumentPdfBuffer('purchase_order', purchaseOrder, {
documentSize: 'full',
watermark: true,
});80mm thermal PDFs
Use the same module payload and select thermal output explicitly:
downloadDocumentPdf('sales_invoice', invoice, {
pdfMake,
documentSize: 'thermal80',
thermal: {
density: 'detailed', // or 'compact'
printableWidthMm: 72,
fontScale: 1,
showTaxSummary: true,
showAmountInWords: true,
showBarcode: false,
currencySymbol: '₹',
escPosCurrencySymbol: 'Rs',
itemSpacingLines: 1,
feedAfterMm: 8,
},
});Thermal output is an exact 80mm-wide, automatically sized PDF supported by the existing browser
and Node APIs. Batch remains visible in both densities for batch-capable documents. Missing batch
data renders as Batch: N/A and is reported by createThermalDocument() without breaking older
payloads. Watermarks and A4 row pagination do not apply in thermal mode.
Thermal headers print supplied compliance values as GSTIN: … | DL No.: …. PDFs prefix money
with ₹; direct ESC/POS defaults to the ASCII-safe Rs prefix because the verified PSF80B text
code page does not reliably encode Unicode ₹. Set itemSpacingLines from 0 to 3; omitting
it preserves the existing one-line gap.
The Sales Invoice receipt uses a receipt-first Customer/Amount composition with three compact lines
per product, taxable value, CGST/SGST totals, a rate-wise tax summary, and paise-aware amount words.
The package does not connect to USB/Bluetooth printers or send ESC/POS/TSPL commands. Configure
the printer driver for continuous 80mm paper, actual size/100%, and no added margins.
If commands such as SIZE, GAP, or BITMAP print as text, the operating-system queue is using
an incompatible driver; changing the PDF layout cannot correct that driver issue. Generic A4
printers remain supported through documentSize: 'full' and documentSize: 'half'.
The package does not persist a default format. Applications can store a user or organisation preference and pass it on every generation call:
const documentSize = organisation.printFormat || 'full';
downloadDocumentPdf('sales_invoice', invoice, { pdfMake, documentSize });Optional direct ESC/POS printing
Direct thermal output is additive and does not replace any PDF API:
import { createThermalPrintJob } from '@devoy/pharmnex-pdf-generator/thermal';
const job = createThermalPrintJob('sales_invoice', invoice, {
profile: 'psf80b',
feedLines: 3,
showBarcode: true,
cut: false,
});
await usbOrNativeTransport.write(job.data);The verified psf80b profile uses ESC/POS, 203 DPI, 576 dots and a 72mm printable area on an
80mm roll. It intentionally disables cutting. generic80 enables cutting for compatible devices.
Use writeThermalPrintJob(job, writer) for a consumer-provided transport. Browser applications can
import binary download, capability detection and explicit WebUSB helpers from /thermal/browser.
WebUSB requires HTTPS or localhost, an explicit user action and a compatible Chromium browser.
Safari and classic Bluetooth are not supported by that adapter.
Use connectThermalUsbDevice() for the initial chooser and getAuthorizedThermalUsbDevices() to
recover previously granted devices. Pass the selected device to printThermalJobWebUsb() so later
explicit print clicks do not reopen the chooser.
The WebUSB adapter initializes the printer separately, then sends paced 256-byte chunks and waits
before releasing the interface. chunkSize, initializeDelayMs, chunkDelayMs, and
finalizeDelayMs can be tuned for another printer profile.
Supported options include documentSize, the backward-compatible invoiceSize alias,
pageSize, pageMargins, rowsPerPage, productsPerPage, minRows, cellPaddingY,
watermark, watermarkImage, watermarkOpacity, watermarkAngle, font sizes, and scale.
The new formats use the Sales Invoice typography, borders, spacing, tables, totals,
amount-in-words, signature, watermark, and continuation-page treatment as their baseline.
When documentSize or invoiceSize is selected, that format is authoritative. Every half-A4
document uses the same exact page dimensions and default [6, 6, 6, 6] outer border margins.
Every PDF type supports opt-in continuation and final-page limits. Existing defaults remain unchanged: 8 rows per half-A4 page and 18 per full-A4 page, except Sales Return's existing 10-row full-A4 default:
downloadDocumentPdf('sales_invoice', invoice, {
pdfMake,
documentSize: 'half',
productsPerContinuationPageHalfPage: 14,
productsPerFinalPageHalfPage: 8,
});Size-specific options are productsPerPageHalfPage, productsPerPageFullPage,
productsPerContinuationPageHalfPage, productsPerFinalPageHalfPage,
productsPerContinuationPageFullPage, and productsPerFinalPageFullPage. They activate
compact pagination for the selected PDF type only when explicitly supplied. Continuation pages
fill toward their configured capacity while leaving no more than the configured maximum on the
final page. Existing
rowsPerPage and productsPerPage behavior remains unchanged.
Sales Return full-A4 capacities are limited to 10 because its return-detail rows are taller.
Sales Invoice half-A4 continuation pages support up to 17 rows with the standard frame and
typography. Values that cannot physically fit are rejected instead of overflowing the page.
Shared JSON-to-PDF helpers for Pharmnex documents.
Version 0.2.1 supports browser-based React applications and Node.js 18+
services through isolated package entry points.
Install
npm install @devoy/pharmnex-pdf-generator pdfmakeFor local portal development:
"@devoy/pharmnex-pdf-generator": "file:../pharmnex-pdf-generator"Runtime Entry Points
| Import | Runtime | Purpose |
| --- | --- | --- |
| @devoy/pharmnex-pdf-generator | Browser | Backward-compatible root export. |
| @devoy/pharmnex-pdf-generator/browser | Browser | Explicit browser PDF actions. |
| @devoy/pharmnex-pdf-generator/node | Node.js 20+ | Buffer and stream generation. |
| @devoy/pharmnex-pdf-generator/core | Universal | Definition, normalization, constants, and formatting. |
Node modules are isolated from the browser entry and are not included in React bundles.
Node.js Usage
Requires Node.js 20 or newer. Import the Node entry only from server-side code:
import { createInvoicePdfBuffer } from '@devoy/pharmnex-pdf-generator/node';
const pdf = await createInvoicePdfBuffer(invoiceJson, {
invoiceSize: 'half',
watermark: true,
});CommonJS is also supported:
const {
createInvoicePdfBuffer,
} = require('@devoy/pharmnex-pdf-generator/node');| Function | Result |
| --- | --- |
| createInvoicePdfBuffer(invoiceJson, options) | Promise resolving to a Node Buffer. |
| createInvoicePdfStream(invoiceJson, options) | Ended readable PDFKit stream. |
| createNodePdfBuffer(docDefinition, options) | Buffer from any pdfmake definition. |
| createNodePdfStream(docDefinition, options) | Stream from any pdfmake definition. |
| createDefaultNodeFonts() | Fresh Roboto font descriptors backed by buffers. |
The Node entry uses deterministic bundled Roboto font data by default. Pass
fonts, printer, or PdfPrinter to override rendering infrastructure, and
pdfKitOptions to configure pdfmake's PDFKit document creation.
Node HTTP Response
import { createInvoicePdfBuffer } from '@devoy/pharmnex-pdf-generator/node';
const pdf = await createInvoicePdfBuffer(invoiceJson, {
invoiceSize: 'full',
watermark: false,
});
response.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': pdf.length,
'Content-Disposition': 'inline; filename="invoice.pdf"',
});
response.end(pdf);Use createInvoicePdfStream() to pipe large responses without accumulating the
complete document in application memory:
const pdf = createInvoicePdfStream(invoiceJson, { invoiceSize: 'half' });
response.setHeader('Content-Type', 'application/pdf');
pdf.pipe(response);Next.js Route Handler
import { createInvoicePdfBuffer } from '@devoy/pharmnex-pdf-generator/node';
export const runtime = 'nodejs';
export async function POST(request) {
const invoice = await request.json();
const pdf = await createInvoicePdfBuffer(invoice, { invoiceSize: 'half' });
return new Response(pdf, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="invoice.pdf"',
},
});
}The /node entry is not compatible with Next.js Edge runtime. Use
runtime = 'nodejs'.
Node Deployment
The Node API must run on a Node-capable server, container, serverless function, or cPanel Node application. A static HTML deployment cannot execute the Node entry. When a browser application calls a separately hosted PDF API, configure CORS, request-size limits, authentication, and invoice authorization in the hosting application.
See docs/node-usage.md for complete Node integration,
configuration, deployment, and troubleshooting guidance.
Invoice Usage
import pdfMake from 'pdfmake/build/pdfmake';
import 'pdfmake/build/vfs_fonts';
import {
createInvoicePdfDefinition,
downloadInvoicePdf,
} from '@devoy/pharmnex-pdf-generator';
const definition = createInvoicePdfDefinition(invoiceJson);
downloadInvoicePdf(invoiceJson, {
pdfMake,
fileName: 'INV-134.pdf',
});The package accepts a normalized JSON format and also maps the current Retail Portal invoice shape, including organisation, customer, and invoice_products.
Tax And Total Handling
Nested totals are canonical. A supplied totals.grandTotal is always used, while missing values can be calculated from line items:
const invoice = {
// seller, buyer, and items...
totals: {
subTotal: 102.90,
taxTotal: 5.14, // optional; derived from item taxes when omitted
discount: 0,
adjustment: 0,
roundOff: 0,
grandTotal: 108.04,
},
};
createInvoicePdfDefinition(invoice, {
totalsMode: 'prefer-provided', // or 'calculate'
taxMode: 'exclusive', // or 'inclusive'
});taxMode: 'exclusive' adds derived tax when the grand total is missing. taxMode: 'inclusive' treats item amounts as tax-inclusive and reports the extracted tax without adding it again. Legacy top-level total fields remain supported.
Half-A4 Portrait Output
Invoices default to a custom half-A4 portrait sheet:
{ width: 420.94, height: 595.28 }This keeps every generated page within a portrait half-A4 page for printers fed with half sheets.
The invoice generator also accepts sizing options:
createInvoicePdfDefinition(invoiceJson, {
invoiceSize: 'half', // 'half' for half-A4, 'full' for full A4
fontSize: 7,
smallFontSize: 6.4,
scale: 1,
rowsPerPage: 8, // defaults to 8 for half-A4 and 18 for full A4
watermark: true,
watermarkOpacity: 0.07,
watermarkAngle: -32,
watermarkWidthRatio: 0.68,
watermarkCenterYRatio: 0.36, // default for half-A4; full A4 defaults to 0.5
});Use invoiceSize: 'full' for full A4 invoice output:
downloadInvoicePdf(invoiceJson, {
pdfMake,
invoiceSize: 'full',
});Half-A4 remains the default. pageSize is still supported for advanced/custom output and takes precedence over invoiceSize.
When an invoice has more products than rowsPerPage, the package creates continuation pages with the same page size and repeats the invoice header/details. Continuation pages show page-level totals and a continuation marker; final invoice totals and taxes are printed on the last page.
Watermarks are optional. Pass watermark: true to add the bundled faded diagonal Pharmnex logo watermark:
createInvoicePdfDefinition(invoiceJson, {
watermark: true,
});