Blog Post

Generating PDFs in Angular with jsPDF and Nutrient Web SDK

Illustration: Generating PDFs in Angular with jsPDF and Nutrient Web SDK

Whether you need to create invoices, reports, or downloadable documents, converting web content into PDF format can significantly enhance the functionality of your Angular application. In this post, we’ll walk you through the process of generating PDFs using Angular — first with a basic approach using jspdf, and then with a more powerful approach using Nutrient Web SDK.

Prerequisites

  • Node.js v18.13 or higher and npm (Node Package Manager)

Generating PDFs using jsPDF

In this section, we’ll focus on using jsPDF to convert web content into PDF format, providing a straightforward approach to PDF generation in your Angular projects.

Step 1 — Angular installation

Start by installing Angular CLI, a powerful tool for creating and managing Angular projects. Open your terminal and run the following command:

npm install -g @angular/cli

This command installs Angular CLI globally on your system, allowing you to create and manage Angular projects.

Step 2 — Creating a new Angular project

With Angular CLI installed, you can create a new Angular project. Navigate to the directory where you want to create your project and run the following command:

ng new angular-pdf-generator

Angular CLI will prompt you to choose various project configuration options. You can either accept the defaults or customize them according to your preferences.

After creating the project, navigate to the project directory using the following command:

cd angular-pdf-generator

Step 3 — Installing the required packages

To generate PDFs in Angular, you’ll use two libraries: jspdf and jspdf-autotable. Install them using npm:

npm install jspdf jspdf-autotable

These packages will enable you to create and customize PDFs within your Angular application.

Step 4 — Creating a PDF generation component

Angular follows a component-based architecture. Create a component dedicated to PDF generation. Run the following command:

ng generate component pdf-generator

This command will generate a new component named pdf-generator with associated files for HTML, CSS, and TypeScript.

Step 5 — Writing the PDF generation code

Inside the pdf-generator component, open the pdf-generator.component.ts file. In this file, you’ll write the code responsible for generating PDFs:

import { Component } from '@angular/core';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

@Component({
	selector: 'app-pdf-generator',
	templateUrl: './pdf-generator.component.html',
	styleUrls: ['./pdf-generator.component.css'],
})
export class PdfGeneratorComponent {
	generatePDF() {
		// Create a new PDF document.
		const doc = new jsPDF();

		// Add content to the PDF.
		doc.setFontSize(16);
		doc.text('My Angular PDF Generator', 10, 10);
		doc.setFontSize(12);
		doc.text(
			'This is a comprehensive guide on generating PDFs with Angular.',
			10,
			20,
		);

		// Create a table using `jspdf-autotable`.
		const headers = [['Name', 'Email', 'Country']];
		const data = [
			['David', '[email protected]', 'Sweden'],
			['Castille', '[email protected]', 'Spain'],
			// ...
		];

		autoTable(doc, {
			head: headers,
			body: data,
			startY: 30, // Adjust the `startY` position as needed.
		});

		// Save the PDF.
		doc.save('table.pdf');
	}
}

Here, the code defines an Angular component named PdfGeneratorComponent that generates a PDF document with text and a table when a button is clicked. It uses the jsPDF library for PDF creation and jspdf-autotable for building tables within the PDF. The PDF is saved with the name table.pdf.

Now open the pdf-generator.component.html file. Add a button element that will trigger the generatePDF() function when clicked. Place this button within your component’s template:

<div>
	<button (click)="generatePDF()">Generate PDF</button>
</div>

Step 6 — Displaying the PDF generation component

Now that you have your PdfGeneratorComponent, you’ll display it in your Angular application. Open the app.component.html file and add the <app-pdf-generator></app-pdf-generator> tag inside the template:

<div>
	<!-- Your navigation or other content can go here -->
	<app-pdf-generator></app-pdf-generator>
</div>

To incorporate the PdfGeneratorComponent into your Angular application, you need to import it into your app.component.ts file. This is achieved by adding the following import statement at the top:

import { PdfGeneratorComponent } from './pdf-generator/pdf-generator.component';

Next, you include PdfGeneratorComponent in the imports array of the @Component decorator. This setup allows you to use the <app-pdf-generator></app-pdf-generator> tag in your application’s HTML template, enabling users to generate PDFs directly from the main interface.

Here’s how your app.component.ts will look:

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { PdfGeneratorComponent } from './pdf-generator/pdf-generator.component';

@Component({
	selector: 'app-root',
	standalone: true,
	imports: [RouterOutlet, PdfGeneratorComponent],
	templateUrl: './app.component.html',
	styleUrls: ['./app.component.css'],
})
export class AppComponent {
	title = 'angular-pdf-generator';
}

Step 7 — Starting the development server

To see your Angular application in action, start the development server with the following command:

ng serve

Your application will be available at http://localhost:4200/. The application will display a Generate PDF button. When this button is clicked, the PDF will be generated as specified in the generatePDF() function.

resulting pdf

Angular PDF generation library: Nutrient Web SDK

While the steps outlined above demonstrate PDF generation using jsPDF, an alternative approach is to use a specialized library like Nutrient Web SDK. This JavaScript library is designed for generating and manipulating PDF documents in Angular-based web applications. Nutrient Web SDK offers a wide range of capabilities, making it a powerful tool for your PDF needs:

  • Create from template — Insert text or images and prefill forms.

  • Generate from images — Convert JPGs, PNGs, or TIFFs into PDF.

  • Assemble documents — Merge multiple PDFs and insert pages.

  • Thumbnail previews — Render pages as thumbnail images.

  • Saving options — Save PDFs to an array buffer, local storage, or a remote server.

  • Headless — Optionally, generate PDFs without displaying the user interface.

  • Client-side — Create PDFs directly in a browser (no server needed).

  • Extendable — Add viewing, forms, signing, annotation, and more.

How to generate PDFs from a template using Nutrient and Angular

Now, you’ll learn how to use Nutrient with Angular to generate PDF documents from predefined PDF templates by merging them with data. This can be incredibly useful for various applications, like generating invoices, contracts, tickets, or any structured documents.

Step 1 — Setting up your Angular project

In recent Angular setups, especially when creating a new project, you might notice that there isn’t an assets directory created by default. This is often due to changes in Angular’s project structure in newer versions. If you don’t have this directory, simply create it under src:

mkdir src/assets

Now, let’s go back to our tutorial and see how to integrate Nutrient into your Angular project.

Create a new Angular project for Nutrient integration:

ng new pspdfkit-web-example-angular

This will ask some configuration questions. Choose No for routing and CSS for the stylesheet. Now, change your directory to this project:

cd pspdfkit-web-example-angular

Step 2 — Adding Nutrient

Install pspdfkit as a dependency with npm or yarn:

npm install pspdfkit

or

yarn add pspdfkit

Now, add the following to your angular.json file. Angular will copy the Nutrient library assets to the assets directory before running your app:

"assets": [
    "src/favicon.ico",
	"src/assets",
   {
  	"glob": "**/*",
	"input": "./node_modules/pspdfkit/dist/pspdfkit-lib/",
	"output": "./assets/pspdfkit-lib/"
	}
]

Step 3 — Loading the PDF document

First, you need to load the PDF document you want to populate with data. Depending on your use case, you can load it in a PDF viewer with a user interface (UI) or in headless mode without a UI. The example here uses the headless mode:

Add your PDF document to the src/assets directory. You can use our demo document as an example.

Replace the contents of app.component.ts with the following:

// src/app/app.component.ts

import { Component } from '@angular/core';
import PSPDFKit from 'pspdfkit';

@Component({
	selector: 'app-root',
	templateUrl: './app.component.html',
	styleUrls: ['./app.component.css'],
	standalone: true,
})
export class AppComponent {
	title = 'PSPDFKit for Web Angular Example';

	ngAfterViewInit() {
		(async () => {
			const baseUrl =
				location.protocol + '//' + location.host + '/assets/';

			const instance: any = await PSPDFKit.load({
				baseUrl,
				document: '/assets/document.pdf', // Specify the path to your PDF template.
				container: '#pspdfkit-container',
				headless: true, // Load in headless mode.
			});
		})();
	}
}
  1. Replace the contents of app.component.html with:

<div class="app">
	<div class="toolbar">PSPDFKit Angular Application</div>

	<!-- We'll mount the PSPDFKit UI to this element. -->
	<div id="pspdfkit-container"></div>
</div>

The license key is optional; however, you may see a watermark on your PDF files without a key. To get a key, contact [sales][].

If you try to run your project, you may get an error stating the mounting container has no height. To fix this issue, add the following styles to the src/app/app.component.css file:

:host {
	height: 100%;
}

.app {
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
}

.toolbar {
	position: relative;
	display: flex;
	align-items: center;
	height: 64px;
	width: 100%;
	padding: 0 24px;
	box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
	font-family: sans-serif;
	font-size: 20px;
	font-weight: 500;
	color: rgba(0, 0, 0, 0.8);
}

#pspdfkit-container {
	height: calc(100% - 64px);
}

Step 4 — Creating the data source

To populate the PDF document with dynamic data, you need a data source. Create a data.json file in the src/assets/ directory with the following content:

{
	"company": "PSPDFKit",
	"companyInfo": "PSPDFKit",
	"companyName": "PSPDFKit"
}

This file contains the sample data that will be merged into the PDF document.

Step 5 — Populating the document with data

To populate the document, you can overlay annotations onto the PDF template. Here’s how you can do this by creating a TextAnnotation:

// Create a free text annotation.
const textAnnotation = new PSPDFKit.Annotations.TextAnnotation({
	boundingBox: bbox, // Set the bounding box of the text annotation.
	fontSize: 8,
	text: {
		format: 'plain', // Specify the format (e.g. 'plain' or 'html').
		value: data.company, // The actual text content.
	},
	pageIndex: 0, // The page index to overlay the text on.
	fontColor: PSPDFKit.Color.RED,
	backgroundColor: PSPDFKit.Color.WHITE,
});

// Add the annotations to the document.
await instance.create(textAnnotation);
  • boundingBox — Define the position and size of the text annotation.

  • fontSize — Set the font size.

  • text — Provide the text content within the value property.

  • pageIndex — Specify the page index where you want to overlay the text.

Repeat this process for other data points that you want to overlay on the document.

Step 6 — Flattening the annotations (optional)

You can optionally flatten the annotations to prevent modification:

await instance.exportPDF({ flatten: true });

Flattening the annotations makes the PDF template appear as though the text was originally part of the document.

Here’s the complete code for populating the PDF template with data:

// src/app/app.component.ts

import { Component } from '@angular/core';
import PSPDFKit from 'pspdfkit';

@Component({
	selector: 'app-root',
	templateUrl: './app.component.html',
	styleUrls: ['app.component.css'],
	standalone: true,
})
export class AppComponent {
	title = 'PSPDFKit for Web Angular Example';

	ngAfterViewInit() {
		// Load the PDF document in headless mode.
		(async () => {
			const baseUrl =
				location.protocol + '//' + location.host + '/assets/';
			const searchQuery = 'Company Ltd.';

			try {
				const res = await fetch('/assets/data.json');
				if (res.ok) {
					const data = await res.json(); // Define and initialize 'data'.
					// Now you can use 'data' here.

					// Load the PDF document in headless mode.
					const instance: any = await PSPDFKit.load({
						baseUrl,
						document: '/assets/document.pdf', // Specify the path to your PDF template.
						container: '#pspdfkit-container',
						headless: true,
					});

					// Create a free text annotation.
					const textAnnotation = new PSPDFKit.Annotations.TextAnnotation(
						{
							// COMPANY bounding box.
							boundingBox: new PSPDFKit.Geometry.Rect({
								height: 9.0675048828125,
								left: 60.375,
								top: 37.739990234375,
								width: 46.905006408691406,
							}),
							fontSize: 8,
							text: {
								format: 'plain', // Specify the format (e.g. 'plain' or 'html').
								value: data.company, // The actual text content.
							},
							pageIndex: 0,
							fontColor: PSPDFKit.Color.RED,
							backgroundColor: PSPDFKit.Color.WHITE,
						},
					);

					const textAnnotation2 = new PSPDFKit.Annotations.TextAnnotation(
						{
							// [Company Info] bounding box.
							boundingBox: new PSPDFKit.Geometry.Rect({
								height: 9.0675048828125,
								left: 478.6350402832031,
								top: 37.739990234375,
								width: 82.69503784179688,
							}),
							fontSize: 8,
							text: {
								format: 'plain',
								value: data.companyInfo,
							},
							pageIndex: 0,
							fontColor: PSPDFKit.Color.RED,
							backgroundColor: PSPDFKit.Color.WHITE,
						},
					);

					// Company Ltd. bounding box.
					const bbox = (await instance.search(searchQuery))
						.first()
						.rectsOnPage.get(0);

					const textAnnotation3 = new PSPDFKit.Annotations.TextAnnotation(
						{
							boundingBox: bbox,
							fontSize: 8,
							text: {
								format: 'plain',
								value: data.companyName,
							},
							pageIndex: 0,
							fontColor: PSPDFKit.Color.RED,
							backgroundColor: PSPDFKit.Color.WHITE,
						},
					);

					// Add the annotations to the document.
					await instance.create([
						textAnnotation,
						textAnnotation2,
						textAnnotation3,
					]);
					// Flatten the annotations.
					const pdfBuffer = await instance.exportPDF({
						flatten: true,
					});

					// Load the PDF with the UI.
					await PSPDFKit.load({
						baseUrl,
						document: pdfBuffer, // Use the flattened PDF.
						container: '#pspdfkit-container',
					});
				} else {
					// Handle server error.
					console.error(
						'Server returned an error:',
						res.status,
						res.statusText,
					);
				}
			} catch (error) {
				console.error(
					'An error occurred while fetching or parsing data:',
					error,
				);
			}
		})();
	}
}

With these steps, you’ve learned how to use PSPDFKit and Angular to generate PDFs from templates by merging them with data. This approach is powerful for creating structured documents in various applications.

Run your project with the following command:

npm start

resulting pdf

For a detailed explanation, check out our guide on how to generate PDFs from a template using JavaScript.

Conclusion

In summary, while basic libraries like jspdf can fulfill simpler PDF generation needs, Nutrient Web SDK excels in scenarios where you require more advanced capabilities, better control, and enhanced functionality. It’s the go-to choice for projects that involve creating structured documents, managing various aspects of PDF files, and empowering your Angular application with a versatile PDF generation and manipulation library.

To get started, you can either:

  • Start your free trial to test the library and see how it works in your application.

  • Launch our demo to see the viewer in action.

FAQ

Here are a few frequently asked questions about generating PDFs using Angular.

How can I generate PDFs in an Angular application?

You can generate PDFs in an Angular application using libraries like jsPDF, pdfmake, or html2pdf.js. These libraries help convert HTML content to PDF format within Angular components.

What are the steps to install jsPDF in an Angular project?

Install jsPDF using npm with the command npm install jspdf. Then import it into your Angular component and use its methods to create and customize PDF documents.

What are the benefits of using Angular for PDF generation?

Angular’s component-based architecture allows for modular and maintainable code, making it easy to create, manage, and reuse the content that will be converted to PDF.

What is Nutrient Web SDK, and how does it enhance PDF generation in Angular?

Nutrient Web SDK is a powerful JavaScript library designed for generating and manipulating PDF documents in web applications. It provides advanced capabilities such as creating PDFs from templates, converting images to PDFs, assembling documents, rendering thumbnails, and more, making it an ideal choice for complex and feature-rich PDF generation needs.

What are the benefits of using Nutrient over basic libraries like jsPDF?

Nutrient offers a wide range of advanced features, such as creating PDFs from templates, generating PDFs from images, assembling documents, rendering thumbnails, and more. It provides better control and enhanced functionality, making it suitable for projects requiring complex and structured document creation and management.

Can I generate PDFs without displaying the user interface using Nutrient?

Yes, Nutrient allows you to generate PDFs in headless mode, which means you can create PDFs directly in the browser without displaying any user interface.

Author
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at Nutrient who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

Explore related topics

Related products
Share post
Free trial Ready to get started?
Free trial