NodeJs0How to Create PDFs in Node.js Using PDFKit

[ad_1]

PDFKit is a Node.js library that makes it easy for developers to create and work with PDF files. It offers a straightforward yet effective API for producing PDFs and adding different kinds of content to them, such as text, images, and shapes.


Learn how to use PDF Kit to create PDFs in Node.js.


Setting Up PDFkit

You must have Node.js and npm (the Node.js package manager) installed on your machine to follow along.

Ensure that you have these tools installed by running the following terminal commands:

 node -v
npm -v

To start using PDFKit in your Node.js project, install it by running the following npm command:

 npm install pdfkit

This command will install PDFKit and add it to your project’s dependencies.

Creating a PDF Document With PDFKit

To create a PDF document using PDFKit, require the pdfkit package and the fs (file system) module in your script file:

 const PDFDocument = require('pdfkit');
const fs = require('fs');

Next, create a new instance of the PDFDocument class. This class represents a PDF file:

 const doc = new PDFDocument();

The instance created is a readable stream, which means you can use the pipe() method to save its contents to a file.

To do this, pipe the doc instance into a writeable stream created by fs.createWriteStream:

 doc.pipe(fs.createWriteStream('MyPDFDoc.pdf'));

The createWriteStream method saves the contents of a PDF file to a specified location on the local file system.

The above code block will save the resulting PDF file to your current working directory, with the name MyPDFDoc.pdf.

It is important to always end the stream after adding content to the PDF. You can do that using this command:

 doc.end();

Now run the node command node [script name] to create the PDF file MyPDFDoc.pdf in your current working directory.

Adding Text With PDFKit

Before you pipe your document to save it, you can make various changes. PDFKit makes adding text to documents simple and includes many options to customize the display of the output.

To add text to the document, simply call the text() method and pass the text that you want to add as the argument:

 doc.text("Coding is Easy!")

As PDFKIT adds text to the document, it keeps track of that text’s current X and Y positions. So, whenever you call the text method, PDFKit will add a new line beneath the previous one.

However, by providing X and Y coordinates to the text method after the text itself, you can change its position:

 doc.text('Coding is Easy!', 100, 100)

To move up or down a line, call the moveDown or moveUp method with the number of lines the text should move:

 doc.moveDown(3);

doc.moveUp();

By default, calling either method without passing an argument will cause it to move by just a single line.

PDFKit supports each of the 14 standard fonts defined by the PDF format. The PDFKit text documentation has a complete list of these standard fonts.

Use the font() method to specify your required font. Just pass in the corresponding font name as a string:

 doc.font('Times-Roman')
   .text('Coding is Easy!');

You can also change the font size and text color using the fontSize() and the fillColor() methods, respectively.

For example:

 
doc.fillColor('red')
   .fontSize(8)
   .text('Coding is Easy!');

Adding Images With PDFKit

To an image to your PDF document, simply pass its path to the image method on the document instance:

 doc.image('path/to/image.jpeg')

PDFKit allows you to add images in either JPEG or PNG format.

By default, PDFKit will insert the image at its native size. You can change an image’s dimensions by providing an object containing key-value pairs as an argument to the image() method. You can specify a width, height, and horizontal and vertical alignment.

For example:

 
doc.image('path/to/image.jpg', { width: 300 });


doc.image('path/to/image.jpg', { width: 300, height:200 })

Adding Pages With PDFKit

To add new pages to the PDF document, simply call the addPage method on the document instance:

 doc.addPage()

To automatically add content every time you add a new page, use the pageAdded event on the document instance.

For example:

 doc.on('pageAdded', () => doc.text("Coding is Easy!"));

PDFKit lets you specify the page dimensions when making a new document or adding a new page to an existing one. There are several predefined page sizes that the PDFKit paper documentation explains.

To use any of these predefined page sizes, pass an object to either the PDFDocument constructor or the addPage() method. Use the size property to specify a string which is the name of the paper size.

For example:

 
const doc = new PDFDocument({ size: 'A5' });


doc.addPage({ size: 'A7' });

Passing this options object to the PDFDocument constructor sets the default page size for the whole document. You can then overwrite this default by passing a different value to the addPage method.

You can set page margins by passing an object to the margins property when adding pages.

The margins property takes an object with top, bottom, left, and right properties representing each margin.

For example:

 
doc.addPage({
  margins: {
    top: 72,
    bottom: 72,
    left: 50,
    right: 50
  }
});

This code sets the top and bottom margins to 72 points, and the left and right margins to 50 points. Note that the default margin for PDFKit-created documents is a 1-inch (72-point) margin on all sides.

To set all the top, bottom, left, and right margins to the same value, simply pass an object with a margin property to the addPage method:

 doc.addPage({ margin: 60 }) 

The Advantages of Creating PDFs With PDFKit in Node.js

PDFKit enables you to produce standard and supported documents from your Node.js applications. With PDFKit, you can handle complex documents easily. Additionally, it can facilitate the delivery of documents to users and make them simpler to share and print.

[ad_2]

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *