Blog Post

How to Add a Signature to a PDF Using Vue.js

Abdul Jabar
Illustration: How to Add a Signature to a PDF Using Vue.js

In this blog post, you’ll add a signature to a PDF document using PSPDFKit and Vue.js. PSPDFKit is a JavaScript PDF library that can quickly be integrated into an application to enable electronic and encrypted-based digital signatures.

Vue.js is a frontend JavaScript framework mainly used for creating user interfaces (UIs) and one-page applications. It allows users to make prototypes and build applications quickly and reliably. One of the best things about Vue.js is it can be used for both desktop and mobile app development, which makes it a great frontend tool for working on any application or system.

Signing PDFs in Vue.js

Users can add signatures to PDFs by drawing, typing, or selecting an image. The drawing option allows users to freehand draw a signature. The typing option lets them type their names and then add a style to their signatures. The final option is to upload an image that’s already saved in their gallery by selecting and dragging the image into the signature box.

Signature Support

The Vue.js signature library supports:

  • Electronic signatures, which are created through ink, bitmaps, text, and drawings.

  • Digital signatures, which include a certificate that provides a unique identifier for the signer. These are used as proof of the document’s origin and can prevent modification by any other person.

PSPDFKit’s Vue.js PDF Library

At PSPDFKit, we offer a commercial, feature-rich, and completely customizable Vue.js PDF library that’s easy to integrate and comes with well-documented APIs to handle advanced use cases. It comes with:

  • Annotation tools — Draw, circle, highlight, comment, and add notes to documents with 15+ prebuilt annotation tools.

  • File support — View PNG, JPG, and TIFF files on the client side. With server deployment, users can view MS Office documents.

  • 30+ features — Easily add features like PDF editing, digital signatures, form filling, real-time document collaboration, and more.

  • Dedicated support — Deploy faster by working 1-on-1 with our developers.

Try it for free, or visit our web demo to see it in action.

Requirements

For adding a signature to a PDF, you’ll need the following software installed:

  • Git — An open source version control system used to control projects efficiently.

  • Node.js — An open source server provider that uses JavaScript on its server. This post uses version 16.13.0.

Installing the Vue CLI

To create, build, and run Vue.js applications, you need to install Vue CLI, which is standard tooling for Vue.js.

You can install the CLI using npm — which comes with Node.js — or yarn:

npm install -g @vue/cli
yarn global add @vue/cli

You can check the version of Vue.js by running the following:

vue --version

This post uses Vue.js CLI version 3.2.37.

Now, create a new Vue.js project to integrate with PSPDFKit using the following command:

vue create pspdfkit-signature-project

You’ll be asked some configuration questions. Select the default option, and then change your directory to pspdfkit-signature-project:

cd pspdfkit-signature-project

Now, add the PSPDFKit dependency to your project:

npm install pspdfkit

Once installed, create a js directory under the project location with the following command:

mkdir -p public/js

Now your project is ready for the digital signature to be added to the PDF, but you have to create a digital signature. This requires two things, outlined below.

  • First, you need the X.509 certificate that contains the public key and the signer information to sign digitally. Verify the PKCS#7 certificate using the following command:

openssl pkcs7 -noout -text -print_certs -in example.p7b
  • Second, you need the self-signed private key and the certificate pair.

Refer to the Add Digital Signatures to PDFs Using JavaScript guide for more information on how to create a digital signature.

Signing Process

You’ll now generate a valid digital signature using the cryptographic Distinguished Encoding Rules (DER) PKCS#7 format. For this, you need to call the PSPDFKit.Instance#signDocument method in your code by passing the data to adjust aspects of the signing process in the first argument list.

In the second argument, you need to pass fileContents, which is used as a callback object with an ArrayBuffer containing the content of the document. This will return a promise, which will resolve the ArrayBuffer or reject the case when an error occurs.

The following code shows how to generate and fetch the private key using the network call:

function generatePKCS7({ fileContents }) {
	const certificatePromise = fetch(
		'certs/certificate.pem',
	).then((response) => response.text());
	const privateKeyPromise = fetch(
		'certs/private-key.pem',
	).then((response) => response.text());
	return new Promise((resolve, reject) => {
		Promise.all([certificatePromise, privateKeyPromise])
			.then(([certificatePem, privateKeyPem]) => {
				const certificate = forge.pki.certificateFromPem(
					certificatePem,
				);
				const privateKey = forge.pki.privateKeyFromPem(
					privateKeyPem,
				);

				const p7 = forge.pkcs7.createSignedData();
				p7.content = new forge.util.ByteBuffer(fileContents);
				p7.addCertificate(certificate);
				p7.addSigner({
					key: privateKey,
					certificate: certificate,
					digestAlgorithm: forge.pki.oids.sha256,
					authenticatedAttributes: [
						{
							type: forge.pki.oids.contentType,
							value: forge.pki.oids.data,
						},
						{
							type: forge.pki.oids.messageDigest,
						},
						{
							type: forge.pki.oids.signingTime,
							value: new Date(),
						},
					],
				});

				p7.sign({ detached: true });
				const result = stringToArrayBuffer(
					forge.asn1.toDer(p7.toAsn1()).getBytes(),
				);
				resolve(result);
			})
			.catch(reject);
	});
}

// https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
function stringToArrayBuffer(binaryString) {
	const buffer = new ArrayBuffer(binaryString.length);
	let bufferView = new Uint8Array(buffer);
	for (let i = 0, len = binaryString.length; i < len; i++) {
		bufferView[i] = binaryString.charCodeAt(i);
	}
	return buffer;
}

You successfully fetched the certificate and the private key in the code snippet above. You also created the container of the DER PKCS#7 using the file contents. Now that your signing callback is defined, call PSPDFKit.Instance#signDocument:

instance
	.signDocument(null, generatePKCS7)
	.then(() => {
		console.log('document signed.');
	})
	.catch((error) => {
		console.error('The document could not be signed.', error);
	});

Once the code above is successfully built, the signing process will run automatically and the document will reload with the new digital signature added to it.

Conclusion

In this post, you learned how to create a Vue.js signature pad using PSPDFKit’s library. If you have any issues doing this, don’t hesitate to reach out to our Support team for help.

If you’d like to test the PSPDFKit for Web SDK, you can request a free trial. Alternatively, you can browse our demo to see what our SDK is capable of.

Related Products
Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
PRODUCTS  |  Web • Releases • Components

PSPDFKit for Web 2024.3 Features New Stamps and Signing UI, Export to Office Formats, and More

PRODUCTS  |  Web • Releases • Components

PSPDFKit for Web 2024.2 Features New Unified UI Icons, Shadow DOM, and Tab Ordering

PRODUCTS  |  Web

Now Available for Public Preview: New Document Authoring Experience Provides Glimpse into the Future of Editing