Quickstart for Adobe PDF Electronic Seal API (Node.js)
To get started using Adobe PDF Electronic Seal API, let's walk through a simple scenario - Applying an electronic seal on an invoice PDF document. In this guide, we will walk you through the complete process for creating a program that will accomplish this task.
Prerequisites
To complete this guide, you will need:
- Node.js - Node.js version 18.0 or higher is required.
- An Adobe ID. If you do not have one, the credential setup will walk you through creating one.
- A way to edit code. No specific editor is required for this guide.
Step One: Getting credentials
1) To begin, open your browser to https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-services-api. If you are not already logged in to Adobe.com, you will need to sign in or create a new user. Using a personal email account is recommended and not a federated ID.
2) After registering or logging in, you will then be asked to name your new credentials. Use the name, "New Project".
3) Change the "Choose language" setting to "Node.js".
4) Also note the checkbox by, "Create personalized code sample." This will include a large set of samples along with your credentials. These can be helpful for learning more later.
5) Click the checkbox saying you agree to the developer terms and then click "Create credentials."
6) After your credentials are created, they are automatically downloaded:
Step Two: Setting up the project
1) In your Downloads folder, find the ZIP file with your credentials: PDFServicesSDK-Node.jsSamples.zip. If you unzip that archive, you will find a folder of samples and the pdfservices-api-credentials.json
file.
2) Take the pdfservices-api-credentials.json
and place it in a new directory. Remember that these credential files are important and should be stored safely.
3) At the command line, change to the directory you created, and initialize a new Node.js project with npm init -y
4) Install the Adobe PDF Services Node.js SDK by typing npm install --save @adobe/pdfservices-node-sdk
at the command line.
5) Install a package to help us work with ZIP files. Type npm install --save adm-zip
.
At this point, we've installed the Node.js SDK for Adobe PDF Services API as a dependency for our project and have copied over our credentials files.
Our application will take an Invoice PDF document, sampleInvoice.pdf
(downloadable from here), and will use the sealing options with default appearance options to apply electronic seal over the PDF document by invoking Acrobat Services API and generate an electronically sealed PDF.
6) In your editor, open the directory where you previously copied the credentials. Create a new file, electronic-seal.js
.
Now you're ready to begin coding.
Step Three: Creating the application
1) We'll begin by including our required dependencies:
Copied to your clipboard1const {2 ServicePrincipalCredentials,3 PDFServices,4 MimeType,5 FieldLocation,6 FieldOptions,7 CSCAuthContext,8 CSCCredential,9 PDFElectronicSealParams,10 PDFElectronicSealJob,11 PDFElectronicSealResult,12 AppearanceOptions,13 AppearanceItem,14 SDKError,15 ServiceUsageError,16 ServiceApiError, DocumentLevelPermission17} = require("@adobe/pdfservices-node-sdk");18const fs = require("fs");
2) Set the environment variables PDF_SERVICES_CLIENT_ID
and PDF_SERVICES_CLIENT_SECRET
by running the following commands and replacing placeholders YOUR CLIENT ID
and YOUR CLIENT SECRET
with the credentials present in pdfservices-api-credentials.json
file:
Windows:
set PDF_SERVICES_CLIENT_ID=<YOUR CLIENT ID>
set PDF_SERVICES_CLIENT_SECRET=<YOUR CLIENT SECRET>
MacOS/Linux:
export PDF_SERVICES_CLIENT_ID=<YOUR CLIENT ID>
export PDF_SERVICES_CLIENT_SECRET=<YOUR CLIENT SECRET>
3) Next, we setup the SDK to use our credentials.
Copied to your clipboard1// Initial setup, create credentials instance2const credentials = new ServicePrincipalCredentials({3 clientId: process.env.PDF_SERVICES_CLIENT_ID,4 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET5});67// Creates a PDF Services instance8const pdfServices = new PDFServices({credentials});
4) Now, let's upload the assets:
Copied to your clipboard1const [sourceFileAsset, sealImageAsset] = await pdfServices.uploadAssets({2 streamAssets: [{3 readStream: sourceFileReadStream,4 mimeType: MimeType.PDF5 }, {6 readStream: sealImageReadStream,7 mimeType: MimeType.PNG8 }]9});
5) Now, we will define the document level permission:
Copied to your clipboard1// Set the document level permission to be applied for output document2const documentLevelPermission = DocumentLevelPermission.FORM_FILLING;
6) Now, we will define seal field options:
Copied to your clipboard1// Create AppearanceOptions and add the required signature appearance items2const sealAppearanceOptions = new AppearanceOptions({3 items: [4 AppearanceItem.DATE,5 AppearanceItem.SEAL_IMAGE,6 AppearanceItem.NAME,7 AppearanceItem.LABELS,8 AppearanceItem.DISTINGUISHED_NAME9 ]10});1112// Set the Seal Field Name to be created in input PDF document13const sealFieldName = "Signature1";1415// Set the page number in input document for applying seal16const sealPageNumber = 1;1718// Set if seal should be visible or invisible19const sealVisible = true;2021// Create FieldLocation instance and set the coordinates for applying signature22const fieldLocation = new FieldLocation({23 left: 150,24 top: 250,25 right: 350,26 bottom: 20027});2829// Create FieldOptions instance with required details30const sealFieldOptions = new FieldOptions({31 visible: sealVisible,32 location: fieldLocation,33 fieldName: sealFieldName,34 pageNumber: sealPageNumber,35});
7) Next, we create a CSC Certificate Credentials instance:
Copied to your clipboard1// Set the name of TSP Provider being used2const providerName = "<PROVIDER_NAME>";34// Set the access token to be used to access TSP provider hosted APIs5const accessToken = "<ACCESS_TOKEN>";67// Set the credential ID8const credentialId = "<CREDENTIAL_ID>";910// Set the PIN generated while creating credentials11const pin = "<PIN>";1213// Create CSCAuthContext instance using access token and token type14const authorizationContext = new CSCAuthContext({15 accessToken,16 tokenType: "Bearer"17});1819// Create CertificateCredentials instance with required certificate details20const certificateCredentials = new CSCCredential({21 providerName,22 credentialId,23 pin,24 authorizationContext,25});
8) Now, let's create the job with seal parameters using certificate credentials and field options and set the seal image asset:
Copied to your clipboard1// Create parameters for the job2const params = new PDFElectronicSealParams({3 documentLevelPermission4 certificateCredentials,5 sealFieldOptions,6 sealAppearanceOptions7});89// Creates a new job instance10const job = new PDFElectronicSealJob({11 inputAsset: sourceFileAsset,12 sealImageAsset,13 params,14});
This set of code defines what we're doing (an Electronic Seal operation), it defines parameters for the seal job and sets input seal image asset.
9) The next code block submits the job and gets the job result:
Copied to your clipboard1// Submit the job and get the job result2const pollingURL = await pdfServices.submit({job});3const pdfServicesResponse = await pdfServices.getJobResult({4 pollingURL,5 resultType: PDFElectronicSealResult6});78// Get content from the resulting asset(s)9const resultAsset = pdfServicesResponse.result.asset;10const streamAsset = await pdfServices.getContent({asset: resultAsset});
10) The next code block saves the result at the specified location:
Copied to your clipboard1// Creates a write stream and copy stream asset's content to it2const outputFilePath = "./sealedOutput.pdf";3console.log(`Saving asset at ${outputFilePath}`);45const writeStream = fs.createWriteStream(outputFilePath);6streamAsset.readStream.pipe(writeStream);
Here's the complete application (electronic-seal.js
):
Copied to your clipboard1const {2 ServicePrincipalCredentials,3 PDFServices,4 MimeType,5 FieldLocation,6 FieldOptions,7 CSCAuthContext,8 CSCCredential,9 PDFElectronicSealParams,10 PDFElectronicSealJob,11 PDFElectronicSealResult,12 AppearanceOptions,13 AppearanceItem,14 SDKError,15 ServiceUsageError,16 ServiceApiError, DocumentLevelPermission17} = require("@adobe/pdfservices-node-sdk");18const fs = require("fs");1920(async () => {2122 let sourceFileReadStream;23 let sealImageReadStream;24 try {25 // Initial setup, create credentials instance26 const credentials = new ServicePrincipalCredentials({27 clientId: process.env.PDF_SERVICES_CLIENT_ID,28 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET29 });3031 // Creates a PDF Services instance32 const pdfServices = new PDFServices({credentials});3334 // Creates an asset(s) from source file(s) and upload35 sourceFileReadStream = fs.createReadStream("./sampleInvoice.pdf")36 sealImageReadStream = fs.createReadStream("./sampleSealImage.png");37 const [sourceFileAsset, sealImageAsset] = await pdfServices.uploadAssets({38 streamAssets: [{39 readStream: sourceFileReadStream,40 mimeType: MimeType.PDF41 }, {42 readStream: sealImageReadStream,43 mimeType: MimeType.PNG44 }]45 });4647 // Set the document level permission to be applied for output document48 const documentLevelPermission = DocumentLevelPermission.FORM_FILLING;4950 // Create AppearanceOptions and add the required signature appearance items51 const sealAppearanceOptions = new AppearanceOptions({52 items: [53 AppearanceItem.DATE,54 AppearanceItem.SEAL_IMAGE,55 AppearanceItem.NAME,56 AppearanceItem.LABELS,57 AppearanceItem.DISTINGUISHED_NAME58 ]59 });6061 // Set the Seal Field Name to be created in input PDF document62 const sealFieldName = "Signature1";6364 // Set the page number in input document for applying seal65 const sealPageNumber = 1;6667 // Set if seal should be visible or invisible68 const sealVisible = true;6970 // Create FieldLocation instance and set the coordinates for applying signature71 const fieldLocation = new FieldLocation({72 left: 150,73 top: 250,74 right: 350,75 bottom: 20076 });7778 // Create FieldOptions instance with required details79 const sealFieldOptions = new FieldOptions({80 visible: sealVisible,81 location: fieldLocation,82 fieldName: sealFieldName,83 pageNumber: sealPageNumber,84 });8586 // Set the name of TSP Provider being used87 const providerName = "<PROVIDER_NAME>";8889 // Set the access token to be used to access TSP provider hosted APIs90 const accessToken = "<ACCESS_TOKEN>";9192 // Set the credential ID93 const credentialId = "<CREDENTIAL_ID>";9495 // Set the PIN generated while creating credentials96 const pin = "<PIN>";9798 // Create CSCAuthContext instance using access token and token type99 const authorizationContext = new CSCAuthContext({100 accessToken,101 tokenType: "Bearer"102 });103104 // Create CertificateCredentials instance with required certificate details105 const certificateCredentials = new CSCCredential({106 providerName,107 credentialId,108 pin,109 authorizationContext,110 });111112 // Create parameters for the job113 const params = new PDFElectronicSealParams({114 documentLevelPermission115 certificateCredentials,116 sealFieldOptions,117 sealAppearanceOptions118 });119120 // Creates a new job instance121 const job = new PDFElectronicSealJob({122 inputAsset: sourceFileAsset,123 sealImageAsset,124 params,125 });126127 // Submit the job and get the job result128 const pollingURL = await pdfServices.submit({job});129 const pdfServicesResponse = await pdfServices.getJobResult({130 pollingURL,131 resultType: PDFElectronicSealResult132 });133134 // Get content from the resulting asset(s)135 const resultAsset = pdfServicesResponse.result.asset;136 const streamAsset = await pdfServices.getContent({asset: resultAsset});137138 // Creates a write stream and copy stream asset's content to it139 const outputFilePath = "./sealedOutput.pdf";140 console.log(`Saving asset at ${outputFilePath}`);141142 const writeStream = fs.createWriteStream(outputFilePath);143 streamAsset.readStream.pipe(writeStream);144 } catch (err) {145 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {146 console.log("Exception encountered while executing operation", err);147 } else {148 console.log("Exception encountered while executing operation", err);149 }150 } finally {151 sourceFileReadStream?.destroy();152 sealImageReadStream?.destroy();153 }154})();
Next Steps
Now that you've successfully performed your first operation, review the documentation for many other examples and reach out on our forums with any questions. Also remember the samples you downloaded while creating your credentials also have many demos.