To use the Adobe SDK, you need to obtain your credentials from the Adobe Admin Console. Follow these steps to download your credentials:
config.zip file will be downloaded.config.zip file and extract the contents. You will find a pdfservices-api-credentials.json file containing your client_id, client_secret, and organization_id.Here is an example pdfservices-api-credentials.json file:
{
"client_credentials": {
"client_id": "e5d18eb1ca3e439e8c92bbab6878a5c0",
"client_secret": "p8e-8rZSPCqvPLJ3fIISF2Fz_AwQPFNmsFAr"
},
"service_principal_credentials": {
"organization_id": "10990B8D672DD3BF0A495C4E@AdobeOrg"
}
}
Install the Adobe SDK and set up your project.
Installation:
npm install --save @adobe/pdfservices-node-sdk
Initialize the Adobe SDK with your credentials.
Example:
const {
ServicePrincipalCredentials,
PDFServices,
MimeType,
DocumentMergeParams,
OutputFormat,
DocumentMergeJob,
DocumentMergeResult,
SDKError,
ServiceUsageError,
ServiceApiError
} = require("@adobe/pdfservices-node-sdk");
const fs = require("fs");
// Initial setup, create credentials instance
const credentials = new ServicePrincipalCredentials({
clientId: process.env.PDF_SERVICES_CLIENT_ID,
clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
// Creates a PDF Services instance
const pdfServices = new PDFServices({credentials});
Use the SDK to create a document.
Example:
// Create Document
(async () => {
try {
// Upload Template
const readStream = fs.createReadStream("resources/documentMergeTemplate.docx");
const inputAsset = await pdfServices.upload({readStream, mimeType: MimeType.DOCX});
// Document Merge Data
const jsonDataForMerge = {
customerName: 'Kane Miller',
customerVisits: 100,
itemsBought: [
{
description: 'Sprays', quantity: 50, amount: 100
},
{
description: 'Chemicals', quantity: 100, amount: 200
}
],
totalAmount: 300,
previousBalance: 50,
lastThreeBillings: [
100, 200, 300
],
photograph: 'data:image/png;base64,...'
};
// Job Parameters
const params = new DocumentMergeParams({
jsonDataForMerge,
outputFormat: OutputFormat.DOCX
});
// Submit Job and Get Result
const job = new DocumentMergeJob({
inputAsset,
params
});
const pollingURL = await pdfServices.submit({job});
const pdfServicesResponse = await pdfServices.getJobResult({pollingURL, resultType: DocumentMergeResult});
// Save Result
const resultAsset = pdfServicesResponse.result.asset;
const streamAsset = await pdfServices.getContent({asset: resultAsset});
const outputFilePath = "output/mergedDocument.docx";
const writeStream = fs.createWriteStream(outputFilePath);
streamAsset.readStream.pipe(writeStream);
} catch (error) {
console.error("Error:", error);
}
})();
Save the created document to your desired location.
Example:
// Generates a string containing a directory structure and file name for the output file
function createOutputFilePath() {
const filePath = "output/MergeDocumentToDOCX/";
const date = new Date();
const dateString = date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" +
("0" + date.getDate()).slice(-2) + "T" + ("0" + date.getHours()).slice(-2) + "-" +
("0" + date.getMinutes()).slice(-2) + "-" + ("0" + date.getSeconds()).slice(-2);
fs.mkdirSync(filePath, { recursive: true });
return (`${filePath}merge${dateString}.docx`);
}
// Save the document
(async () => {
let readStream;
try {
// Your existing code for creating the document...
// Create parameters for the job
const params = new DocumentMergeParams({
jsonDataForMerge,
outputFormat: OutputFormat.DOCX
});
// Creates a new job instance
const job = new DocumentMergeJob({ inputAsset, params });
// Submit the job and get the job result
const pollingURL = await pdfServices.submit({ job });
const pdfServicesResponse = await pdfServices.getJobResult({
pollingURL,
resultType: DocumentMergeResult
});
// Get content from the resulting asset(s)
const resultAsset = pdfServicesResponse.result.asset;
const streamAsset = await pdfServices.getContent({ asset: resultAsset });
// Creates a write stream and copy stream asset's content to it
const outputFilePath = createOutputFilePath();
console.log(`Saving asset at ${outputFilePath}`);
const writeStream = fs.createWriteStream(outputFilePath);
streamAsset.readStream.pipe(writeStream);
} catch (err) {
if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {
console.log("Exception encountered while executing operation", err);
} else {
console.log("Exception encountered while executing operation", err);
}
} finally {
readStream?.destroy();
}
})();
Create an .env file in your project root directory and add your Adobe credentials.
.env File:
PDF_SERVICES_CLIENT_ID=<YOUR CLIENT ID>
PDF_SERVICES_CLIENT_SECRET=<YOUR CLIENT SECRET>
Example pdfservices-api-credentials.json File:
{
"client_credentials": {
"client_id": "<YOUR_CLIENT_ID>",
"client_secret": "<YOUR_CLIENT_SECRET>"
},
"service_principal_credentials": {
"organization_id": "<YOUR_ORGANIZATION_ID>"
}
}
Running any sample or custom code requires the following steps:
@adobe/pdfservices-node-sdk npm package automatically downloads when you build the sample project.Installation:
npm install --save @adobe/pdfservices-node-sdk
The quickest way to get up and running is to download the code samples during the Getting Credentials workflow. These samples provide everything from ready-to-run sample code, an embedded credential json file, and pre-configured connections to dependencies.
npm install.Set the environment variables PDF_SERVICES_CLIENT_ID and PDF_SERVICES_CLIENT_SECRET by running the following commands:
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>
Test the sample code on the command line:
node yourSampleFile.js
Replace yourSampleFile.js with the actual name of your JavaScript file.
For security reasons, you may wish to confirm the installer’s authenticity. To do so:
Refer to the API docs for error and exception details.
The SDK uses the log4js API for logging. During execution, the SDK searches for config/pdfservices-sdk-log4js-config.json in the working directory and reads the logging properties from there. If you do not provide a configuration file, the default logging logs INFO to the console. Customize the logging settings as needed.
//log4js.properties file
{
"appenders": {
"consoleAppender": {
"_comment": "A sample console appender configuration, Clients can change as per their logging implementation",
"type": "console",
"layout": {
"type": "pattern",
"pattern": "%d:[%p]: %m"
}
}
},
"categories": {
"default": {
"appenders": ["consoleAppender"],
"_comment": "Change the logging levels as per need. info is recommended for pdfservices-node-sdk",
"level": "info"
}
}
}
While building the sample project automatically downloads the Node package, you can do it manually if you wish to use your own tools and process.
Go to https://www.npmjs.com/package/@adobe/pdfservices-node-sdk
Download the latest package.
Follow the installation instructions provided in the package documentation.
This should provide a clear and comprehensive guide for setting up and using the Adobe SDK to create documents 😊📚🚀.