jsLabel2PDF.js
This module extends jQuery to generate PDF documents composed of printable labels. It builds raw PDF objects in JavaScript, encodes them in Base64, and triggers a download via a data URI. The code is based on HTML5Marketplace’s GPL-licensed PDF routines .
Overview
- Defines four public methods on the jQuery object (
$) for template creation, text placement, and PDF rendering. - Uses raw PDF 1.4 syntax to assemble objects, pages, fonts, and XObjects.
- Outputs a Base64-encoded PDF via
data:application/pdf;base64,….
Public API
$.CreateTemplate(units, paperWidth, paperHeight, marginLeft, marginTop, labelWidth, labelHeight, numRows, numColumns, horizontalSpace, verticalSpace)
Configures page and label dimensions before adding any content.
$.CreateTemplate(
"inches", // units: "inches" or "mm"
8.268, // paperWidth
11.693, // paperHeight
0.3815, // marginLeft
0.5965, // marginTop
2.5, // labelWidth
1.5, // labelHeight
7, // numRows
3, // numColumns
0.0, // horizontalSpace
0.0 // verticalSpace
);
- units: measurement unit (
"inches"or"mm"). - All other numeric parameters define the layout grid.
- Converts all values to PDF points (72 pt/in or 72/25.4 pt/mm).
$.CreateLabel()
(Currently a placeholder)
- Defined but not implemented.
- Intended to initialize or reset label-specific settings.
$.AddText(x, y, str, fontSize)
Adds a text string at a given position on every label.
$.AddText(
0.1, // x-position
0.2, // y-position
"SKU-123",// text to render
10 // font size in points
);
- Converts
x/yto PDF points based on selected units. - Stores text, coordinates, and font size in internal arrays.
- Increments an internal text counter.
$.DrawPDF() 🖨️
Renders the PDF and triggers a download.
$.DrawPDF();
- Calls a sequence of internal setup functions.
- Logs the assembled PDF string to the console.
- Sets
document.location.hrefto a Base64 PDF data URI. - Requires global availability of
Base64.encodeandsprintf.
Internal Workflow
The PDF generation follows a strict pipeline of object creation:
flowchart TD
A["DrawPDF()"] --> B["setupVersion()"]
B --> C["setupFonts()"]
C --> D["setupXObject()"]
D --> E["setupResources()"]
E --> F["setupPage()"]
F --> G["setupPages()"]
G --> H["setupOutlines()"]
H --> I["setupCatalog()"]
I --> J["setupTrailer()"]
J --> K["Output & Download"]
- setupVersion: Emits the PDF header
%PDF-1.4. - setupFonts: Registers Helvetica as the default font.
- setupXObject: Creates a Form XObject per label slot, drawing borders and injected text.
- setupResources: Builds the resource dictionary (fonts + XObjects).
- setupPage: Defines each page object, its MediaBox, and content streams referencing XObjects.
- setupPages: Compiles all page objects into a Pages tree.
- setupOutlines & setupCatalog: Create outline (empty) and catalog objects.
- setupTrailer: Writes the cross-reference table, trailer, and EOF marker.
Code Snippets
Version Header
function setupVersion() {
pdfoutput += '%PDF-1.4\n';
}
Font Registration
function setupFonts() {
objCounter++;
fontNumbersArry[++fontCounter] = objCounter;
pdfoutput += `${objCounter} 0 obj
<< /Type /Font
/BaseFont /Helvetica
/Subtype /Type1
/Encoding /WinAnsiEncoding
>>
endobj
`;
}
XObject Creation
function setupXObject() {
for (let y = 0; y < _numRows; y++) {
for (let x = 0; x < _numColumns; x++) {
objCounter++;
xobjectNumbersArry[y][x] = objCounter;
// Begin Form XObject
pdfoutput += `${objCounter} 0 obj
<< /Type /XObject
/Subtype /Form
/FormType 1
/BBox [0 0 ${_labelWidthPt} ${_labelHeightPt}]
/Matrix [1 0 0 1 ${_CalcX(x)} ${_CalcY(y)}]
/Resources << /ProcSet [/PDF /Text] /Font << /XF1 ${fontNumbersArry[1]} 0 R >> >>
/Length ${streamLength}
>>
stream
${streamoutput}
endstream
endobj
`;
}
}
}
Dependencies
- jQuery: for plugin definition (
(function($){…})(jQuery)). - Base64: must expose
Base64.encode(string)in the global scope. - sprintf: used for zero-padded offsets in the cross-reference table.
Usage Example
// 1. Define label layout in inches
$.CreateTemplate("inches", 8.5, 11, 0.5, 0.5, 2.5, 1.5, 7, 3, 0, 0);
// 2. Add text fields to each label
$.AddText(0.1, 0.1, "Product Name", 12);
$.AddText(0.1, 0.3, "SKU-00123", 10);
// 3. Generate and download
$.DrawPDF();
⚠️ Known Issue
- The code uses the assignment operator (
=) instead of comparison (==or===) inif (units="inches"). As a result, units always resets to"inches". This bug may affect metric layouts.