";
+```javascript
+// Create parameters for the job
+const params = new PDFElectronicSealParams({
+ documentLevelPermission
+ certificateCredentials,
+ sealFieldOptions,
+ sealAppearanceOptions
+});
+
+// Creates a new job instance
+const job = new PDFElectronicSealJob({
+ inputAsset: sourceFileAsset,
+ sealImageAsset,
+ params,
+});
+```
-//Create CSCAuthContext instance using access token and token type.
-cscAuthContext = new options.CSCAuthContext(accessToken, "Bearer");
+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.
-//Create CertificateCredentials instance with required certificate details.
-certificateCredentials = options.CertificateCredentials.cscCredentialBuilder()
- .withProviderName(providerName)
- .withCredentialID(credentialID)
- .withPin(pin)
- .withCSCAuthContext(cscAuthContext)
- .build();
+9) The next code block submits the job and gets the job result:
+```javascript
+// Submit the job and get the job result
+const pollingURL = await pdfServices.submit({job});
+const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: PDFElectronicSealResult
+});
+
+// Get content from the resulting asset(s)
+const resultAsset = pdfServicesResponse.result.asset;
+const streamAsset = await pdfServices.getContent({asset: resultAsset});
```
-8) Now, let's create the seal options with certificate credentials and field options:
+10) The next code block saves the result at the specified location:
```javascript
- //Create SealOptions instance with sealing parameters.
-sealOptions = new options.SealOptions.Builder(certificateCredentials, fieldOptions)
- .withAppearanceOptions(appearanceOptions)
- .build()
-```
+// Creates a write stream and copy stream asset's content to it
+const outputFilePath = "./sealedOutput.pdf";
+console.log(`Saving asset at ${outputFilePath}`);
+const writeStream = fs.createWriteStream(outputFilePath);
+streamAsset.readStream.pipe(writeStream);
+```
-9) Now, let's create the operation:
+Here's the complete application (`electronic-seal.js`):
```javascript
-//Create the PDFElectronicSealOperation instance using the SealOptions instance
-const pdfElectronicSealOperation = pdfElectronicSeal.Operation.createNew(sealOptions);
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ FieldLocation,
+ FieldOptions,
+ CSCAuthContext,
+ CSCCredential,
+ PDFElectronicSealParams,
+ PDFElectronicSealJob,
+ PDFElectronicSealResult,
+ AppearanceOptions,
+ AppearanceItem,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError, DocumentLevelPermission
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+
+ let sourceFileReadStream;
+ let sealImageReadStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
+ });
-//Set the input source file for PDFElectronicSealOperation instance
-pdfElectronicSealOperation.setInput(sourceFile);
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ sourceFileReadStream = fs.createReadStream("./sampleInvoice.pdf")
+ sealImageReadStream = fs.createReadStream("./sampleSealImage.png");
+ const [sourceFileAsset, sealImageAsset] = await pdfServices.uploadAssets({
+ streamAssets: [{
+ readStream: sourceFileReadStream,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: sealImageReadStream,
+ mimeType: MimeType.PNG
+ }]
+ });
-//Set the optional input seal image for PDFElectronicSealOperation instance
-pdfElectronicSealOperation.setSealImage(sealImageFile);
+ // Set the document level permission to be applied for output document
+ const documentLevelPermission = DocumentLevelPermission.FORM_FILLING;
+
+ // Create AppearanceOptions and add the required signature appearance items
+ const sealAppearanceOptions = new AppearanceOptions({
+ items: [
+ AppearanceItem.DATE,
+ AppearanceItem.SEAL_IMAGE,
+ AppearanceItem.NAME,
+ AppearanceItem.LABELS,
+ AppearanceItem.DISTINGUISHED_NAME
+ ]
+ });
-```
-This code creates a seal operation using sealOptions, input source file and input seal image.
+ // Set the Seal Field Name to be created in input PDF document
+ const sealFieldName = "Signature1";
-10) Let's execute this seal operation:
+ // Set the page number in input document for applying seal
+ const sealPageNumber = 1;
-```javascript
-// Execute the operation and Save the result to the specified location.
-pdfElectronicSealOperation.execute(executionContext)
- .then(result => result.saveAsFile("output/sealedOutput.pdf"))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+ // Set if seal should be visible or invisible
+ const sealVisible = true;
+
+ // Create FieldLocation instance and set the coordinates for applying signature
+ const fieldLocation = new FieldLocation({
+ left: 150,
+ top: 250,
+ right: 350,
+ bottom: 200
});
-```
-Here's the complete application (`electronic-seal.js`):
+ // Create FieldOptions instance with required details
+ const sealFieldOptions = new FieldOptions({
+ visible: sealVisible,
+ location: fieldLocation,
+ fieldName: sealFieldName,
+ pageNumber: sealPageNumber,
+ });
-```javascript
-/*
- * Copyright 2023 Adobe
- * All Rights Reserved.
- *
- * NOTICE: Adobe permits you to use, modify, and distribute this file in
- * accordance with the terms of the Adobe license agreement accompanying
- * it. If you have received this file from a source other than Adobe,
- * then your use, modification, or distribution of it requires the prior
- * written permission of Adobe.
- */
-
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-/**
- * This sample illustrates how to apply electronic seal over the PDF document using custom appearance options.
- *
- *
- * To know more about PDF Electronic Seal, please see the <documentation.
- *
- * Refer to README.md for instructions on how to run the samples.
- */
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
- .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- const pdfElectronicSeal = PDFServicesSdk.PDFElectronicSeal,
- options = pdfElectronicSeal.options;
-
- //Get the input document to perform the sealing operation
- const sourceFile = PDFServicesSdk.FileRef.createFromLocalFile('./sampleInvoice.pdf'),
-
- //Get the background seal image for signature , if required.
- sealImageFile = PDFServicesSdk.FileRef.createFromLocalFile('./sampleSealImage.png');
-
- //Create AppearanceOptions and add the required signature appearance items
- appearanceOptions = new options.AppearanceOptions();
- appearanceOptions.addItem(options.AppearanceOptions.AppearanceItem.DATE);
- appearanceOptions.addItem(options.AppearanceOptions.AppearanceItem.SEAL_IMAGE);
- appearanceOptions.addItem(options.AppearanceOptions.AppearanceItem.NAME);
- appearanceOptions.addItem(options.AppearanceOptions.AppearanceItem.LABELS);
- appearanceOptions.addItem(options.AppearanceOptions.AppearanceItem.DISTINGUISHED_NAME);
-
- // Set the Seal Field Name to be created in input PDF document.
- sealFieldName = "Signature1";
-
- // Set the page number in input document for applying seal.
- sealPageNumber = 1;
-
- // Set if seal should be visible or invisible.
- sealVisible = true;
-
- //Create FieldLocation instance and set the coordinates for applying signature
- fieldLocation = new options.FieldLocation(150,250,350,200);
-
- //Create FieldOptions instance with required details.
- fieldOptions = new options.FieldOptions.Builder(sealFieldName)
- .setFieldLocation(fieldLocation)
- .setPageNumber(sealPageNumber)
- .setVisible(sealVisible)
- .build();
-
- //Set the name of TSP Provider being used.
- providerName = "";
-
- //Set the access token to be used to access TSP provider hosted APIs.
- accessToken = "";
-
- //Set the credential ID.
- credentialID = "";
-
- //Set the PIN generated while creating credentials.
- pin = "";
-
- //Create CSCAuthContext instance using access token and token type.
- cscAuthContext = new options.CSCAuthContext(accessToken, "Bearer");
-
- //Create CertificateCredentials instance with required certificate details.
- certificateCredentials = options.CertificateCredentials.cscCredentialBuilder()
- .withProviderName(providerName)
- .withCredentialID(credentialID)
- .withPin(pin)
- .withCSCAuthContext(cscAuthContext)
- .build();
-
- //Create SealOptions instance with sealing parameters.
- sealOptions = new options.SealOptions.Builder(certificateCredentials, fieldOptions)
- .withAppearanceOptions(appearanceOptions)
- .build()
-
- //Create the PDFElectronicSealOperation instance using the SealOptions instance
- const pdfElectronicSealOperation = pdfElectronicSeal.Operation.createNew(sealOptions);
-
- //Set the input source file for PDFElectronicSealOperation instance
- pdfElectronicSealOperation.setInput(sourceFile);
-
- //Set the optional input seal image for PDFElectronicSealOperation instance
- pdfElectronicSealOperation.setSealImage(sealImageFile);
-
- // Execute the operation and Save the result to the specified location.
- pdfElectronicSealOperation.execute(executionContext)
- .then(result => result.saveAsFile("output/sealedOutput.pdf"))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
-
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+ // Set the name of TSP Provider being used
+ const providerName = "";
+
+ // Set the access token to be used to access TSP provider hosted APIs
+ const accessToken = "";
+
+ // Set the credential ID
+ const credentialId = "";
+
+ // Set the PIN generated while creating credentials
+ const pin = "";
+
+ // Create CSCAuthContext instance using access token and token type
+ const authorizationContext = new CSCAuthContext({
+ accessToken,
+ tokenType: "Bearer"
+ });
+
+ // Create CertificateCredentials instance with required certificate details
+ const certificateCredentials = new CSCCredential({
+ providerName,
+ credentialId,
+ pin,
+ authorizationContext,
+ });
+
+ // Create parameters for the job
+ const params = new PDFElectronicSealParams({
+ documentLevelPermission
+ certificateCredentials,
+ sealFieldOptions,
+ sealAppearanceOptions
+ });
+
+ // Creates a new job instance
+ const job = new PDFElectronicSealJob({
+ inputAsset: sourceFileAsset,
+ sealImageAsset,
+ params,
+ });
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: PDFElectronicSealResult
+ });
+ // 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 = "./sealedOutput.pdf";
+ 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 {
+ sourceFileReadStream?.destroy();
+ sealImageReadStream?.destroy();
+ }
+})();
```
## Next Steps
diff --git a/src/pages/overview/pdf-extract-api/gettingstarted.md b/src/pages/overview/pdf-extract-api/gettingstarted.md
index c8c64521e..8b0f20f5f 100644
--- a/src/pages/overview/pdf-extract-api/gettingstarted.md
+++ b/src/pages/overview/pdf-extract-api/gettingstarted.md
@@ -5,7 +5,7 @@ title: Getting Started | PDF Accessibility Auto-Tag API | Adobe PDF Services
# Getting Started
-PDF Accessibility Auto-Tag API assists in the process of improving accessibility in individual PDFs via auto-tagging, adding document structure tags to the PDF file that are used to read a document's text and presenting it in a way that makes sense to users using assistive technology. The API is accessible through SDKs which help you get up and running quickly. Once you've received your developer credential, download and set up one of the sample projects. After you're familiar with the APIs, leverage the samples in your own server-side code.
+The PDF Extract API provides modern cloud-based capabilities for automatically extracting contents from PDF. The API is accessible through SDKs which help you get up and running quickly. Once you've received your developer credential, download and set up one of the sample projects. After you're familiar with the APIs, leverage the samples in your own server-side code.
@@ -19,9 +19,9 @@ PDF Services API endpoints are authenticated endpoints. Getting an access token
1. **Get Credentials** Invoking PDF Services API requires an Adobe-provided credential. To get one, [click here](https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-services-api), and complete the workflow. Be sure to copy and save the credential values to a secure location.
2. **Retrieve Access Token** The PDF Services APIs require an access_token to authorize the request. Use the "Get AccessToken" API from the Postman Collection with your client_id, client_secret (mentioned in the pdfservices-api-credentials.json file downloaded in 1) to get the access_token OR directly use the below mentioned cURL to get the access_token.
-
+
-### Rest API
+### REST API
```javascript
curl --location 'https://pdf-services.adobe.io/token' \
@@ -472,7 +472,7 @@ After downloading the zip, you can run the samples in the zip directly by settin
Running any sample or custom code requires the following steps:
-1. Install [Node.js 14.0](https://nodejs.org/en/download/) or higher.
+1. Install [Node.js 18.0](https://nodejs.org/en/download/) or higher.
@@ -508,7 +508,7 @@ For security reasons you may wish to confirm the installer's authenticity. To do
3. Verify the hash in the downloaded file matches the value published here.
```
-sha512-QFwmKkeFTvZhHXrklJOUbjCx8V6FftBC+DAsMCy7Q9vy5sPXQtO47rjAt6R7nzzcA/uUPfuw4/gCFNh7yRKKRQ==
+sha512-rDe5Er+pss0RJWt+ZUTCRw2sS9mwiD7mqPj0k0YGLzDdm8uZeGx3D7q4OfVoCZKR7ESBn8DlzDekXQM4P4WqhA==
```
#### Logging
diff --git a/src/pages/overview/pdf-extract-api/howtos/extract-api.md b/src/pages/overview/pdf-extract-api/howtos/extract-api.md
index 9f103086a..c54cc08d4 100644
--- a/src/pages/overview/pdf-extract-api/howtos/extract-api.md
+++ b/src/pages/overview/pdf-extract-api/howtos/extract-api.md
@@ -143,7 +143,7 @@ schema](/extractJSONOutputSchema2.json)):
| Unknown error / failure | ERROR | Unable to extract content - Internal error. |
-## Rest API
+## REST API
See our public API Reference for [Extract PDF](../../../apis/#tag/Extract-PDF).
@@ -153,7 +153,7 @@ The sample below extracts text element information from a PDF document and retur
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -293,48 +293,74 @@ namespace ExtractTextInfoFromPDF
// Run the sample:
// node src/extractpdf/extract-text-info-from-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT).build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file.
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextInfoFromPDF.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT]
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextInfoFromPDF.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -379,10 +405,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -395,9 +421,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
"text"
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables
@@ -406,7 +429,7 @@ The sample below extracts text and table element information from a PDF document
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -547,51 +570,74 @@ namespace ExtractTextTableInfoFromPDF
// Run the sample:
// node src/extractpdf/extract-text-table-info-from-pdf.js
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file.
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableInfoFromPDF.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES]
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableInfoFromPDF.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -637,10 +683,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
-```javascript
-// Please refer our Rest API docs for more information
+```curl
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -654,9 +700,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
"tables"
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables (w/ Tables Renditions)
@@ -665,7 +708,7 @@ The sample below extracts text and table element information as well as table re
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -808,51 +851,76 @@ namespace ExtractTextTableInfoWithRenditionsFromPDF
// Run the sample:
// node src/extractpdf/extract-text-table-info-with-tables-renditions-from-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .addElementsToExtractRenditions(PDFServicesSdk.ExtractPDF.options.ExtractRenditionsElementType.TABLES)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableInfoWithTablesRenditionsFromPDF.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
-
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ ExtractRenditionsElementType,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES],
+ elementsToExtractRenditions: [ExtractRenditionsElementType.TABLES]
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableInfoWithRenditionsFromPDF.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -898,10 +966,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -918,9 +986,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
"tables"
],
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables (w/ Tables and Figures Renditions)
@@ -929,7 +994,7 @@ The sample below extracts text and table elements information as well as table a
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1072,50 +1137,76 @@ namespace ExtractTextTableInfoWithFiguresTablesRenditionsFromPDF
// Run the sample:
// node src/extractpdf/extract-text-table-info-with-figures-tables-renditions-from-pdf.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .addElementsToExtractRenditions(PDFServicesSdk.ExtractPDF.options.ExtractRenditionsElementType.FIGURES, PDFServicesSdk.ExtractPDF.options.ExtractRenditionsElementType.TABLES)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableWithFigureTableRendition.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ ExtractRenditionsElementType,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES],
+ elementsToExtractRenditions: [ExtractRenditionsElementType.FIGURES, ExtractRenditionsElementType.TABLES]
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableWithFigureTableRendition.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -1161,10 +1252,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -1182,9 +1273,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
"tables"
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables and Character Bounding Boxes (w/ Renditions)
@@ -1193,7 +1281,7 @@ The sample below extracts table renditions and bounding boxes for characters pre
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1336,50 +1424,75 @@ namespace ExtractTextTableInfoWithCharBoundsFromPDF
// Run the sample:
// node src/extractpdf/extract-text-table-info-with-char-bounds-from-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .addCharInfo(true)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file.
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableInfoWithCharBoundsFromPDF.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES],
+ addCharInfo: true
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableInfoWithCharBoundsFromPDF.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -1425,10 +1538,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -1447,9 +1560,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
],
"getCharBounds": true
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables and Table Structure as CSV (w/ Renditions)
@@ -1458,7 +1568,7 @@ The sample below adds option to get CSV output for tables in addition to extract
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1601,53 +1711,80 @@ namespace ExtractTextTableInfoWithTableStructureFromPDF
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/extractpdf/extract-text-table-info-with-tables-renditions-from-pdf.js
-
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
+// node src/extractpdf/extract-text-table-info-with-tables-structure-from-pdf.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ ExtractRenditionsElementType,
+ TableStructureType,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .addElementsToExtractRenditions(PDFServicesSdk.ExtractPDF.options.ExtractRenditionsElementType.TABLES)
- .addTableStructureFormat(PDFServicesSdk.ExtractPDF.options.TableStructureType.CSV)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file.
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableWithTableStructure.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES],
+ elementsToExtractRenditions: [ExtractRenditionsElementType.TABLES],
+ tableStructureType: TableStructureType.CSV
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableWithTableStructure.zip";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const writeStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(writeStream);
} catch (err) {
- console.log('Exception encountered while executing operation', 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();
}
+})();
```
#### Python
@@ -1694,10 +1831,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -1715,9 +1852,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
],
"tableOutputFormat": "csv"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
## Extract Text and Tables and Styling Info
@@ -1727,7 +1861,7 @@ schema](/extractJSONOutputSchemaStylingInfo.json) for reference.
Please refer the [API usage guide](./api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1870,51 +2004,75 @@ namespace ExtractTextTableInfoWithStylingFromPDF
// Run the sample:
// node src/extractpdf/extract-text-table-with-styling-info-from-pdf.js
-
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build extractPDF options
- const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT, PDFServicesSdk.ExtractPDF.options.ExtractElementType.TABLES)
- .getStylingInfo(true)
- .build();
-
- // Create a new operation instance.
- const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/extractPDFInput.pdf',
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
- // Set operation input from a source file.
- extractPDFOperation.setInput(input);
-
- // Set options
- extractPDFOperation.setOptions(options);
-
- extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ExtractTextTableInfoWithStylingInfoFromPDF.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./extractPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT, ExtractElementType.TABLES],
+ getStylingInfo: true,
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextTableInfoWithStylingInfoFromPDF.zip";
+ 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();
+ }
+})();
```
#### Python
@@ -1960,10 +2118,10 @@ except (ServiceApiException, ServiceUsageException, SdkException):
logging.exception("Exception encountered while executing operation")
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \
@@ -1978,7 +2136,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/extractp
],
"includeStyling": true
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
```
diff --git a/src/pages/overview/pdf-extract-api/howtos/index.md b/src/pages/overview/pdf-extract-api/howtos/index.md
index a13fa53b8..760226b0e 100644
--- a/src/pages/overview/pdf-extract-api/howtos/index.md
+++ b/src/pages/overview/pdf-extract-api/howtos/index.md
@@ -90,14 +90,8 @@ ClientConfig clientConfig = ClientConfig.ConfigBuilder()
Available properties:
-- **connectTimeout**: Default: 10000. The maximum allowed time in
- milliseconds for creating an initial HTTPS connection.
-- **readTimeout**: Default: 10000. The maximum allowed time in
- milliseconds between two successive HTTP response packets.
-- **processingTimeout**: Default: 600000. The maximum allowed time
- in milliseconds for processing the documents. Any operation taking more time than the specified `processingTimeout` will result in an operation timeout exception.
- - **Note :** It is advisable to set the `processingTimeout` to higher values for processing large files.
-
+- **timeout**: Default: 10000. The maximum allowed time in milliseconds before the request times out. If the request
+ takes longer than `timeout`, the request will be aborted.
Override the timeout properties via a custom `ClientConfig` class:
@@ -106,11 +100,9 @@ Override the timeout properties via a custom `ClientConfig` class:
###
```javascript
-const clientConfig = PDFServicesSdk.ClientConfig
- .clientConfigBuilder()
- .withConnectTimeout(15000)
- .withReadTimeout(15000)
- .build();
+const clientConfig = new ClientConfig({
+ timeout: 15000
+})
```
### Python timeout configuration
diff --git a/src/pages/overview/pdf-extract-api/quickstarts/nodejs/index.md b/src/pages/overview/pdf-extract-api/quickstarts/nodejs/index.md
index fd3fb0d88..3765d78e4 100644
--- a/src/pages/overview/pdf-extract-api/quickstarts/nodejs/index.md
+++ b/src/pages/overview/pdf-extract-api/quickstarts/nodejs/index.md
@@ -10,7 +10,7 @@ To get started using Adobe PDF Extract API, let's walk through a simple scenario
To complete this guide, you will need:
-* [Node.js](https://nodejs.org) - Node.js version 14.0 or higher is required.
+* [Node.js](https://nodejs.org) - 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.
@@ -65,27 +65,20 @@ Now you're ready to begin coding.
1) We'll begin by including our required dependencies:
```js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-const fs = require('fs');
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
const AdmZip = require('adm-zip');
```
-The first line includes the Adobe PDF Services Node.js SDK. The second third include Node's `filesystem` package as well as the package that will work with the ZIP file returned from the API.
-
-2) Now let's define our input and output:
-
-```js
-const OUTPUT_ZIP = './ExtractTextInfoFromPDF.zip';
-
-//Remove if the output already exists.
-if(fs.existsSync(OUTPUT_ZIP)) fs.unlinkSync(OUTPUT_ZIP);
-
-const INPUT_PDF = './Adobe Extract API Sample.pdf';
-```
-
-This defines what our output ZIP will be and optionally deletes it if it already exists. Then we define what PDF will be extracted. (You can download the source we used [here](/Adobe%20Extract%20API%20Sample.pdf).) In a real application, these values would be typically be dynamic.
-
-3) 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:
+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=`
- `set PDF_SERVICES_CLIENT_SECRET=`
@@ -94,70 +87,87 @@ This defines what our output ZIP will be and optionally deletes it if it already
- `export PDF_SERVICES_CLIENT_ID=`
- `export PDF_SERVICES_CLIENT_SECRET=`
-4) Next, we setup the SDK to use our credentials.
+3) Next, we setup the SDK to use our credentials.
```js
-const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
- .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
- .build();
-
-// Create an ExecutionContext using credentials
-const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
+// 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});
```
-This code both points to the credentials downloaded previously as well as sets up an execution context object that will be used later.
+4) Now, let's upload the asset:
-5) Now, let's create the operation:
+```js
+const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+});
+```
+We define what PDF will be extracted. (You can download the source we used [here](/Adobe%20Extract%20API%20Sample.pdf).) In a real application, these values would be typically be dynamic.
+5) Now, let's create the parameters and the job:
+
+```js
+// Create parameters for the job
+const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT]
+});
+
+// Creates a new job instance
+const job = new ExtractPDFJob({inputAsset, params});
+```
+
+This set of code defines what we're doing (an Extract operation),
+it defines parameters for the Extract job. PDF Extract API has a few different options, but in this example, we're simply asking for the most basic of extractions, the textual content of the document.
+
+6) The next code block submits the job and gets the job result:
```js
-// Create a new operation instance.
-const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- INPUT_PDF,
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
-// Build extractPDF options
-const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT).build()
-
-extractPDFOperation.setInput(input);
-extractPDFOperation.setOptions(options);
+// Submit the job and get the job result
+const pollingURL = await pdfServices.submit({job});
+const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+});
+
+// Get content from the resulting asset(s)
+const resultAsset = pdfServicesResponse.result.resource;
+const streamAsset = await pdfServices.getContent({asset: resultAsset});
```
-This set of code defines what we're doing (an Extract operation), points to our local file and specifies the input is a PDF, and then defines options for the Extract call. PDF Extract API has a few different options, but in this example, we're simply asking for the most basic of extractions, the textual content of the document.
+This code runs the Extraction process, gets the content of the result zip in stream asset.
-6) The next code block executes the operation:
+7) The next code block saves the result at the specified location:
```js
-// Execute the operation
-extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile(OUTPUT_ZIP))
- .then(() => {
- console.log('Successfully extracted information from PDF.');
- })
- .catch(err => console.log(err));
+// Creates a write stream and copy stream asset's content to it
+const outputFilePath = "./ExtractTextInfoFromPDF.zip";
+console.log(`Saving asset at ${outputFilePath}`);
+
+const writeStream = fs.createWriteStream(outputFilePath);
+streamAsset.readStream.pipe(writeStream);
```
-This code runs the Extraction process and then stores the result zip to the file system.
+Here's the complete application (`extract.js`):
-7) In this block, we read in the ZIP file, extract the JSON result file, and parse it:
+8) In this block, we read in the ZIP file, extract the JSON result file, and parse it:
```js
-let zip = new AdmZip(OUTPUT_ZIP);
+let zip = new AdmZip(outputFilePath);
let jsondata = zip.readAsText('structuredData.json');
let data = JSON.parse(jsondata);
```
-
-8) Finally we can loop over the result and print out any found element that is an `H1`:
+9) Finally, we can loop over the result and print out any found element that is an `H1`:
```js
data.elements.forEach(element => {
- if(element.Path.endsWith('/H1')) {
- console.log(element.Text);
- }
+ if(element.Path.endsWith('/H1')) {
+ console.log(element.Text);
+ }
});
```
@@ -166,57 +176,77 @@ data.elements.forEach(element => {
Here's the complete application (`extract.js`):
```js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-const fs = require('fs');
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExtractPDFParams,
+ ExtractElementType,
+ ExtractPDFJob,
+ ExtractPDFResult
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
const AdmZip = require('adm-zip');
-const OUTPUT_ZIP = './ExtractTextInfoFromPDF.zip';
-
-//Remove if the output already exists.
-if(fs.existsSync(OUTPUT_ZIP)) fs.unlinkSync(OUTPUT_ZIP);
-
-const INPUT_PDF = './Adobe Extract API Sample.pdf';
-
-const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
- .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
- .build();
-
-// Create an ExecutionContext using credentials
-const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
-// Create a new operation instance.
-const extractPDFOperation = PDFServicesSdk.ExtractPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- INPUT_PDF,
- PDFServicesSdk.ExtractPDF.SupportedSourceFormat.pdf
- );
-
-// Build extractPDF options
-const options = new PDFServicesSdk.ExtractPDF.options.ExtractPdfOptions.Builder()
- .addElementsToExtract(PDFServicesSdk.ExtractPDF.options.ExtractElementType.TEXT).build()
-
-
-extractPDFOperation.setInput(input);
-extractPDFOperation.setOptions(options);
-
-// Execute the operation
-extractPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile(OUTPUT_ZIP))
- .then(() => {
- console.log('Successfully extracted information from PDF. Printing H1 Headers:\n');
- let zip = new AdmZip(OUTPUT_ZIP);
- let jsondata = zip.readAsText('structuredData.json');
- let data = JSON.parse(jsondata);
- data.elements.forEach(element => {
- if(element.Path.endsWith('/H1')) {
- console.log(element.Text);
- }
- });
-
- })
- .catch(err => console.log(err));
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./Adobe Extract API Sample.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExtractPDFParams({
+ elementsToExtract: [ExtractElementType.TEXT]
+ });
+
+ // Creates a new job instance
+ const job = new ExtractPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExtractPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.resource;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates a write stream and copy stream asset's content to it
+ const outputFilePath = "./ExtractTextInfoFromPDF.zip";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const writeStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(writeStream);
+
+ let zip = new AdmZip(outputFilePath);
+ let jsondata = zip.readAsText('structuredData.json');
+ let data = JSON.parse(jsondata);
+ data.elements.forEach(element => {
+ if(element.Path.endsWith('/H1')) {
+ console.log(element.Text);
+ }
+ });
+ } catch (err) {
+ console.log("Exception encountered while executing operation", err);
+ } finally {
+ readStream?.destroy();
+ }
+})();
```
## Next Steps
diff --git a/src/pages/overview/pdf-extract-api/quickstarts/nodejs/shot9.png b/src/pages/overview/pdf-extract-api/quickstarts/nodejs/shot9.png
index b09d4ce9f..0eb77ef8e 100644
Binary files a/src/pages/overview/pdf-extract-api/quickstarts/nodejs/shot9.png and b/src/pages/overview/pdf-extract-api/quickstarts/nodejs/shot9.png differ
diff --git a/src/pages/overview/pdf-services-api/gettingstarted.md b/src/pages/overview/pdf-services-api/gettingstarted.md
index 64ca1461b..c587ecf3b 100644
--- a/src/pages/overview/pdf-services-api/gettingstarted.md
+++ b/src/pages/overview/pdf-services-api/gettingstarted.md
@@ -17,9 +17,9 @@ PDF Services API endpoints are authenticated endpoints. Getting an access token
1. **Get Credentials** Invoking PDF Services API requires an Adobe-provided credential. To get one, [click here](https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-services-api), and complete the workflow. Be sure to copy and save the credential values to a secure location.
2. **Retrieve Access Token** The PDF Services APIs require an access_token to authorize the request. Use the "Get AccessToken" API from the Postman Collection with your client_id, client_secret (mentioned in the pdfservices-api-credentials.json file downloaded in 1) to get the access_token OR directly use the below mentioned cURL to get the access_token.
-
+
-### Rest API
+### REST API
```javascript
curl --location 'https://pdf-services.adobe.io/token' \
@@ -37,9 +37,9 @@ After getting the access token, we need to upload the asset. Uploading an asset
You can read more about the API in detail [here](../../../apis/#operation/asset.uploadpresignedurl).
-
+
-### Rest API
+### REST API
```javascript
curl --location --request POST 'https://pdf-services.adobe.io/assets' \
@@ -53,9 +53,9 @@ curl --location --request POST 'https://pdf-services.adobe.io/assets' \
2. On getting a `200` response status from the above API, use the `uploadUri` field in the response body of the above API to upload the asset directly to the cloud provider using a PUT API call. You will also get an `assetID` field which will be used in creating the job.
-
+
-### Rest API
+### REST API
```javascript
curl --location -g --request PUT 'https://dcplatformstorageservice-prod-us-east-1.s3-accelerate.amazonaws.com/b37fd583-1ab6-4f49-99ef-d716180b5de4?X-Amz-Security-Token={{Placeholder for X-Amz-Security-Token}}&X-Amz-Algorithm={{Placeholder for X-Amz-Algorithm}}&X-Amz-Date={{Placeholder for X-Amz-Date}}&X-Amz-SignedHeaders={{Placeholder for X-Amz-SignedHeaders}}&X-Amz-Expires={{Placeholder for X-Amz-Expires}}&X-Amz-Credential={{Placeholder for X-Amz-Credential}}&X-Amz-Signature={{Placeholder for X-Amz-Signature}}' \
@@ -75,9 +75,9 @@ Once the job is successfully created, you need to poll the at the `location` ret
You can read more about the API in detail [here](../../../apis/#operation/pdfoperations.compresspdf.jobstatus).
-
+
-### Rest API
+### REST API
```javascript
curl --location -g --request GET 'https://pdf-services.adobe.io/operation/compresspdf/{{Placeholder for job id}}/status' \
@@ -100,9 +100,9 @@ If the `status` field is `done` the response body will also have a download pre-
You can read more about the API in detail [here](../../../apis/#operation/asset.get).
-
+
-### Rest API
+### REST API
```javascript
curl --location -g --request GET 'https://dcplatformstorageservice-prod-us-east-1.s3-accelerate.amazonaws.com/b37fd583-1ab6-4f49-99ef-d716180b5de4?X-Amz-Security-Token={{Placeholder for X-Amz-Security-Token}}&X-Amz-Algorithm={{Placeholder for X-Amz-Algorithm}}&X-Amz-Date={{Placeholder for X-Amz-Date}}&X-Amz-SignedHeaders={{Placeholder for X-Amz-SignedHeaders}}&X-Amz-Expires={{Placeholder for X-Amz-Expires}}&X-Amz-Credential={{Placeholder for X-Amz-Credential}}&X-Amz-Signature={{Placeholder for X-Amz-Signature}}'
@@ -471,7 +471,7 @@ After downloading the zip, you can run the samples in the zip directly by settin
Running any sample or custom code requires the following steps:
-1. Install [Node.js 14.0](https://nodejs.org/en/download/) or higher.
+1. Install [Node.js 18.0](https://nodejs.org/en/download/) or higher.
@@ -507,7 +507,7 @@ For security reasons you may wish to confirm the installer's authenticity. To do
3. Verify the hash in the downloaded file matches the value published here.
```
-sha512-QFwmKkeFTvZhHXrklJOUbjCx8V6FftBC+DAsMCy7Q9vy5sPXQtO47rjAt6R7nzzcA/uUPfuw4/gCFNh7yRKKRQ==
+sha512-rDe5Er+pss0RJWt+ZUTCRw2sS9mwiD7mqPj0k0YGLzDdm8uZeGx3D7q4OfVoCZKR7ESBn8DlzDekXQM4P4WqhA==
```
#### Logging
diff --git a/src/pages/overview/pdf-services-api/howtos/combine-pdf.md b/src/pages/overview/pdf-services-api/howtos/combine-pdf.md
index 42d3e9dd4..5e36fec5c 100644
--- a/src/pages/overview/pdf-services-api/howtos/combine-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/combine-pdf.md
@@ -5,7 +5,7 @@ title: Combine PDF | How Tos | PDF Services API | Adobe PDF Services
Combine two or more documents into a single PDF file
-## Rest API
+## REST API
See our public API Reference for [Combine PDF](../../../apis/#tag/Combine-PDF)
@@ -15,7 +15,7 @@ This sample combines up to 20 PDF files into a single PDF file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -142,46 +142,87 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/combinepdf/combine-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- combineFilesOperation = PDFServicesSdk.CombineFiles.Operation.createNew();
-
- // Set operation input from a source file.
- const combineSource1 = PDFServicesSdk.FileRef.createFromLocalFile('resources/combineFilesInput1.pdf'),
- combineSource2 = PDFServicesSdk.FileRef.createFromLocalFile('resources/combineFilesInput2.pdf');
- combineFilesOperation.addInput(combineSource1);
- combineFilesOperation.addInput(combineSource2);
-
- // Execute the operation and Save the result to the specified location.
- combineFilesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/combineFilesOutput.pdf'))
- .catch(err => {
- if (err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CombinePDFJob,
+ CombinePDFParams,
+ CombinePDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream1;
+ let readStream2;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream1 = fs.createReadStream("./combineFilesInput1.pdf");
+ readStream2 = fs.createReadStream("./combineFilesInput2.pdf");
+ const [inputAsset1, inputAsset2] = await pdfServices.uploadAssets({
+ streamAssets: [{
+ readStream: readStream1,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: readStream2,
+ mimeType: MimeType.PDF
+ }]
+ });
+
+ // Create parameters for the job
+ const params = new CombinePDFParams()
+ .addAsset(inputAsset1)
+ .addAsset(inputAsset2);
+
+ // Create a new job instance
+ const job = new CombinePDFJob({params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CombinePDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./combineFilesOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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 {
+ readStream1?.destroy();
+ readStream2?.destroy();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \
@@ -198,9 +239,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/combinep
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
```
## Combine pages from multiple files
@@ -211,7 +249,7 @@ ranges for each file to combine in the output file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -390,72 +428,108 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/combinepdf/combine-pdf-with-page-ranges.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getPageRangesForFirstFile = () => {
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CombinePDFParams,
+ CombinePDFJob,
+ CombinePDFResult,
+ PageRanges,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream1;
+ let readStream2;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream1 = fs.createReadStream("./combineFilesInput1.pdf");
+ readStream2 = fs.createReadStream("./combineFilesInput2.pdf");
+ const [inputAsset1, inputAsset2] = await pdfServices.uploadAssets({
+ streamAssets: [{
+ readStream: readStream1,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: readStream2,
+ mimeType: MimeType.PDF
+ }]
+ });
+
+ // Create a CombinePDFParams instance
+ const params = new CombinePDFParams()
+ .addAsset(inputAsset1, getPageRangesForFirstFile())
+ .addAsset(inputAsset2, getPageRangesForSecondFile());
+
+ // Create a new job instance
+ const job = new CombinePDFJob({params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CombinePDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./combineFilesOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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 {
+ readStream1?.destroy();
+ readStream2?.destroy();
+ }
+})();
+
+const getPageRangesForFirstFile = () => {
// Specify which pages of the first file are to be included in the combined file.
- const pageRangesForFirstFile = new PDFServicesSdk.PageRanges();
+ const pageRangesForFirstFile = new PageRanges();
// Add page 1.
pageRangesForFirstFile.addSinglePage(1);
// Add page 2.
pageRangesForFirstFile.addSinglePage(2);
// Add pages 3 to 4.
- pageRangesForFirstFile.addPageRange(3, 4);
+ pageRangesForFirstFile.addRange(3, 4);
return pageRangesForFirstFile;
- };
-
- const getPageRangesForSecondFile = () => {
+};
+
+const getPageRangesForSecondFile = () => {
// Specify which pages of the second file are to be included in the combined file.
- const pageRangesForSecondFile = new PDFServicesSdk.PageRanges();
+ const pageRangesForSecondFile = new PageRanges();
// Add all pages including and after page 3.
pageRangesForSecondFile.addAllFrom(3);
return pageRangesForSecondFile;
- };
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- combineFilesOperation = PDFServicesSdk.CombineFiles.Operation.createNew();
-
- // Create a FileRef instance from a local file.
- const combineSource1 = PDFServicesSdk.FileRef.createFromLocalFile('resources/combineFilesInput1.pdf'),
- pageRangesForFirstFile = getPageRangesForFirstFile();
- // Add the first file as input to the operation, along with its page range.
- combineFilesOperation.addInput(combineSource1, pageRangesForFirstFile);
-
- // Create a second FileRef instance using a local file.
- const combineSource2 = PDFServicesSdk.FileRef.createFromLocalFile('resources/combineFilesInput2.pdf'),
- pageRangesForSecondFile = getPageRangesForSecondFile();
- // Add the second file as input to the operation, along with its page range.
- combineFilesOperation.addInput(combineSource2, pageRangesForSecondFile);
-
- // Execute the operation and Save the result to the specified location.
- combineFilesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/combineFilesWithPageRangesOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+};
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \
@@ -484,7 +558,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/combinep
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/compress-pdf.md b/src/pages/overview/pdf-services-api/howtos/compress-pdf.md
index 5b4e433dc..d2d79c042 100644
--- a/src/pages/overview/pdf-services-api/howtos/compress-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/compress-pdf.md
@@ -7,7 +7,7 @@ Reduce the size of PDF files by compressing to smaller sizes for lower bandwidth
Support for multiple compression levels to retain the quality of images and graphics
-## Rest API
+## REST API
See our public API Reference for [Compress PDF](../../../apis/#tag/Compress-PDF)
@@ -18,7 +18,7 @@ operations that use bandwidth or memory.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -131,45 +131,73 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/compresspdf/compress-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- compressPDF = PDFServicesSdk.CompressPDF,
- compressPDFOperation = compressPDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/compressPDFInput.pdf');
- compressPDFOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- compressPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/compressPDFOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CompressPDFJob,
+ CompressPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./compressPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Creates a new job instance
+ const job = new CompressPDFJob({inputAsset});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CompressPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./compressPDFOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \
@@ -180,8 +208,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/compress
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-compressPDF
```
## Compress PDFs with Compression Level
@@ -193,7 +219,7 @@ list of supported compression levels.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -318,51 +344,80 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/compresspdf/compress-pdf-with-options.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- compressPDF = PDFServicesSdk.CompressPDF,
- compressPDFOperation = compressPDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/compressPDFInput.pdf');
- compressPDFOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- const options = new compressPDF.options.CompressPDFOptions.Builder()
- .withCompressionLevel(PDFServicesSdk.CompressPDF.options.CompressionLevel.MEDIUM)
- .build();
- compressPDFOperation.setOptions(options);
-
- // Execute the operation and Save the result to the specified location.
- compressPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/compressPDFWithOptionsOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CompressPDFJob,
+ CompressPDFParams,
+ CompressionLevel,
+ CompressPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./compressPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Set the compression level
+ const params = new CompressPDFParams({
+ compressionLevel: CompressionLevel.LOW,
+ });
+
+ // Creates a new job instance
+ const job = new CompressPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CompressPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = createOutputFilePath();
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = "./compressPDFWithOptionsOutput.pdf";
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \
@@ -373,7 +428,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/compress
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",
"compressionLevel": "MEDIUM"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-compressPDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/create-pdf.md b/src/pages/overview/pdf-services-api/howtos/create-pdf.md
index f869e3eaf..d10828bc4 100644
--- a/src/pages/overview/pdf-services-api/howtos/create-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/create-pdf.md
@@ -5,7 +5,7 @@ title: Create PDF | How Tos | PDF Services API | Adobe PDF Services
Create PDFs from a variety of formats, including static and dynamic HTML; Microsoft Word, PowerPoint, and Excel; as well as text, image, Zip, and URL. Support for HTML to PDF, DOC to PDF, DOCX to PDF, PPT to PDF, PPTX to PDF, XLS to PDF, XLSX to PDF, TXT to PDF, RTF to PDF, BMP to PDF, JPEG to PDF, GIF to PDF, TIFF to PDF, PNG to PDF
-## Rest API
+## REST API
See our public API Reference for :
- [Create PDF from Office formats](../../../apis/#tag/Create-PDF)
@@ -32,7 +32,7 @@ For more information, refer [Benefits of embedding custom fonts](https://support
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -146,44 +146,73 @@ namespace CreatePDFFromDocx
// Run the sample:
// node src/createpdf/create-pdf-from-docx.js
-const PDFservicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- createPdfOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/createPDFInput.docx');
- createPdfOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- createPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPDFFromDOCX.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CreatePDFJob,
+ CreatePDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./createPDFInput.docx");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.DOCX
+ });
+
+ // Creates a new job instance
+ const job = new CreatePDFJob({inputAsset});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CreatePDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./createPDFFromDOCX.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \
@@ -193,9 +222,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/createpd
--data-raw '{
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-createPDF
```
## Create PDF with DocumentLanguage
@@ -212,7 +238,7 @@ file, the SDK supports the following formats:
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -347,57 +373,80 @@ namespace CreatePDFFromDocxWithOptions
// Run the sample:
// node src/createpdf/create-pdf-from-docx-with-options.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-const setCustomOptions = (createPdfOperation) => {
- // Select the documentLanguage for input file.
- const documentLanguage = PDFServicesSdk.CreatePDF.options.word.SupportedDocumentLanguage.EN_US;
-
- // Set the desired WORD-to-PDF conversion options with documentLanguage.
- const createPdfOptions = new PDFServicesSdk.CreatePDF.options.word.CreatePDFFromWordOptions.Builder()
- .withDocumentLanguage(documentLanguage).build();
- createPdfOperation.setOptions(createPdfOptions);
-};
-
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- createPdfOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/createPDFInput.docx');
- createPdfOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- setCustomOptions(createPdfOperation);
-
- // Execute the operation and Save the result to the specified location.
- createPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPDFFromDOCXWithOptionsOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ CreatePDFJob,
+ CreatePDFParams,
+ CreatePDFResult,
+ DocumentLanguage,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./createPDFInput.docx");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.DOCX
+ });
+
+ // Create parameters for the job
+ const params = new CreatePDFParams({
+ documentLanguage: DocumentLanguage.EN_US
+ });
+
+ // Creates a new job instance
+ const job = new CreatePDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: CreatePDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./createPDFFromDOCXWithOptionsOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \
@@ -408,9 +457,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/createpd
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",
"documentLanguage": "en-US"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-createPDF
```
## Create a PDF from static HTML
@@ -423,7 +469,7 @@ files, and so on.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -565,63 +611,93 @@ namespace CreatePDFFromStaticHtml
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/createpdf/create-pdf-from-static-html.js
-
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const setCustomOptions = (htmlToPDFOperation) => {
- // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).
- const pageLayout = new PDFServicesSdk.CreatePDF.options.html.PageLayout();
- pageLayout.setPageSize(8, 11.5);
-
- // Set the desired HTML-to-PDF conversion options.
- const htmlToPdfOptions = new PDFServicesSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder()
- .includesHeaderFooter(true)
- .withPageLayout(pageLayout)
- .build();
- htmlToPDFOperation.setOptions(htmlToPdfOptions);
- };
-
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- htmlToPDFOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/createPDFFromStaticHtmlInput.zip');
- htmlToPDFOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- setCustomOptions(htmlToPDFOperation);
-
- // Execute the operation and Save the result to the specified location.
- htmlToPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPdfFromStaticHtmlOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/htmltopdf/static-html-to-pdf.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageLayout,
+ HTMLToPDFParams,
+ HTMLToPDFResult,
+ HTMLToPDFJob,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./createPDFFromStaticHtmlInput.zip");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.ZIP
+ });
+
+ // Create parameters for the job
+ const params = getHTMLToPDFParams();
+
+ // Creates a new job instance
+ const job = new HTMLToPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: HTMLToPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "createPdfFromStaticHtmlOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
+
+function getHTMLToPDFParams() {
+ // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)
+ const pageLayout = new PageLayout({
+ pageHeight: 11.5,
+ pageWidth: 8
+ });
+
+ return new HTMLToPDFParams({
+ pageLayout,
+ includeHeaderFooter: true,
+ });
+}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \
@@ -637,9 +713,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopd
"pageHeight": 8.5
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
```
## Create a PDF from static HTML with inline CSS
@@ -648,7 +721,7 @@ The sample below creates a PDF file from a static HTML file with inline CSS. The
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -790,63 +863,93 @@ namespace CreatePDFFromHTMLWithInlineCSS
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/create-pdf-from-html-with-inline-css.js
-
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-const setCustomOptions = (htmlToPDFOperation) => {
- // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation).
- const pageLayout = new PDFServicesSdk.CreatePDF.options.html.PageLayout();
- pageLayout.setPageSize(20, 25);
-
- // Set the desired HTML-to-PDF conversion options.
- const htmlToPdfOptions = new PDFServicesSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder()
- .includesHeaderFooter(true)
- .withPageLayout(pageLayout)
- .build();
- htmlToPDFOperation.setOptions(htmlToPdfOptions);
-};
-
-
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- htmlToPDFOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/createPDFFromHTMLWithInlineCSSInput.html');
- htmlToPDFOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- setCustomOptions(htmlToPDFOperation);
-
- // Execute the operation and Save the result to the specified location.
- htmlToPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPDFFromHTMLWithInlineCSSOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/htmltopdf/html-with-inline-css-to-pdf.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ HTMLToPDFJob,
+ HTMLToPDFResult,
+ PageLayout,
+ HTMLToPDFParams,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./createPDFFromHTMLWithInlineCSSInput.html");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.HTML
+ });
+
+ // Create parameters for the job
+ const params = getHTMLToPDFParams();
+
+ // Creates a new job instance
+ const job = new HTMLToPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: HTMLToPDFResult
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./createPDFFromHTMLWithInlineCSSOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
+
+function getHTMLToPDFParams() {
+ // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation)
+ const pageLayout = new PageLayout({
+ pageHeight: 25,
+ pageWidth: 20
+ });
+
+ return new HTMLToPDFParams({
+ pageLayout,
+ includeHeaderFooter: true,
+ });
}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \
@@ -862,9 +965,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopd
"pageHeight": 8.5
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
```
## Create a PDF File From HTML specified via URL
@@ -873,7 +973,7 @@ The sample below creates a PDF file from a HTML file specified via URL.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1014,64 +1114,84 @@ namespace CreatePDFFromURL
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/create-pdf-from-url.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-const setCustomOptions = (htmlToPDFOperation) => {
- // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation).
- const pageLayout = new PDFServicesSdk.CreatePDF.options.html.PageLayout();
- pageLayout.setPageSize(20, 25);
-
- // Set the desired HTML-to-PDF conversion options.
- const htmlToPdfOptions = new PDFServicesSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder()
- .includesHeaderFooter(true)
- .withPageLayout(pageLayout)
- .build();
- htmlToPDFOperation.setOptions(htmlToPdfOptions);
-};
-
-
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- htmlToPDFOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromURL(
- "https://www.adobe.io"
- );
- htmlToPDFOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- setCustomOptions(htmlToPDFOperation);
-
- // Execute the operation and Save the result to the specified location.
- htmlToPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPdfFromURLOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/htmltopdf/html-to-pdf-from-url.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ PageLayout,
+ HTMLToPDFParams,
+ HTMLToPDFResult,
+ HTMLToPDFJob,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ try {
+ // 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});
+
+ const inputURL = "";
+
+ // Create parameters for the job
+ const params = getHTMLToPDFParams();
+
+ // Creates a new job instance
+ const job = new HTMLToPDFJob({inputURL, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: HTMLToPDFResult
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./createPDFFromHTMLURL.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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);
+ }
+ }
+})();
+
+function getHTMLToPDFParams() {
+ // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)
+ const pageLayout = new PageLayout({
+ pageHeight: 11.5,
+ pageWidth: 8
+ });
+
+ return new HTMLToPDFParams({
+ includeHeaderFooter: true,
+ pageLayout
+ });
}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \
@@ -1087,9 +1207,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopd
"pageHeight": 8.5
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
```
## Create a PDF from dynamic HTML
@@ -1111,7 +1228,7 @@ dynamically prior to PDF conversion.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -1266,68 +1383,100 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/createpdf/create-pdf-from-dynamic-html.js
-
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const setCustomOptions = (htmlToPDFOperation) => {
- // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).
- const pageLayout = new PDFServicesSdk.CreatePDF.options.html.PageLayout();
- pageLayout.setPageSize(8, 11.5);
- //Set the dataToMerge field that needs to be populated in the HTML before its conversion.
- const dataToMerge = {
- "title":"Create, Convert PDFs and More!",
- "sub_title": "Easily integrate PDF actions within your document workflows."
- };
- // Set the desired HTML-to-PDF conversion options.
- const htmlToPdfOptions = new PDFServicesSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder()
- .includesHeaderFooter(true)
- .withPageLayout(pageLayout)
- .withDataToMerge(dataToMerge)
- .build();
- htmlToPDFOperation.setOptions(htmlToPdfOptions);
- };
-
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- htmlToPDFOperation = PDFServicesSdk.CreatePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/createPDFFromDynamicHtmlInput.zip');
- htmlToPDFOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- setCustomOptions(htmlToPDFOperation);
-
- // Execute the operation and Save the result to the specified location.
- htmlToPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/createPdfFromDynamicHtmlOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/htmltopdf/dynamic-html-to-pdf.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageLayout,
+ HTMLToPDFParams,
+ HTMLToPDFResult,
+ HTMLToPDFJob,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./createPDFFromDynamicHtmlInput.zip");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.ZIP
+ });
+
+ // Create parameters for the job
+ const params = getHTMLToPDFParams();
+
+ // Creates a new job instance
+ const job = new HTMLToPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: HTMLToPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./createPDFFromDynamicHtmlOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
+
+function getHTMLToPDFParams() {
+ // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)
+ const pageLayout = new PageLayout({
+ pageHeight: 11.5,
+ pageWidth: 8
+ });
+
+ // Set the dataToMerge field that needs to be populated in the HTML before its conversion
+ const dataToMerge = {
+ "title": "Create, Convert PDFs and More!",
+ "sub_title": "Easily integrate PDF actions within your document workflows."
+ };
+
+ return new HTMLToPDFParams({
+ pageLayout,
+ dataToMerge,
+ includeHeaderFooter: true,
+ });
+}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \
@@ -1343,7 +1492,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopd
"pageHeight": 8.5
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/delete-pages.md b/src/pages/overview/pdf-services-api/howtos/delete-pages.md
index e01d256ad..898941c9f 100644
--- a/src/pages/overview/pdf-services-api/howtos/delete-pages.md
+++ b/src/pages/overview/pdf-services-api/howtos/delete-pages.md
@@ -5,7 +5,7 @@ title: Delete Pages | How Tos | PDF Services API | Adobe PDF Services
Delete one or more pages from a document
-## Rest API
+## REST API
See our public API Reference for [Delete Pages](../../../apis/#tag/Page-Manipulation)
@@ -15,7 +15,7 @@ The delete pages operation selectively removes pages from a PDF file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -162,61 +162,95 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/replacepages/replace-pdf-pages.js
-
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getPageRangesForDeletion = () => {
- // Specify pages for deletion.
- const pageRangesForDeletion = new PDFServicesSdk.PageRanges();
- // Add page 1.
- pageRangesForDeletion.addSinglePage(1);
-
- // Add pages 3 to 4.
- pageRangesForDeletion.addPageRange(3, 4);
- return pageRangesForDeletion;
- };
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- deletePagesOperation = PDFServicesSdk.DeletePages.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/deletePagesInput.pdf');
- deletePagesOperation.setInput(input);
-
- // Delete pages of the document (as specified by PageRanges).
- const pageRangesForDeletion = getPageRangesForDeletion();
- deletePagesOperation.setPageRanges(pageRangesForDeletion);
-
- // Execute the operation and Save the result to the specified location.
- deletePagesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/deletePagesOutput.pdf'))
- .catch(err => {
- if (err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/deletepages/delete-pdf-pages.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ DeletePagesParams,
+ PageRanges,
+ DeletePagesJob,
+ DeletePagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./deletePagesInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Delete pages of the document (as specified by PageRanges).
+ const pageRangeForDeletion = getPageRangesForDeletion();
+
+ // Create parameters for the job
+ const params = new DeletePagesParams({
+ pageRanges: pageRangeForDeletion
+ });
+
+ // Creates a new job instance
+ const job = new DeletePagesJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: DeletePagesResult
+ });
+
+ // 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 = "./deletePagesOutput.pdf";
+ 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();
+ }
+})();
+
+const getPageRangesForDeletion = () => {
+ // Specify pages for deletion.
+ const pageRangesForDeletion = new PageRanges();
+ // Add page 1.
+ pageRangesForDeletion.addSinglePage(1);
+ // Add pages 3 to 4.
+ pageRangesForDeletion.addRange(3, 4);
+ return pageRangesForDeletion;
+};
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulation
curl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \
@@ -238,7 +272,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/pagemani
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
```
diff --git a/src/pages/overview/pdf-services-api/howtos/export-pdf.md b/src/pages/overview/pdf-services-api/howtos/export-pdf.md
index e1c2be7a1..e0100fd40 100644
--- a/src/pages/overview/pdf-services-api/howtos/export-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/export-pdf.md
@@ -5,7 +5,7 @@ title: Export PDF | How Tos | PDF Services API | Adobe PDF Services
Export a source PDF file into doc, docx, jpeg, png, pptx, rtf, xlsx.
-## Rest API
+## REST API
See our public API Reference for :
- [Export PDF to Office format or text files](../../../apis/#tag/Export-PDF)
@@ -22,7 +22,7 @@ such as:
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -140,45 +140,80 @@ public class ExportPDFToDOCX {
// Run the sample:
// node src/exportpdf/export-pdf-to-docx.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- //Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- exportPDF = PDFServicesSdk.ExportPDF,
- exportPdfOperation = exportPDF.Operation.createNew(exportPDF.SupportedTargetFormats.DOCX);
-
- // Set operation input from a source file
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/exportPDFInput.pdf');
- exportPdfOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- exportPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/exportPdfOutput.docx'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFJob,
+ ExportPDFParams,
+ ExportPDFTargetFormat,
+ ExportPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./exportPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExportPDFParams({
+ targetFormat: ExportPDFTargetFormat.DOCX
+ });
+
+ // Creates a new job instance
+ const job = new ExportPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./exportPDFToDOCXOutput.docx";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Export-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/exportpdf' \
@@ -189,9 +224,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/exportpd
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",
"targetFormat": "docx"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-exportPDF
```
## Export a PDF file to a DOCX file (apply OCR on the PDF file)
@@ -207,7 +239,7 @@ OCR processing is also performed on the input PDF file to extract text from imag
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -329,49 +361,80 @@ public class ExportPDFToDOCXWithOCROption {
// Run the sample:
// node src/exportpdf/export-docx-to-pdf-with-ocr-options.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- //Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- exportPDF = PDFServicesSdk.ExportPDF,
- exportPdfOperation = exportPDF.Operation.createNew(exportPDF.SupportedTargetFormats.DOCX);
-
- // Set operation input from a source file
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/exportPDFInput.pdf');
- exportPdfOperation.setInput(input);
-
- // Create a new ExportPDFOptions instance from the specified OCR locale and set it into the operation.
- const options = new exportPDF.options.ExportPDFOptions(exportPDF.options.ExportPDFOptions.OCRSupportedLocale.EN_US);
- exportPdfOperation.setOptions(options);
-
- // Execute the operation and Save the result to the specified location.
- exportPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/exportPdfWithOCROptionsOutput.docx'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFParams,
+ ExportPDFTargetFormat,
+ ExportOCRLocale,
+ ExportPDFJob,
+ ExportPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./exportPDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExportPDFParams({
+ targetFormat: ExportPDFTargetFormat.DOCX,
+ ocrLocale: ExportOCRLocale.EN_US
+ });
+
+ // Creates a new job instance
+ const job = new ExportPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./ExportPDFToDOCXWithOCROption.docx";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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);
+ }
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Export-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/exportpdf' \
@@ -383,9 +446,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/exportpd
"targetFormat": "docx",
"ocrLang": "en-US"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-exportPDF
```
## Export a PDF to images
@@ -397,7 +457,7 @@ pages will generate 15 image files. The first file's name ends with
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -525,51 +585,85 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/exportpdftoimages/export-pdf-to-jpeg.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- exportPDFToImages = PDFServicesSdk.ExportPDFToImages,
- exportPDFToImagesOperation = exportPDFToImages.Operation.createNew(exportPDFToImages.SupportedTargetFormats.JPEG);
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/exportPDFToImageInput.pdf');
- exportPDFToImagesOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- exportPDFToImagesOperation.execute(executionContext)
- .then(result => {
- let saveFilesPromises = [];
- for(let i = 0; i < result.length; i++){
- saveFilesPromises.push(result[i].saveAsFile(`output/exportPDFToImagesOutput_${i}.jpeg`));
- }
- return Promise.all(saveFilesPromises);
- })
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFToImagesJob,
+ ExportPDFToImagesTargetFormat,
+ ExportPDFToImagesOutputType,
+ ExportPDFToImagesParams,
+ ExportPDFToImagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./exportPDFToImageInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExportPDFToImagesParams({
+ targetFormat: ExportPDFToImagesTargetFormat.JPEG,
+ outputType: ExportPDFToImagesOutputType.LIST_OF_PAGE_IMAGES
+ });
+
+ // Creates a new job instance
+ const job = new ExportPDFToImagesJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFToImagesResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAssets = pdfServicesResponse.result.assets;
+
+ for (let i = 0; i < resultAssets.length; i++) {
+ const _outputFilePath = "./exportPDFToImageOutput_${i}.jpeg";
+ console.log(`Saving asset at ${_outputFilePath}`);
+
+ const streamAsset = await pdfServices.getContent({asset: resultAssets[i]});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputStream = fs.createWriteStream(_outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ }
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-To-Images
curl --location --request POST 'https://pdf-services.adobe.io/operation/pdftoimages' \
@@ -581,9 +675,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/pdftoima
"targetFormat": "jpeg",
"outputType": "listOfPageImages"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-exportPDF
```
## Export a PDF to zip of page images
@@ -592,7 +683,7 @@ The sample below converts a PDF file to one or more jpeg or png images. The resu
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -713,48 +804,82 @@ namespace
// Run the sample:
// node src/exportpdftoimages/export-pdf-to-jpeg-zip.js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- //Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- exportPDF = PDFServicesSdk.ExportPDF,
- exportPdfToImagesOperation = exportPDFToImages.Operation.createNew(exportPDFToImages.SupportedTargetFormats.JPEG);
-
- // Set the output type to create zip of images.
- exportPDFToImagesOperation.setOutputType(exportPDFToImages.OutputType.ZIP_OF_PAGE_IMAGES);
-
- // Set operation input from a source file
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/exportPDFToImageInput.pdf');
- exportPdfToImagesOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- exportPdfToImagesOperation.execute(executionContext)
- .then(result => result[0].saveAsFile('output/exportPDFToJPEG.zip'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFToImagesParams,
+ ExportPDFToImagesTargetFormat,
+ ExportPDFToImagesOutputType,
+ ExportPDFToImagesJob,
+ ExportPDFToImagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./exportPDFToImageInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExportPDFToImagesParams({
+ targetFormat: ExportPDFToImagesTargetFormat.JPEG,
+ outputType: ExportPDFToImagesOutputType.ZIP_OF_PAGE_IMAGES
+ });
+
+ // Creates a new job instance
+ const job = new ExportPDFToImagesJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFToImagesResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.assets;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset[0]});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./exportPDFToJPEGOutput.zip";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-To-Images
curl --location --request POST 'https://pdf-services.adobe.io/operation/pdftoimages' \
@@ -766,7 +891,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/pdftoima
"targetFormat": "jpeg",
"outputType": "zipOfPageImages"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-exportPDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/index.md b/src/pages/overview/pdf-services-api/howtos/index.md
index 578fbe730..298a5511f 100644
--- a/src/pages/overview/pdf-services-api/howtos/index.md
+++ b/src/pages/overview/pdf-services-api/howtos/index.md
@@ -72,11 +72,11 @@ ClientConfig clientConfig = ClientConfig.ConfigBuilder()
### Node.js
```javascript
-const clientConfig = PDFServicesSdk.ClientConfig
- .clientConfigBuilder()
- .setRegion(Region.EU)
- .build();
+const clientConfig = new ClientConfig({
+ region: Region.EU
+});
```
+
### Python
```javascript
@@ -87,12 +87,13 @@ client_config = ClientConfig.builder()
## Proxy Server Configuration
-The Java SDK enables connection to API calls through Proxy via Client Configurations.
+The Java and Node SDK enables connection to API calls through Proxy via Client Configurations.
Also, it supports username and password based authentication for the proxy server.
It allows the clients to use SDK within the network where all outgoing calls have to
go through a proxy and are allowed only if allow-listed on the proxy. Please refer to the
following sample for details.
+### Java
- [Java Sample for Proxy Server Config](https://github.com/adobe/pdfservices-java-sdk-samples/blob/master/src/main/java/com/adobe/pdfservices/operation/samples/customconfigurations/CreatePDFWithProxyServer.java )
- [Java Sample for Proxy Server Config With Basic Authentication](https://github.com/adobe/pdfservices-java-sdk-samples/blob/master/src/main/java/com/adobe/pdfservices/operation/samples/customconfigurations/CreatePDFWithAuthenticatedProxyServer.java )
@@ -106,6 +107,20 @@ Available properties:
- **username**: Username for the authentication.
- **password**: Password for the authentication.
+### Node.js
+- [Node Sample for Proxy Server Config](https://github.com/adobe/pdfservices-node-sdk-samples/blob/master/src/customconfigurations/create-pdf-with-proxy-server.js)
+- [Node Sample for Proxy Server Config With Basic Authentication](https://github.com/adobe/pdfservices-node-sdk-samples/blob/master/src/customconfigurations/create-pdf-with-authenticated-proxy-server.js)
+
+### Node Proxy Server configuration
+
+Available properties:
+
+- **host**: The proxy Server Hostname (DNS or IP Address)
+- **scheme**: Default: http. Scheme of the proxy server i.e. http or https.
+- **port**: Port on which proxy server is listening.
+- **username**: Username for the authentication.
+- **password**: Password for the authentication.
+
All these properties are wrapped within the `proxyServerConfig` object. Further, `username` and `password` is to be provided
inside the nested object `usernamePasswordCredentials`.
@@ -113,11 +128,11 @@ Set the above properties using a custom `ProxyServerConfig` class, and use `Clie
**Sample showing proxy server configuration without authentication.**
-
+
-###
+### Java
-```javascript
+```java
ProxyServerConfig proxyServerConfig = new ProxyServerConfig.Builder()
.withHost("PROXY_HOSTNAME")
.withProxyScheme(ProxyScheme.HTTPS)
@@ -131,13 +146,27 @@ ClientConfig clientConfig = ClientConfig.builder()
.build();
```
+### Node.js
+
+```js
+const proxyServerConfig = new ProxyServerConfig({
+ host: "PROXY_HOSTNAME",
+ port: 443,
+ scheme: ProxyScheme.HTTP
+});
+
+const clientConfig = new ClientConfig({
+ proxyServerConfig
+});
+```
+
**Sample showing proxy server configuration with authentication.**
-
+
-###
+### Java
-```javascript
+```java
ProxyServerConfig proxyServerConfig = new ProxyServerConfig.Builder()
.withHost("PROXY_HOSTNAME")
.withProxyScheme(ProxyScheme.HTTPS)
@@ -152,6 +181,24 @@ ClientConfig clientConfig = ClientConfig.builder()
.build();
```
+### Node.js
+
+```js
+const proxyServerConfig = new ProxyServerConfig({
+ host: "PROXY_HOSTNAME",
+ port: 443,
+ scheme: ProxyScheme.HTTP,
+ credentials: new UsernamePasswordCredentials({
+ username: "USERNAME",
+ password: "PASSWORD"
+ })
+});
+
+const clientConfig = new ClientConfig({
+ proxyServerConfig
+});
+```
+
## Custom timeout configuration
The APIs use inferred timeout properties and provide defaults. However,
@@ -217,13 +264,8 @@ ClientConfig clientConfig = ClientConfig.ConfigBuilder()
Available properties:
-- **connectTimeout**: Default: 10000. The maximum allowed time in
- milliseconds for creating an initial HTTPS connection.
-- **readTimeout**: Default: 10000. The maximum allowed time in
- milliseconds between two successive HTTP response packets.
-- **processingTimeout**: Default: 600000. The maximum allowed time
- in milliseconds for processing the documents. Any operation taking more time than the specified `processingTimeout` will result in an operation timeout exception.
- - **Note :** It is advisable to set the `processingTimeout` to higher values for processing large files.
+- **timeout**: Default: 10000. The maximum allowed time in milliseconds before the request times out. If the request
+ takes longer than `timeout`, the request will be aborted.
Override the timeout properties via a custom `ClientConfig` class:
@@ -232,12 +274,9 @@ Override the timeout properties via a custom `ClientConfig` class:
###
```javascript
-const clientConfig = PDFServicesSdk.ClientConfig
- .clientConfigBuilder()
- .withConnectTimeout(15000)
- .withReadTimeout(15000)
- .withProcessingTimeout(900000)
- .build();
+const clientConfig = new ClientConfig({
+ timeout: 15000
+})
```
### Python timeout configuration
diff --git a/src/pages/overview/pdf-services-api/howtos/insert-pages.md b/src/pages/overview/pdf-services-api/howtos/insert-pages.md
index 9e62f03b3..681300c1b 100644
--- a/src/pages/overview/pdf-services-api/howtos/insert-pages.md
+++ b/src/pages/overview/pdf-services-api/howtos/insert-pages.md
@@ -5,7 +5,7 @@ title: Insert Pages | How Tos | PDF Services API | Adobe PDF Services
Insert one or more pages into an existing document
-## Rest API
+## REST API
See our public API Reference for [Insert Pages](../../../apis/#tag/Combine-PDF)
@@ -16,7 +16,7 @@ an existing PDF.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -182,71 +182,103 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/insertpages/insert-pdf-pages.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getPageRangesForFirstFile = () => {
- // Specify which pages of the first file are to be inserted in the base file.
- const pageRangesForFirstFile = new PDFServicesSdk.PageRanges();
- // Add pages 1 to 3.
- pageRangesForFirstFile.addPageRange(1, 3);
-
- // Add page 4.
- pageRangesForFirstFile.addSinglePage(4);
-
- return pageRangesForFirstFile;
- };
-
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageRanges,
+ InsertPagesParams,
+ InsertPagesJob,
+ InsertPagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let baseReadStream;
+ let firstReadStreamToInsert;
+ let secondReadStreamToInsert;
try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- insertPagesOperation = PDFServicesSdk.InsertPages.Operation.createNew();
-
- // Set operation base input from a source file.
- const baseInputFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/baseInput.pdf');
- insertPagesOperation.setBaseInput(baseInputFile);
-
- // Create a FileRef instance using a local file.
- const firstFileToInsert = PDFServicesSdk.FileRef.createFromLocalFile('resources/firstFileToInsertInput.pdf'),
- pageRanges = getPageRangesForFirstFile();
-
- // Adds the pages (specified by the page ranges) of the input PDF file to be inserted at
- // the specified page of the base PDF file.
- insertPagesOperation.addPagesToInsertAt(2, firstFileToInsert, pageRanges);
-
- // Create a FileRef instance using a local file.
- const secondFileToInsert = PDFServicesSdk.FileRef.createFromLocalFile('resources/secondFileToInsertInput.pdf');
-
- // Adds all the pages of the input PDF file to be inserted at the specified page of the
- // base PDF file.
- insertPagesOperation.addPagesToInsertAt(3, secondFileToInsert);
-
- // Execute the operation and Save the result to the specified location.
- insertPagesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/insertPagesOutput.pdf'))
- .catch(err => {
- if (err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ baseReadStream = fs.createReadStream("./baseInput.pdf");
+ firstReadStreamToInsert = fs.createReadStream("./firstFileToInsertInput.pdf");
+ secondReadStreamToInsert = fs.createReadStream("./secondFileToInsertInput.pdf");
+ const [baseAsset, firstAssetToInsert, secondAssetToInsert] = await pdfServices.uploadAssets({
+ streamAssets: [{
+ readStream: baseReadStream,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: firstReadStreamToInsert,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: secondReadStreamToInsert,
+ mimeType: MimeType.PDF
+ }]
+ });
+
+ // Create parameters for the job
+ const params = new InsertPagesParams(baseAsset)
+ // Add the first asset as input to the params, along with its page ranges and base page
+ .addPagesToInsertAt({
+ inputAsset: firstAssetToInsert,
+ pageRanges: getPageRangesForFirstFile(),
+ basePage: 2
+ })
+ // Add the second asset as input to the params, along with base page
+ .addPagesToInsertAt({
+ inputAsset: secondAssetToInsert,
+ basePage: 3
+ });
+
+ // Create a new job instance
+ const job = new InsertPagesJob({params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: InsertPagesResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./insertPagesOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
} catch (err) {
- console.log('Exception encountered while executing operation', 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 {
+ baseReadStream?.destroy();
+ firstReadStreamToInsert?.destroy();
+ secondReadStreamToInsert?.destroy();
}
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \
@@ -290,7 +322,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/combinep
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/linearize-pdf.md b/src/pages/overview/pdf-services-api/howtos/linearize-pdf.md
index 8ca897385..9cce24ffe 100644
--- a/src/pages/overview/pdf-services-api/howtos/linearize-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/linearize-pdf.md
@@ -5,7 +5,7 @@ title: Linearize PDF | How Tos | PDF Services API | Adobe PDF Services
Optimize PDFs for quick viewing on the web, especially for mobile clients. Linearization allows your end users to view large PDF documents incrementally so that they can view pages much faster in lower bandwidth conditions.
-## Rest API
+## REST API
See our public API Reference for [Linearize PDF](../../../apis/#tag/Linearize-PDF)
@@ -16,7 +16,7 @@ incremental access in network environments.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -129,45 +129,73 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/linearizepdf/linearize-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- linearizePDF = PDFServicesSdk.LinearizePDF,
- linearizePDFOperation = linearizePDF.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/linearizePDFInput.pdf');
- linearizePDFOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- linearizePDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/linearizePDFOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ LinearizePDFJob,
+ LinearizePDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@dcloud/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./linearizePDFInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Creates a new job instance
+ const job = new LinearizePDFJob({inputAsset});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: LinearizePDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./linearizePDFOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Linearize-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/linearizepdf' \
@@ -177,7 +205,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/lineariz
--data-raw '{
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-linearizePDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/ocr-pdf.md b/src/pages/overview/pdf-services-api/howtos/ocr-pdf.md
index 27923c3b7..c749ac110 100644
--- a/src/pages/overview/pdf-services-api/howtos/ocr-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/ocr-pdf.md
@@ -5,7 +5,7 @@ title: OCR PDF | How Tos | PDF Services API | Adobe PDF Services
Use built-in optical character recognition (OCR) to convert images to text and enable fully text searchable documents for archiving and creation of searchable indexes.
-## Rest API
+## REST API
See our public API Reference for [OCR PDF](../../../apis/#tag/OCR)
@@ -20,7 +20,7 @@ This sample defaults to the en-us locale. For other languages, see [OCR with exp
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -133,44 +133,73 @@ public class OcrPDF {
// Run the sample:
// node src/ocr/ocr-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- ocrOperation = PDFServicesSdk.OCR.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf');
- ocrOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- ocrOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ocrOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ OCRJob,
+ OCRResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./ocrInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Creates a new job instance
+ const job = new OCRJob({inputAsset});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: OCRResult
+ });
+
+ // 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 = "./ocrOutput.pdf";
+ 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Ocr
curl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \
@@ -180,9 +209,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \
--data-raw '{
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-ocr
```
## OCR with explicit language
@@ -208,7 +234,7 @@ are two types which produce a different result:
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -333,51 +359,82 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/ocr/ocr-pdf-with-options.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- //Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- ocrOperation = PDFServicesSdk.OCR.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf');
- ocrOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- const options = new PDFServicesSdk.OCR.options.OCROptions.Builder()
- .withOcrType(PDFServicesSdk.OCR.options.OCRSupportedType.SEARCHABLE_IMAGE_EXACT)
- .withOcrLang(PDFServicesSdk.OCR.options.OCRSupportedLocale.EN_US)
- .build();
- ocrOperation.setOptions(options);
-
- // Execute the operation and Save the result to the specified location.
- ocrOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/ocrWithOptionsOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ OCRJob,
+ OCRParams,
+ OCRSupportedLocale,
+ OCRSupportedType,
+ OCRResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./ocrInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new OCRParams({
+ ocrLocale: OCRSupportedLocale.EN_US,
+ ocrType: OCRSupportedType.SEARCHABLE_IMAGE_EXACT
+ });
+
+ // Creates a new job instance
+ const job = new OCRJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: OCRResult
+ });
+
+ // 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 = "./ocrWithOptionsOutput.pdf";
+ 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Ocr
curl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \
@@ -388,7 +445,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \
"assetID": "ce8fe9da-99f2-4d01-999e-42b9ce22ec5f",
"ocrLang": "en-US"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-ocr
```
diff --git a/src/pages/overview/pdf-services-api/howtos/pdf-properties.md b/src/pages/overview/pdf-services-api/howtos/pdf-properties.md
index 8270d3d64..1f78ae35e 100644
--- a/src/pages/overview/pdf-services-api/howtos/pdf-properties.md
+++ b/src/pages/overview/pdf-services-api/howtos/pdf-properties.md
@@ -7,7 +7,7 @@ Use this service to get the metadata properties of a PDF. Metadata including pag
This data can be used to: check if a document is fully text searchable (OCR), understand the e-signature certificate info, find out compliance levels (e.g., PDF/A and PDF/UA), assess file size before compressing, check permissions related to copy, edit, printing, encryption, and much more.
-## Rest API
+## REST API
See our public API Reference for [PDF Properties](../../../apis/#tag/PDF-Properties).
@@ -17,7 +17,7 @@ The sample below fetches the properties of an input PDF.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -136,52 +136,77 @@ namespace GetPDFProperties
```javascript
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample
// Run the sample:
-// node src/exportpdf/get-pdf-properties.js
-
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
-try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- //Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- pdfPropertiesOperation = PDFServicesSdk.PDFProperties.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/pdfPropertiesInput.pdf');
- pdfPropertiesOperation.setInput(input);
-
- // Provide any custom configuration options for the operation.
- const options = new PDFServicesSdk.PDFProperties.options.PDFPropertiesOptions.Builder()
- .includePageLevelProperties(true)
- .build();
- pdfPropertiesOperation.setOptions(options);
-
- // Execute the operation ang get properties of the PDF in PDFProperties object.
- pdfPropertiesOperation.execute(executionContext)
- .then(result => console.log("The resultant json object is : " + JSON.stringify(result, null, 4)))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+// node src/pdfproperties/get-pdf-properties.js
+
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PDFPropertiesParams,
+ PDFPropertiesJob,
+ PDFPropertiesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
-} catch (err) {
- console.log('Exception encountered while executing operation', err);
-}
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./pdfPropertiesInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new PDFPropertiesParams({
+ includePageLevelProperties: true
+ });
+
+ // Creates a new job instance
+ const job = new PDFPropertiesJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: PDFPropertiesResult
+ });
+
+ const pdfProperties = pdfServicesResponse.result.pdfProperties;
+
+ // Fetch the requisite properties of the specified PDF.
+ console.log(`Size of the specified PDF file: ${pdfProperties.document.fileSize}`);
+ console.log(`Version of the specified PDF file: ${pdfProperties.document.pdfVersion}`);
+ console.log(`Page count of the specified PDF file: ${pdfProperties.document.pageCount}`);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-Properties
curl --location --request POST 'https://pdf-services.adobe.io/operation/pdfproperties' \
@@ -192,7 +217,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/pdfprope
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",
"pageLevel": false
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-pdfProperties
```
diff --git a/src/pages/overview/pdf-services-api/howtos/protect-pdf.md b/src/pages/overview/pdf-services-api/howtos/protect-pdf.md
index 7211affa1..d05fe2e8b 100644
--- a/src/pages/overview/pdf-services-api/howtos/protect-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/protect-pdf.md
@@ -7,7 +7,7 @@ Secure a PDF file with a password encrypt the document. Set an owner password an
Support for AES-128 and AES-256 encryption on PDF files, with granular permissions for high and low quality printing and fill and sign form field restrictions.
-## Rest API
+## REST API
See our public API Reference for [Protect PDF](../../../apis/#tag/Protect-PDF)
@@ -18,7 +18,7 @@ password can open the file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -146,54 +146,81 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/protectpdf/protect-pdf.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ProtectPDFParams,
+ EncryptionAlgorithm,
+ ProtectPDFJob,
+ ProtectPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Build ProtectPDF options by setting a User Password and Encryption
- // Algorithm (used for encrypting the PDF file).
- const protectPDF = PDFServicesSdk.ProtectPDF,
- options = new protectPDF.options.PasswordProtectOptions.Builder()
- .setUserPassword("encryptPassword")
- .setEncryptionAlgorithm(PDFServicesSdk.ProtectPDF.options.EncryptionAlgorithm.AES_256)
- .build();
-
- // Create a new operation instance.
- const protectPDFOperation = protectPDF.Operation.createNew(options);
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/protectPDFInput.pdf');
- protectPDFOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- protectPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/protectPDFOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./protectPDFInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ProtectPDFParams({
+ userPassword: "password",
+ encryptionAlgorithm: EncryptionAlgorithm.AES_256
+ });
+
+ // Create a new job instance
+ const job = new ProtectPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ProtectPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./protectPDFOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
} catch (err) {
- console.log('Exception encountered while executing operation', 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();
}
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Protect-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/protectpdf' \
@@ -207,9 +234,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/protectp
"encryptionAlgorithm": "AES_128",
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-protectPDF
```
## Protect PDFs with owner password
@@ -222,7 +246,7 @@ of document permissions.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -370,63 +394,95 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/protectpdf/protect-pdf-with-owner-password.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Create new permissions instance and add the required permissions
- const protectPDF = PDFServicesSdk.ProtectPDF,
- protectPDFOptions = protectPDF.options,
- permissions = protectPDFOptions.Permissions.createNew();
- permissions.addPermission(protectPDFOptions.Permission.PRINT_LOW_QUALITY);
- permissions.addPermission(protectPDFOptions.Permission.EDIT_DOCUMENT_ASSEMBLY);
- permissions.addPermission(protectPDFOptions.Permission.COPY_CONTENT);
-
- // Build ProtectPDF options by setting an Owner/Permissions Password, Permissions,
- // Encryption Algorithm (used for encrypting the PDF file) and specifying the type of content to encrypt.
- const options = new protectPDFOptions.PasswordProtectOptions.Builder()
- .setOwnerPassword("password")
- .setPermissions(permissions)
- .setEncryptionAlgorithm(protectPDFOptions.EncryptionAlgorithm.AES_256)
- .setContentEncryption(protectPDFOptions.ContentEncryption.ALL_CONTENT_EXCEPT_METADATA)
- .build();
-
- // Create a new operation instance.
- const protectPDFOperation = protectPDF.Operation.createNew(options);
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/protectPDFInput.pdf');
- protectPDFOperation.setInput(input);
-
- // Execute the operation and Save the result to the specified location.
- protectPDFOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/protectPDFWithOwnerPasswordOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ProtectPDFParams,
+ EncryptionAlgorithm,
+ ProtectPDFJob,
+ ProtectPDFResult,
+ ContentEncryption,
+ Permissions,
+ Permission,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // Initial setup, create credentials instance
+ const credentials = new ServicePrincipalCredentials({
+ clientId: process.env.PDF_SERVICES_CLIENT_ID,
+ clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET
});
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+
+ // Creates a PDF Services instance
+ const pdfServices = new PDFServices({credentials});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./protectPDFInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create new permissions instance and add the required permissions
+ const permissions = new Permissions({
+ permissions: [
+ Permission.PRINT_LOW_QUALITY,
+ Permission.EDIT_DOCUMENT_ASSEMBLY,
+ Permission.COPY_CONTENT
+ ]
+ });
+
+ // Create parameters for the job
+ const params = new ProtectPDFParams({
+ ownerPassword: "password",
+ permissions: permissions,
+ encryptionAlgorithm: EncryptionAlgorithm.AES_256,
+ contentEncryption: ContentEncryption.ALL_CONTENT_EXCEPT_METADATA,
+ });
+
+ // Create a new job instance
+ const job = new ProtectPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ProtectPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./protectPDFWithOwnerPasswordOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Protect-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/protectpdf' \
@@ -440,7 +496,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/protectp
"encryptionAlgorithm": "AES_256",
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-protectPDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/remove-protection.md b/src/pages/overview/pdf-services-api/howtos/remove-protection.md
index 017931fb2..abe73e2a6 100644
--- a/src/pages/overview/pdf-services-api/howtos/remove-protection.md
+++ b/src/pages/overview/pdf-services-api/howtos/remove-protection.md
@@ -5,7 +5,7 @@ title: Remove Protection | How Tos | PDF Services API | Adobe PDF Services
Remove password security from a PDF document. This can only be accomplished with the owner password of the document which must be passed in the operation.
-## Rest API
+## REST API
See our public API Reference for [Remove Protection](../../../apis/#tag/Remove-Protection)
@@ -15,7 +15,7 @@ Use the below sample to remove security from a PDF document.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -137,51 +137,79 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/removeprotection/remove-protection.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Create a new operation instance.
- const removeProtectionOperation = PDFServicesSdk.RemoveProtection.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/removeProtectionInput.pdf',
- PDFServicesSdk.RemoveProtection.SupportedSourceFormat.pdf
- );
- // Set operation input from a source file.
- removeProtectionOperation.setInput(input);
-
- // Set the password for removing security from a PDF document.
- removeProtectionOperation.setPassword("password");
-
- // Execute the operation and Save the result to the specified location.
- removeProtectionOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/removeProtectionOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ RemoveProtectionParams,
+ RemoveProtectionJob,
+ RemoveProtectionResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./removeProtectionInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new RemoveProtectionParams({
+ password: "password"
+ });
+
+ // Creates a new job instance
+ const job = new RemoveProtectionJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: RemoveProtectionResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./removeProtectionOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Remove-Protection
curl --location --request POST 'https://pdf-services.adobe.io/operation/removeprotection' \
@@ -192,7 +220,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/removepr
"password": "mypassword",
"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-removeProtection
```
diff --git a/src/pages/overview/pdf-services-api/howtos/reorder-pages.md b/src/pages/overview/pdf-services-api/howtos/reorder-pages.md
index 761206999..710e7708d 100644
--- a/src/pages/overview/pdf-services-api/howtos/reorder-pages.md
+++ b/src/pages/overview/pdf-services-api/howtos/reorder-pages.md
@@ -5,7 +5,7 @@ title: Reorder Pages | How Tos | PDF Services API | Adobe PDF Services
Reorder the pages of a PDF file to reorganize.
-## Rest API
+## REST API
See our public API Reference for [Reorder Pages](../../../apis/#tag/Combine-PDF)
@@ -16,7 +16,7 @@ a PDF file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -166,59 +166,92 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/reorderpages/reorder-pdf-pages.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getPageRangeForReorder = () => {
- // Specify order of the pages for an output document.
- const pageRanges = new PDFServicesSdk.PageRanges();
-
- // Add pages 3 to 4.
- pageRanges.addPageRange(3, 4);
-
- // Add page 1.
- pageRanges.addSinglePage(1);
-
- return pageRanges;
- };
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- reorderPagesOperation = PDFServicesSdk.ReorderPages.Operation.createNew();
-
- // Set operation input from a source file, along with specifying the order of the pages for
- // rearranging the pages in a PDF file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/reorderPagesInput.pdf');
- const pageRanges = getPageRangeForReorder();
- reorderPagesOperation.setInput(input);
- reorderPagesOperation.setPagesOrder(pageRanges);
-
- // Execute the operation and Save the result to the specified location.
- reorderPagesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/reorderPagesOutput.pdf'))
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageRanges,
+ ReorderPagesParams,
+ ReorderPagesJob,
+ ReorderPagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./reorderPagesInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ // Add the asset as input to the params, along with its page order
+ const params = new ReorderPagesParams({
+ asset: inputAsset,
+ pageRanges: getPageRangeForReorder()
+ });
+
+ // Creates a new job instance
+ const job = new ReorderPagesJob({params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ReorderPagesResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./reorderPagesOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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();
+ }
+})();
+
+function getPageRangeForReorder() {
+ // Specify order of the pages for an output document
+ const pageRanges = new PageRanges();
+ // Add pages 3 to 4
+ pageRanges.addRange(3, 4);
+ // Add page 1
+ pageRanges.addSinglePage(1);
+ return pageRanges;
+}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \
@@ -246,7 +279,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/combinep
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/replace-pages.md b/src/pages/overview/pdf-services-api/howtos/replace-pages.md
index 11d3f2ba5..6d633f1d3 100644
--- a/src/pages/overview/pdf-services-api/howtos/replace-pages.md
+++ b/src/pages/overview/pdf-services-api/howtos/replace-pages.md
@@ -5,7 +5,7 @@ title: Replace Pages | How Tos | PDF Services API | Adobe PDF Services
Replace one or more pages with another page in an existing document
-## Rest API
+## REST API
See our public API Reference for [Replace Pages](../../../apis/#tag/Combine-PDF)
@@ -16,7 +16,7 @@ other PDF files.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -182,70 +182,113 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/replacepages/replace-pdf-pages.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getPageRangesForFirstFile = () => {
- // Specify pages of the first file for replacing the page of base PDF file.
- const pageRangesForFirstFile = new PDFServicesSdk.PageRanges();
- // Add pages 1 to 3.
- pageRangesForFirstFile.addPageRange(1, 3);
-
- // Add page 4.
- pageRangesForFirstFile.addSinglePage(4);
-
- return pageRangesForFirstFile;
- };
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- replacePagesOperation = PDFServicesSdk.ReplacePages.Operation.createNew();
-
- // Set operation base input from a source file.
- const baseInputFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/baseInput.pdf');
- replacePagesOperation.setBaseInput(baseInputFile);
-
- // Create a FileRef instance using a local file.
- const firstInputFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/replacePagesInput1.pdf'),
- pageRanges = getPageRangesForFirstFile();
-
- // Adds the pages (specified by the page ranges) of the input PDF file for replacing the
- // page of the base PDF file.
- replacePagesOperation.addPagesForReplace(1, firstInputFile, pageRanges);
-
- // Create a FileRef instance using a local file.
- const secondInputFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/replacePagesInput2.pdf');
-
- // Adds all the pages of the input PDF file for replacing the page of the base PDF file.
- replacePagesOperation.addPagesForReplace(3, secondInputFile);
-
- // Execute the operation and Save the result to the specified location.
- replacePagesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/replacePagesOutput.pdf'))
- .catch(err => {
- if (err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageRanges,
+ InsertPagesResult,
+ ReplacePagesJob,
+ ReplacePagesParams,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let baseReadStream;
+ let readStream1;
+ let readStream2;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ baseReadStream = fs.createReadStream("./baseInput.pdf");
+ readStream1 = fs.createReadStream("./replacePagesInput1.pdf");
+ readStream2 = fs.createReadStream("./replacePagesInput2.pdf");
+ const [baseAsset, asset1, asset2] = await pdfServices.uploadAssets({
+ streamAssets: [{
+ readStream: baseReadStream,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: readStream1,
+ mimeType: MimeType.PDF
+ }, {
+ readStream: readStream2,
+ mimeType: MimeType.PDF
+ }]
+ });
+
+ // Create parameters for the job
+ const params = new ReplacePagesParams(baseAsset)
+ // Add the first asset as input to the params, along with its page ranges and base page
+ .addPagesForReplace({
+ asset: asset1,
+ pageRanges: getPageRangesForFirstFile(),
+ basePage: 1
+ })
+ // Add the second asset as input to the params, along with base page
+ .addPagesForReplace({
+ asset: asset2,
+ basePage: 3
+ });
+
+ // Create a new job instance
+ const job = new ReplacePagesJob({params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: InsertPagesResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy result asset's content to it
+ const outputFilePath = "./replacePagesOutput.pdf";
+ console.log(`Saving asset at ${outputFilePath}`);
+
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } 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 {
+ baseReadStream?.destroy();
+ readStream1?.destroy();
+ readStream2?.destroy();
+ }
+})();
+
+function getPageRangesForFirstFile() {
+ // Specify pages of the first file for replacing the page of base PDF file
+ const pageRanges = new PageRanges();
+ // Add pages 1 to 3
+ pageRanges.addRange(1, 3);
+ // Add page 4
+ pageRanges.addSinglePage(4);
+ return pageRanges;
+}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \
@@ -281,6 +324,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/combinep
}
]
}'
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
```
diff --git a/src/pages/overview/pdf-services-api/howtos/rotate-pages.md b/src/pages/overview/pdf-services-api/howtos/rotate-pages.md
index 05fc8cad3..0ba8b1ff6 100644
--- a/src/pages/overview/pdf-services-api/howtos/rotate-pages.md
+++ b/src/pages/overview/pdf-services-api/howtos/rotate-pages.md
@@ -5,7 +5,7 @@ title: Rotate Pages | How Tos | PDF Services API | Adobe PDF Services
Rotate a page in an existing document.
-## Rest API
+## REST API
See our public API Reference for [Rotate Pages.](../../../apis/#tag/Page-Manipulation)
@@ -16,7 +16,7 @@ example, you can change portrait view to landscape view.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -195,75 +195,105 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/rotatepages/rotate-pdf-pages.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- const getFirstPageRangeForRotation = () => {
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ PageRanges,
+ RotatePagesParams,
+ Angle,
+ RotatePagesJob,
+ RotatePagesResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./rotatePagesInput.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // First set of page ranges for rotating the specified pages of the input PDF file
+ const firstPageRange = getFirstPageRangeForRotation();
+
+ // Second set of page ranges for rotating the specified pages of the input PDF file
+ const secondPageRange = getSecondPageRangeForRotation();
+
+ // Create parameters for the job
+ const params = new RotatePagesParams()
+ .setAngleToRotatePagesBy(Angle._90, firstPageRange)
+ .setAngleToRotatePagesBy(Angle._180, secondPageRange);
+
+ // Creates a new job instance
+ const job = new RotatePagesJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: RotatePagesResult
+ });
+
+ // 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 = "./rotatePagesOutput.pdf";
+ 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();
+ }
+})();
+
+function getFirstPageRangeForRotation() {
// Specify pages for rotation.
- const firstPageRange = new PDFServicesSdk.PageRanges();
+ const firstPageRange = new PageRanges();
// Add page 1.
firstPageRange.addSinglePage(1);
-
// Add pages 3 to 4.
- firstPageRange.addPageRange(3, 4);
-
+ firstPageRange.addRange(3, 4);
return firstPageRange;
- };
-
- const getSecondPageRangeForRotation = () => {
+}
+
+function getSecondPageRangeForRotation() {
// Specify pages for rotation.
- const secondPageRange = new PDFServicesSdk.PageRanges();
+ const secondPageRange = new PageRanges();
// Add page 2.
secondPageRange.addSinglePage(2);
-
return secondPageRange;
- };
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials and create a new operation instance.
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),
- rotatePagesOperation = PDFServicesSdk.RotatePages.Operation.createNew();
-
- // Set operation input from a source file.
- const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/rotatePagesInput.pdf');
- rotatePagesOperation.setInput(input);
-
- // Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of
- // the input PDF file.
- const firstPageRange = getFirstPageRangeForRotation();
- rotatePagesOperation.setAngleToRotatePagesBy(PDFServicesSdk.RotatePages.Angle._90, firstPageRange);
-
- // Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of
- // the input PDF file.
- const secondPageRange = getSecondPageRangeForRotation();
- rotatePagesOperation.setAngleToRotatePagesBy(PDFServicesSdk.RotatePages.Angle._180,secondPageRange);
-
- // Execute the operation and Save the result to the specified location.
- rotatePagesOperation.execute(executionContext)
- .then(result => result.saveAsFile('output/rotatePagesOutput.pdf'))
- .catch(err => {
- if (err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+}
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulation
curl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \
@@ -296,7 +326,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/pagemani
}
]
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
```
diff --git a/src/pages/overview/pdf-services-api/howtos/service-region-configuration-for-apis.md b/src/pages/overview/pdf-services-api/howtos/service-region-configuration-for-apis.md
index 13bc6ff99..a0cdd2350 100644
--- a/src/pages/overview/pdf-services-api/howtos/service-region-configuration-for-apis.md
+++ b/src/pages/overview/pdf-services-api/howtos/service-region-configuration-for-apis.md
@@ -24,9 +24,9 @@ For invoking region specific PDF Services API endpoints, hostnames needs to be c
### Assets API
-
+
-#### Rest API
+#### REST API
```javascript
curl --location --request POST 'https://pdf-services-ew1.adobe.io/assets' \
@@ -40,9 +40,9 @@ curl --location --request POST 'https://pdf-services-ew1.adobe.io/assets' \
### Create Job API
-
+
-#### Rest API
+#### REST API
```javascript
@@ -58,9 +58,9 @@ curl --location --request POST 'https://pdf-services-ew1.adobe.io/operation/{Pla
### Poll Job API
-
+
-#### Rest API
+#### REST API
```javascript
diff --git a/src/pages/overview/pdf-services-api/howtos/split-pdf.md b/src/pages/overview/pdf-services-api/howtos/split-pdf.md
index 0a37090f3..9a4b18774 100644
--- a/src/pages/overview/pdf-services-api/howtos/split-pdf.md
+++ b/src/pages/overview/pdf-services-api/howtos/split-pdf.md
@@ -5,7 +5,7 @@ title: Split PDF | How Tos | PDF Services API | Adobe PDF Services
Split a PDF document into multiple smaller documents by simply specifying either the number of files, pages per file, or page ranges.
-## Rest API
+## REST API
See our public API Reference for [Split PDF](../../../apis/#tag/Split-PDF).
@@ -17,7 +17,7 @@ file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -152,58 +152,82 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/splitpdf/split-pdf-by-number-of-pages.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Create a new operation instance.
- const splitPDFOperation = PDFServicesSdk.SplitPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/splitPDFInput.pdf',
- PDFServicesSdk.SplitPDF.SupportedSourceFormat.pdf
- );
- // Set operation input from a source file.
- splitPDFOperation.setInput(input);
-
- // Set the maximum number of pages each of the output files can have.
- splitPDFOperation.setPageCount(2);
-
- // Execute the operation and Save the result to the specified location.
- splitPDFOperation.execute(executionContext)
- .then(result => {
- let saveFilesPromises = [];
- for(let i = 0; i < result.length; i++){
- saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFByNumberOfPagesOutput_${i}.pdf`));
- }
- return Promise.all(saveFilesPromises);
- })
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
-
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ SplitPDFParams,
+ SplitPDFJob,
+ SplitPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./splitPDFInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new SplitPDFParams({
+ pageCount: 2
+ });
+
+ // Creates a new job instance
+ const job = new SplitPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: SplitPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAssets = pdfServicesResponse.result.assets;
+
+ for (let i = 0; i < resultAssets.length; i++) {
+ const streamAsset = await pdfServices.getContent({asset: resultAssets[i]});
+
+ // Creates an output stream and copy stream asset's content to it
+ const _outputFilePath = "./SplitPDFByNumberOfPagesOutput_" + i + ".pdf";
+ 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Split-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf' \
@@ -216,9 +240,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf
"pageCount": 9
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-splitPDF
```
## Split PDF by page ranges
@@ -229,7 +250,7 @@ ranges where each page range corresponds to a single output file.
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -392,68 +413,94 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/splitpdf/split-pdf-by-page-ranges.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ SplitPDFParams,
+ SplitPDFJob,
+ SplitPDFResult,
+ PageRanges,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./splitPDFInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create the page ranges where each page range corresponds to a single output file
+ const pageRanges = getPageRanges();
+
+ // Create parameters for the job
+ const params = new SplitPDFParams({pageRanges});
+
+ // Creates a new job instance
+ const job = new SplitPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: SplitPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAssets = pdfServicesResponse.result.assets;
+
+ for (let i = 0; i < resultAssets.length; i++) {
+ const streamAsset = await pdfServices.getContent({asset: resultAssets[i]});
+
+ // Creates an output stream and copy stream asset's content to it
+ const _outputFilePath = "./SplitPDFByPageRangesOutput_" + i + ".pdf";
+ 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();
+ }
+})();
- const getPageRanges = () => {
+const getPageRanges = () => {
// Specify pages ranges.
- const pageRanges = new PDFServicesSdk.PageRanges();
+ const pageRanges = new PageRanges();
// Add page 1.
pageRanges.addSinglePage(1);
-
// Add pages 3 to 4.
- pageRanges.addPageRange(3, 4);
+ pageRanges.addRange(3, 4);
return pageRanges;
- };
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Create a new operation instance.
- const splitPDFOperation = PDFServicesSdk.SplitPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/splitPDFInput.pdf',
- PDFServicesSdk.SplitPDF.SupportedSourceFormat.pdf
- );
- // Set operation input from a source file.
- splitPDFOperation.setInput(input);
-
- // Set the page ranges where each page range corresponds to a single output file.
- const pageRanges = getPageRanges();
- splitPDFOperation.setPageRanges(pageRanges);
-
- // Execute the operation and Save the result to the specified location.
- splitPDFOperation.execute(executionContext)
- .then(result => {
- let saveFilesPromises = [];
- for(let i = 0; i < result.length; i++){
- saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFByPageRangesOutput_${i}.pdf`));
- }
- return Promise.all(saveFilesPromises);
- })
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+};
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Split-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf' \
@@ -475,9 +522,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf
]
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-splitPDF
```
## Split PDF into number of files
@@ -489,7 +533,7 @@ an identical number of pages (if possible).
Please refer the [API usage guide](../api-usage.md) to understand how to use our APIs.
-
+
#### Java
@@ -626,57 +670,82 @@ Please refer the [API usage guide](../api-usage.md) to understand how to use our
// Run the sample:
// node src/splitpdf/split-pdf-into-number-of-files.js
- const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-
- try {
- // Initial setup, create credentials instance.
- const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId("PDF_SERVICES_CLIENT_ID")
- .withClientSecret("PDF_SERVICES_CLIENT_SECRET")
- .build();
-
- // Create an ExecutionContext using credentials
- const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
- // Create a new operation instance.
- const splitPDFOperation = PDFServicesSdk.SplitPDF.Operation.createNew(),
- input = PDFServicesSdk.FileRef.createFromLocalFile(
- 'resources/splitPDFInput.pdf',
- PDFServicesSdk.SplitPDF.SupportedSourceFormat.pdf
- );
- // Set operation input from a source file.
- splitPDFOperation.setInput(input);
-
- // Set the number of documents to split the input PDF file into.
- splitPDFOperation.setFileCount(2);
-
- // Execute the operation and Save the result to the specified location.
- splitPDFOperation.execute(executionContext)
- .then(result => {
- let saveFilesPromises = [];
- for(let i = 0; i < result.length; i++){
- saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFIntoNumberOfFilesOutput_${i}.pdf`));
- }
- return Promise.all(saveFilesPromises);
- })
- .catch(err => {
- if(err instanceof PDFServicesSdk.Error.ServiceApiError
- || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
- console.log('Exception encountered while executing operation', err);
- } else {
- console.log('Exception encountered while executing operation', err);
- }
- });
- } catch (err) {
- console.log('Exception encountered while executing operation', err);
- }
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ SplitPDFParams,
+ SplitPDFJob,
+ SplitPDFResult,
+ SDKError,
+ ServiceUsageError,
+ ServiceApiError
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./splitPDFInput.pdf")
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new SplitPDFParams({
+ fileCount: 2
+ });
+
+ // Creates a new job instance
+ const job = new SplitPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: SplitPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAssets = pdfServicesResponse.result.assets;
+
+ for (let i = 0; i < resultAssets.length; i++) {
+ const streamAsset = await pdfServices.getContent({asset: resultAssets[i]});
+
+ // Creates an output stream and copy stream asset's content to it
+ const _outputFilePath = "./SplitPDFIntoNumberOfFilesOutput_" + i + ".pdf";
+ 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();
+ }
+})();
```
-#### Rest API
+#### REST API
```javascript
-// Please refer our Rest API docs for more information
+// Please refer our REST API docs for more information
// https://developer.adobe.com/document-services/docs/apis/#tag/Split-PDF
curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf' \
@@ -689,7 +758,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf
"fileCount": 3
}
}'
-
-// Legacy API can be found here
-// https://documentcloud.adobe.com/document-services/index.html#post-splitPDF
```
diff --git a/src/pages/overview/pdf-services-api/quickstarts/nodejs/index.md b/src/pages/overview/pdf-services-api/quickstarts/nodejs/index.md
index 4ba1cc9d4..2f5165ea1 100644
--- a/src/pages/overview/pdf-services-api/quickstarts/nodejs/index.md
+++ b/src/pages/overview/pdf-services-api/quickstarts/nodejs/index.md
@@ -10,7 +10,7 @@ To get started using Adobe PDF Services API, let's walk through a simple scenari
To complete this guide, you will need:
-* [Node.js](https://nodejs.org) - Node.js version 14.0 or higher is required.
+* [Node.js](https://nodejs.org) - 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.
@@ -63,24 +63,19 @@ Now you're ready to begin coding.
1) We'll begin by including our required dependencies:
```js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-const fs = require('fs');
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFParams,
+ ExportPDFTargetFormat,
+ ExportPDFJob,
+ ExportPDFResult
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
```
-The first line includes the Adobe PDF Services Node.js SDK. The second third include Node's `filesystem` package.
-
-2) Now let's define our input and output:
-
-```js
-const OUTPUT = './Bodea Brochure.docx';
-
-// If our output already exists, remove it so we can run the application again.
-if(fs.existsSync(OUTPUT)) fs.unlinkSync(OUTPUT);
-
-const INPUT = './Bodea Brochure.pdf';
-```
-
-3) 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:
+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=`
- `set PDF_SERVICES_CLIENT_SECRET=`
@@ -89,51 +84,64 @@ const INPUT = './Bodea Brochure.pdf';
- `export PDF_SERVICES_CLIENT_ID=`
- `export PDF_SERVICES_CLIENT_SECRET=`
-4) Next, we setup the SDK to use our credentials.
+3) Next, we can create our credentials and use them:
```js
-const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
- .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
- .build();
-
-// Create an ExecutionContext using credentials
-const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
+// 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});
```
-This code both points to the credentials downloaded previously as well as sets up an execution context object that will be used later.
+4) Now, let's upload the asset:
-5) Now, let's create the operation:
+```js
+const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+});
+```
+
+5) Now, let's create the parameters and the job:
```js
-// This creates an instance of the Export operation we're using, as well as specifying output type (DOCX)
-const exportPdfOperation = PDFServicesSdk.ExportPDF.Operation.createNew(PDFServicesSdk.ExportPDF.SupportedTargetFormats.DOCX);
+// Create parameters for the job
+const params = new ExportPDFParams({
+ targetFormat: ExportPDFTargetFormat.DOCX
+});
-// Set operation input from a source file
-const inputPDF = PDFServicesSdk.FileRef.createFromLocalFile(INPUT);
-exportPdfOperation.setInput(inputPDF);
+// Creates a new job instance
+const job = new ExportPDFJob({inputAsset, params});
```
-This set of code defines what we're doing (an Export operation), points to our local file and specifies the input is a PDF, and then defines options for the Export call. In this example, the only option is the export format, DOCX.
+This set of code defines what we're doing (an Export operation), and sets parameter for the Export PDF job.
+In this example, the only parameter is the export format ,ie, DOCX.
+
+6) The next code block submits the job and gets the job result:
+
+```js
+// Submit the job and get the job result
+const pollingURL = await pdfServices.submit({job});
+const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFResult
+});
+
+// Get content from the resulting asset(s)
+const resultAsset = pdfServicesResponse.result.asset;
+const streamAsset = await pdfServices.getContent({asset: resultAsset});
+```
-6) The next code block executes the operation:
+7) The next code block saves the result at the specified location:
```js
-try {
-
- exportPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile(OUTPUT))
- .then(() => {
- console.log('Export Done')
- })
- .catch(err => {
- console.log('Exception encountered while executing operation', err);
- });
-
-} catch(err) {
- console.error('Error:', err);
-}
+// Creates an output stream and copy stream asset's content to it
+const outputStream = fs.createWriteStream("./Bodea Brochure.docx");
+streamAsset.readStream.pipe(outputStream);
```
This code runs the Export process and then stores the result Word document to the file system.
@@ -143,50 +151,66 @@ This code runs the Export process and then stores the result Word document to th
Here's the complete application (`export.js`):
```js
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
-const fs = require('fs');
-
-const OUTPUT = './Bodea Brochure.docx';
-
-// If our output already exists, remove it so we can run the application again.
-if(fs.existsSync(OUTPUT)) fs.unlinkSync(OUTPUT);
-
-const INPUT = './Bodea Brochure.pdf';
-
-
-console.log(`About to export ${INPUT} to ${OUTPUT}.`);
-
-// Set up our credentials object.
-const credentials = PDFServicesSdk.Credentials
- .servicePrincipalCredentialsBuilder()
- .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
- .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
- .build();
-
-// An exectuionContext object wraps our credentials
-const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);
-
-// This creates an instance of the Export operation we're using, as well as specifying output type (DOCX)
-const exportPdfOperation = PDFServicesSdk.ExportPDF.Operation.createNew(PDFServicesSdk.ExportPDF.SupportedTargetFormats.DOCX);
-
-// Set operation input from a source file
-const inputPDF = PDFServicesSdk.FileRef.createFromLocalFile(INPUT);
-exportPdfOperation.setInput(inputPDF);
-
-try {
-
- exportPdfOperation.execute(executionContext)
- .then(result => result.saveAsFile(OUTPUT))
- .then(() => {
- console.log('Export Done')
- })
- .catch(err => {
- console.log('Exception encountered while executing operation', err);
- });
-
-} catch(err) {
- console.error('Error:', err);
-}
+const {
+ ServicePrincipalCredentials,
+ PDFServices,
+ MimeType,
+ ExportPDFParams,
+ ExportPDFTargetFormat,
+ ExportPDFJob,
+ ExportPDFResult
+} = require("@adobe/pdfservices-node-sdk");
+const fs = require("fs");
+
+(async () => {
+ let readStream;
+ try {
+ // 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});
+
+ // Creates an asset(s) from source file(s) and upload
+ readStream = fs.createReadStream("./Bodea Brochure.pdf");
+ const inputAsset = await pdfServices.upload({
+ readStream,
+ mimeType: MimeType.PDF
+ });
+
+ // Create parameters for the job
+ const params = new ExportPDFParams({
+ targetFormat: ExportPDFTargetFormat.DOCX
+ });
+
+ // Creates a new job instance
+ const job = new ExportPDFJob({inputAsset, params});
+
+ // Submit the job and get the job result
+ const pollingURL = await pdfServices.submit({job});
+ const pdfServicesResponse = await pdfServices.getJobResult({
+ pollingURL,
+ resultType: ExportPDFResult
+ });
+
+ // Get content from the resulting asset(s)
+ const resultAsset = pdfServicesResponse.result.asset;
+ const streamAsset = await pdfServices.getContent({asset: resultAsset});
+
+ // Creates an output stream and copy stream asset's content to it
+ const outputFilePath = "./Bodea Brochure.docx";
+ console.log(`Saving asset at ${outputFilePath}`);
+ const outputStream = fs.createWriteStream(outputFilePath);
+ streamAsset.readStream.pipe(outputStream);
+ } catch (err) {
+ console.log("Exception encountered while executing operation", err);
+ } finally {
+ readStream?.destroy();
+ }
+})();
```
## Next Steps
diff --git a/src/pages/overview/pdf-services-api/quickstarts/nodejs/shot9.png b/src/pages/overview/pdf-services-api/quickstarts/nodejs/shot9.png
index b48baa077..f629ac0ac 100644
Binary files a/src/pages/overview/pdf-services-api/quickstarts/nodejs/shot9.png and b/src/pages/overview/pdf-services-api/quickstarts/nodejs/shot9.png differ
diff --git a/src/pages/overview/pdf-services-api/releasenotes.md b/src/pages/overview/pdf-services-api/releasenotes.md
index 580744f44..9e04bdec2 100644
--- a/src/pages/overview/pdf-services-api/releasenotes.md
+++ b/src/pages/overview/pdf-services-api/releasenotes.md
@@ -73,13 +73,13 @@ import com.adobe.pdfservices.operation.ExecutionContext;
* Update the latest SDK dependency in package.json file of your project
```
-"@adobe/pdfservices-node-sdk": "3.4.2"
+"@adobe/pdfservices-node-sdk": "4.0.0"
```
* Require the `@adobe/pdfservices-node-sdk` in the Sample file to access the SDK interface
```
-const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
+const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');
```
@@ -129,6 +129,18 @@ Upgrading to the latest SDK should not break existing applications.
## Change history
+### 4.0.0 (April, 2024; major release)
+
+| Change | Language | Description |
+|---------|----------|------------------------------------------------------------------------------------------------------------------------------------|
+| New | NodeJS | Released Adobe PDF Services Node SDK v4.0.0, introducing new interfaces fully leveraging power of new PDF Services rest APIs. |
+| New | NodeJS | Added support for delete asset and webhook notifiers. |
+| New | NodeJS | Eliminated need of storage to save intermediate result by removed dependency on temporary storage. |
+| New | NodeJS | Extended I/O capabilities by introducing external storage for PDF Services operations. |
+| New | NodeJS | Enabled connection to Internet through Proxy, where proxy server settings can be set via "proxyServerConfig" in the client config. |
+| Changed | NodeJS | Updated PDF Properties operation to return PDFProperties object along with JSON string. |
+| Changed | NodeJS | Updated Extract PDF operation to return content and resource asset along with content JSON object. |
+
### 2.3.1 (March, 2024; patch release)
| Change | Language | Description |
diff --git a/src/pages/overview/releasenotes.md b/src/pages/overview/releasenotes.md
index e6d4f06a6..0fa3e6606 100644
--- a/src/pages/overview/releasenotes.md
+++ b/src/pages/overview/releasenotes.md
@@ -116,7 +116,7 @@ import com.adobe.pdfservices.operation.ExecutionContext;
* Update the latest SDK dependency in package.json file of your project
```
-"@adobe/pdfservices-node-sdk": "3.4.2"
+"@adobe/pdfservices-node-sdk": "4.0.0"
```
* Require the `@adobe/pdfservices-node-sdk` in the Sample file to access the SDK interface
@@ -173,13 +173,25 @@ Upgrading to the latest SDK should not break existing applications.
## Change history
+### 4.0.0 (April, 2024; major release)
+
+| Change | Language | Description |
+|---------|----------|------------------------------------------------------------------------------------------------------------------------------------|
+| New | NodeJS | Released Adobe PDF Services Node SDK v4.0.0, introducing new interfaces fully leveraging power of new PDF Services rest APIs. |
+| New | NodeJS | Added support for delete asset and webhook notifiers. |
+| New | NodeJS | Eliminated need of storage to save intermediate result by removed dependency on temporary storage. |
+| New | NodeJS | Extended I/O capabilities by introducing external storage for PDF Services operations. |
+| New | NodeJS | Enabled connection to Internet through Proxy, where proxy server settings can be set via "proxyServerConfig" in the client config. |
+| Changed | NodeJS | Updated PDF Properties operation to return PDFProperties object along with JSON string. |
+| Changed | NodeJS | Updated Extract PDF operation to return content and resource asset along with content JSON object. |
+
### Server Side Release (April, 2024; server side release)
| Change | Language | Description |
|--------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| New | API | Added support for [Webhook Notification](../pdf-services-api/howtos/webhook-notification/) in PDF Properties and External Storage operations. |
+| New | API | Added support for [Webhook Notification](../pdf-services-api/howtos/webhook-notification/) in PDF Properties. |
| New | API | Added support for [External Storage](../pdf-services-api/howtos/pdf-external-storage-sol/) in Extract PDF, Split PDF, PDF Electronic Seal and Auto-Tag PDF. |
-| New | API | Added support for [Lists](/overview/document-generation-api/templatetags/#insert-list-using-ul-and-ol-html-elements) feature. |
+| New | API | Added support for [Webhook Notification](../pdf-services-api/howtos/webhook-notification/) for external storage operations. |
### 2.3.1 (March, 2024; patch release)