In one of the projects I needed to use pdfkit. Despite the existing documentation for this npm package, many aspects of what I needed to do were not covered in the documentation.
I spent a lot of time looking for applications/examples of usage, something was found something was figured out on my own through trials and errors, something had to be given up.
In this documentation, I will use small examples to share with you my experience and the solutions that I found. If this information was useful to you, I would be grateful if you put a star on this repository on GitHub.
Notice, that this is not a tutorial on how to use this package, but only a small hint in solving some problems that you may have to face.
The library provides a large number of predefined sizes that you can use. Here you can find them
let doc = new PDFDocument({
size: 'A4',
margins: {
left: 50,
right: 50,
top: 50,
bottom: 20,
},
bufferPages: true,
});
Available Fonts : 'Courier', 'Helvetica', 'Symbol', 'Times-Roman', 'ZapfDingbats' and more.
Library methods can be called one after the other, which has its pros and cons
doc
.font('Helvetica')
.fontSize(8)
.lineGap(3)
.text(
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio
dignissimos similique adipisci? Ratione voluptates nemo odit possimus aspernatur vitae
officiis.',
posX,
posY,
{
width: 500,
align: 'left',
underline: true,
}
);
To create a table, I had to work the most. I created a helper function with which I could already create table headers and fill it dynamically.
function generateTableRow(doc, tableStartPosY, col1, col2, col3, col4, col5) {
const width = {
col1: 80,
col2: 130,
col3: 110,
col4: 70,
col5: 70,
};
const docMarginLeft = 50;
const tableGap = 10;
const col1_x = marginLeft;
const col2_x = tableGap + col1_x + width.col1;
const col3_x = tableGap + col2_x + width.col2;
const col4_x = tableGap + col3_x + width.col3;
const col5_x = tableGap + col4_x + width.col4;
doc
.fontSize(8)
.fill('#444444')
.text(col1, col1_x, tableStartPosY, { width: width.col1, align: 'left' })
.text(col2, col2_x, tableStartPosY, { width: width.col2, align: 'left' })
.text(col3, col3_x, tableStartPosY, { width: width.col3, align: 'right' })
.text(col4, col4_x, tableStartPosY, { width: width.col4, align: 'right' })
.text(col5, col5_x, tableStartPosY, { width: width.col5, align: 'right' });
}
Then called the function passing arguments to it
generateTableRow(
doc,
300,
item.invoiceDate,
item.invoiceNr,
item.tax,
item.shippingCosts,
item.packagingСosts
);
These links were very helpful throughout the project.
freeCodeCamp - Responsive Web Design Projects - Build a Technical Documentation Page