pdfmake-tools
v1.0.0
Published
Useful tools for pdfmake
Readme
pdfmake-tools
A lightweight and intuitive Node.js library that simplifies the creation of PDF documents using pdfmake by providing a fluent, chainable API for constructing text and table structures. The library abstracts away the complexity of pdfmake's raw document definitions, making it easier to create well-formatted PDFs with minimal code.
Features
- Fluent API: Chain methods to style text and tables effortlessly.
- Text Formatting: Easily apply styles like bold, italics, alignment, margins, and more.
- Table Support: Build complex tables with customizable layouts, widths, and cell spans.
- Text Processing: Transform text with operations like case conversion, whitespace removal, and string replacement.
- Utility Functions: Predefined helpers for common tasks like creating paragraphs, bold text, and page breaks.
Installation
Install the library via npm:
npm install pdfmake-toolsEnsure you have pdfmake installed as a peer dependency:
npm install pdfmakeUsage
The library provides two main classes: TextBlock and TableBlock, along with utility functions for common use cases.
Using pdfmake-tools
Combine with pdfmake to generate a PDF.
const { parseBlocks, text, bold, table } = require('pdfmake-tools');
const PdfPrinter = require('pdfmake');
const fonts = {
Roboto: {
normal: 'path/to/Roboto-Regular.ttf',
bold: 'path/to/Roboto-Bold.ttf',
},
};
const printer = new PdfPrinter(fonts);
const docDefinition = {
content: [
bold`Welcome to my PDF!`.center(),
table([
[bold`Col 1`, bold`Col 2`],
[text`Data 1`, text`Data 2`],
]).widths(['50%', '50%'])
],
};
const pdfStructure = parseBlocks(docDefinition);
const pdfDoc = printer.createPdfKitDocument(pdfStructure);
pdfDoc.pipe(fs.createWriteStream('output.pdf'));
pdfDoc.end();Creating Text Blocks
Use TextBlock to create and style text content.
const { parseBlocks, text, bold, italics, underline, paragraph } = require('pdfmake-tools');
// Create a simple text block
const content = [
bold`Hello, World!`.center(),
text`A long paragraph of text goes here,
and it can span multiple lines.`,
paragraph`This is a sample paragraph with a leading indent.`,
text([
bold`It is very `,
italics`easy to create `,
underline`PDFs with pdfmake-tools.`,
]),
];
// Output for pdfmake
console.log(parseBlocks(content));Output (simplified pdfmake structure):
[
{ text: 'Hello, World!', bold: true, alignment: 'center' },
{ text: 'A long paragraph of text goes here, and it can span multiple lines.' },
{ text: 'This is a sample paragraph with a leading indent.', leadingIndent: 20 },
{ text: [
{ text: 'It is very ', bold: true },
{ text: 'easy to create ', italics: true },
{ text: 'PDFs with pdfmake-tools.', underline: true },
] },
]Creating Tables
Use TableBlock to create and customize tables.
const { parseBlocks, bold, table, text } = require('pdfmake-tools');
const myTable = table([
[bold`Header 1`, bold`Header 2`],
[text`Row 1, Col 1`, text`Row 1, Col 2`],
])
.widths(['*', '*'])
.layout({ fillColor: '#f0f0f0' });
console.log(parseBlocks(myTable));Output (simplified pdfmake structure):
{
table: {
body: [
[{ text: 'Header 1', bold: true }, { text: 'Header 2', bold: true }],
[{ text: 'Row 1, Col 1' }, { text: 'Row 1, Col 2' }]
],
widths: ['*', '*']
},
layout: { fillColor: '#f0f0f0' }
}Advanced Text Formatting
Apply transformations like case conversion or string replacement.
const { parseBlocks, text } = require('pdfmake-tools');
const formattedText = text`Hello, WORLD!`
.toUpperCase()
.replace('WORLD', 'Universe')
.bold();
console.log(parseBlocks(formattedText));Output:
{ text: 'HELLO, UNIVERSE!', bold: true }Custom Components
Create custom components
const { parseBlocks, TextBlock, bold } = require('pdfmake-tools');
const customHeader1 = new TextBlock()
.bold()
.center()
.margin([ 0, 20, 0, 10 ])
.value();
const customHeader2 = new TextBlock()
.addWrapper(text => ({
style: 'tableExample',
table: {
widths: ['*'],
body: [[text]],
},
layout: {
fillColor: '#CCCCCC',
},
}))
.value();
const content = [
customHeader1`Wrapped content 1`,
customHeader2`Wrapped content 2`,
bold`Other content`,
];
console.log(parseBlocks(content));Output:
[
{
text: 'Wrapped content 1',
bold: true,
alignment: 'center',
margin: [ 0, 20, 0, 10 ]
},
{
style: 'tableExample',
table: {
widths: ['*'],
body: [['Wrapped content 2']],
},
layout: {
fillColor: '#CCCCCC',
},
},
{
text: 'Other content',
bold: true
}
]Page Breaks and Line Breaks
Add structural elements like page breaks or line breaks.
const { parseBlocks, pageBreak, lineBreak, text } = require('pdfmake-tools');
const content = [
text`First page content`,
pageBreak(),
text`Second page content`,
lineBreak(),
text`After line break`,
];
console.log(parseBlocks(content));Output:
[
{ text: 'First page content' },
{ text: '', pageBreak: 'before' },
{ text: 'Second page content' },
{ text: '\n' },
{ text: 'After line break' }
]API Reference
TextBlock
- Constructor:
new TextBlock({ text, options, wrapper, formats }) - Methods:
bold(),italics(),underline(): Apply text styles.center(),right(),left(): Set text alignment.fontSize(value),margin(value),margin[Direction](value): Set styling options.toLowerCase(),toUpperCase(),replace(search, replace): Transform text.removeWhiteSpaces(): Normalize whitespace in custom components.rowSpan(value),colSpan(value): Set table cell spans.addWrapper(wrapper): Add a wrapper function to modify output.
TableBlock
- Constructor:
new TableBlock({ body, options, wrapper }) - Methods:
widths(value): Set column widths.fillColor(value): Set table fill color.layout(value): Set table layout options.pushRow(row): Add a row to the table.addWrapper(wrapper): Add a wrapper function.
Utility Functions
text,bold,italics,paragraph: PreconfiguredTextBlockfactories.table: PreconfiguredTableBlockfactory.lineBreak(): Insert a line break.pageBreak(): Insert a page break.inline(...args): Create inline text with interpolated values.parseBlocks(obj): Recursively convert blocks topdfmake-compatible structures.
License
MIT
