diff --git a/src/pages/overview/document-generation-api/gettingstarted.md b/src/pages/overview/document-generation-api/gettingstarted.md index 0a57a33fa..5c5c61177 100644 --- a/src/pages/overview/document-generation-api/gettingstarted.md +++ b/src/pages/overview/document-generation-api/gettingstarted.md @@ -143,7 +143,7 @@ The sample below generates the output document in the **PDF** format. Similarly, Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to understand how to use our APIs. - + ##### Java @@ -290,56 +290,87 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u // Run the sample: // node src/documentmerge/merge-document-to-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(); - - // Setup input data for the document merge process. - const jsonString = "{\"customerName\": \"Kane Miller\", \"customerVisits\": 100}", - jsonDataForMerge = JSON.parse(jsonString); - - // Create an ExecutionContext using credentials. - const executionContext = PDFServicesSdk.ExecutionContext.create(credentials); - - // Create a new DocumentMerge options instance. - const documentMerge = PDFServicesSdk.DocumentMerge, - documentMergeOptions = documentMerge.options, - options = new documentMergeOptions.DocumentMergeOptions(jsonDataForMerge, documentMergeOptions.OutputFormat.PDF); - - // Create a new operation instance using the options instance. - const documentMergeOperation = documentMerge.Operation.createNew(options); - - // Set operation input document template from a source file. - const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/documentMergeTemplate.docx'); - documentMergeOperation.setInput(input); - - // Execute the operation and Save the result to the specified location. - documentMergeOperation.execute(executionContext) - .then(result => result.saveAsFile('output/documentMergeOutput.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, + DocumentMergeParams, + OutputFormat, + DocumentMergeJob, + DocumentMergeResult, + 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}); + + // Setup input data for the document merge process + const jsonDataForMerge = { + customerName: "Kane Miller", + customerVisits: 100 + } + + // Creates an asset(s) from source file(s) and upload + readStream = fs.createReadStream("./documentMergeTemplate.docx"); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.DOCX + }); + + // Create parameters for the job + const params = new DocumentMergeParams({ + jsonDataForMerge, + outputFormat: OutputFormat.PDF + }); + + // Creates a new job instance + const job = new DocumentMergeJob({inputAsset, params}); + + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: DocumentMergeResult + }); + + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.asset; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + + // Creates a write stream and copy stream asset's content to it + const outputFilePath = "./documentMergeOutput.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/Document-Generation curl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \ @@ -374,16 +405,13 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/document "photograph": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP88h8AAu0B9XNPCQQAAAAASUVORK5CYII=" } }' - -// Legacy API can be found here -// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration ``` -#### Rest API with External Storage +#### REST API with External Storage ```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/Document-Generation curl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \ @@ -426,9 +454,6 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/document } } }' - -// Legacy API can be found here -// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration ``` As a result of the Document Generation API, template tags are replaced @@ -439,18 +464,18 @@ with the input JSON data. #### Generate PDF or Word document (with [Fragments](./fragments.md)) -The sample below shows the use of **Fragments** in the word template and generates the output document in the **PDF** format. +The sample below shows the use of **Fragments** in the word template and generates the output document in the **DOCX** format. Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to understand how to use our APIs. - + ##### Java ```javascript // Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples // Run the sample: -// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.documentmerge.MergeDocumentToPDFWithFragments +// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.documentmerge.MergeDocumentToDOCXWithFragments package com.adobe.pdfservices.operation.samples.documentmerge; public class MergeDocumentToPDFWithFragments { @@ -531,7 +556,7 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u StreamAsset streamAsset = pdfServices.getContent(resultAsset); // Creates an output stream and copy stream asset's content to it - OutputStream outputStream = Files.newOutputStream(new File("output/documentMergeFragmentsOutput.pdf").toPath()); + OutputStream outputStream = Files.newOutputStream(new File("output/documentMergeFragmentsOutput.docx").toPath()); IOUtils.copy(streamAsset.getInputStream(), outputStream); outputStream.close(); } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) { @@ -547,8 +572,8 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u // Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples // Run the sample: // cd MergeDocumentToDocx/ -// dotnet run MergeDocumentToDOCX.csproj - namespace MergeDocumentToPDFFragments +// dotnet run MergeDocumentToDocxFragments.csproj + namespace MergeDocumentToDocxFragments { class Program { @@ -589,7 +614,7 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u // Create a new DocumentMerge Options instance with fragment - DocumentMergeOptions documentMergeOptions = new DocumentMergeOptions(jsonDataForMerge, OutputFormat.PDF, fragments); + DocumentMergeOptions documentMergeOptions = new DocumentMergeOptions(jsonDataForMerge, OutputFormat.DOCX, fragments); // Create a new DocumentMerge Operation instance with the DocumentMerge Options instance DocumentMergeOperation documentMergeOperation = DocumentMergeOperation.CreateNew(documentMergeOptions); @@ -601,7 +626,7 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u FileRef result = documentMergeOperation.Execute(executionContext); // Save the result to the specified location - result.SaveAs(Directory.GetCurrentDirectory() + "/output/orderDetailOutput.pdf"); + result.SaveAs(Directory.GetCurrentDirectory() + "/output/orderDetailOutput.docx"); } catch (ServiceUsageException ex) { @@ -640,81 +665,112 @@ Please refer the [API usage guide](../pdf-services-api/howtos/api-usage.md) to u // Run the sample: // node src/documentmerge/merge-document-to-pdf-fragments.js - const PDFServicesSdk = require('@dcloud/pdfservices-node-sdk'); - +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + DocumentMergeParams, + OutputFormat, + DocumentMergeJob, + DocumentMergeResult, + 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(); - + // 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("./documentMergeFragmentsTemplate.docx"); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.DOCX + }); + // Setup input data for the document merge process - const jsonString = ` -{ - "customerName": "Kane Miller", - "customerVisits": 100," - "itemsBought": [ - { - "description": "Sprays", - "quantity": 50", - "amount: 100 - }, - { - "description": "Chemicals", - "quantity": 100", - "amount": 200 - } - ], - "totalAmount": 300, - "previousBalance": 50, - "lastThreeBillings": [100, 200, 300], - "photograph": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP88h8AAu0B9XNPCQQAAAAASUVORK5CYII=" -}`; - - jsonDataForMerge = JSON.parse(jsonString); - - const fragment1 = JSON.parse(`{"orderDetails": "Quantity:{{quantity}}, Description:{{description}}, Amount:{{amount}}"}`); - const fragment2 = JSON.parse(`{"customerDetails": "{{customerName}}, Visits: {{customerVisits}}"}`); - - const fragmentsList = [fragment1, fragment2]; - - // Create an ExecutionContext using credentials - const executionContext = PDFServicesSdk.ExecutionContext.create(credentials); - - // Create a new DocumentMerge options instance - const documentMerge = PDFServicesSdk.DocumentMerge, - documentMergeOptions = documentMerge.options, - options = new documentMergeOptions.DocumentMergeOptions(jsonDataForMerge, documentMergeOptions.OutputFormat.PDF, fragmentsList); - - // Create a new operation instance using the options instance - const documentMergeOperation = documentMerge.Operation.createNew(options); - - // Set operation input document template from a source file. - const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/documentMergeFragmentsTemplate.docx'); - documentMergeOperation.setInput(input); - - // Execute the operation and Save the result to the specified location. - documentMergeOperation.execute(executionContext) - .then(result => result.saveAsFile('output/documentMergeOutput.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 jsonDataForMerge = { + customerName: 'Kane Miller', + customerVisits: 100, + itemsBought: [ + { + description: 'Sprays', + quantity: 50, + amount: 100 + }, + { + description: 'Chemicals', + quantity: 100, + amount: 200 } - }); + ], + totalAmount: 300, + previousBalance: 50, + lastThreeBillings: [ + 100, + 200, + 300 + ], + photograph: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAZuElEQVR4nL1de7gcRZX/neqeme65l7zuzRsijxgwBJJAghBBXQ0PkeCCD15+i+7qqkvg81v8dkX9Y1fYBZUVBVzQRR4rEXCVh8AniisQFJIQlIsIeQAxkoQ8bp7ce+fR3XX2j+ruqZ7q7um5N+z55ruZ6T516lTVr845daq6Q+sO6Z0B8hkABBRJAAKEiNR1otYVnYi178QxJzOn8kecLR7mlmROryTklIkrFPNLg1+ivXbFybJVu8/t5fRSUteEBTPb2c0ZDYWNBwBktDrilIozj1dJyxqk0emm6pJSdlbRoNTOEgCYJSJFVf8LDSl6A3QsEAtEnZWHq0hPzugIHZVBAqEC8fgXwFQCp7KFZR01IeI4E1OhTErvrM6UNeaqmiIDZnLmT9uwFLe6KUurbvFSnBKdpY+SoBZGLLTbi5DHwFpxPbO6SRo8um3qgCYTL6GFAoAgi8fEFIvWFQ2nhZAlC9iOIrgwKV+m5M7WLwtNSQuVz1OUbAlIlkwCSb8W2iklVEOZ8pIEibQR1kkYV1L41TBoJRJeTLOYJmWhKQKMEt/ZQoXSNEyZnlTVYkc6K6U7T6MQZTiYfipCUFGLk4+mIq3oVrLS0A7vMRD1qB5hpdipcNhaWAMCAMQW2rykroReMQKAAUu7RqEK1AlHITvQ5um4ZTFVWCA1G6exZFsohURtcun8SqsUm9V9dNNqttRNvi5TZ6f2CSoJlA2pfB+noym0TflyRlWLIlsyJEj1IoW9C0ThYujjDFuWQmObkRxHZ6ZNMa2S+m7G4ubELBhDtZU1MKXsaQdvGFbDLbXePtKj/w76hJTn6dL4M+5mWCiTbA6LCCRnrI4mHWs66bgrHogmFE2Ia69RJx1HqmhW3GTKL44maaxAiSwAAUu0Iatba6XjLj+MGB1l4YhbFzqWyrhbGE36dRvguKgyk+FSnDQzZpCJu+Kk6kuWagWQuvFR+vi5gUXCKum2dQxoSkZ8yQie41W4kqC7/4zF81iIBTh2JmEjBQCQjFuQ8Gu51RaJwrtFUxbZyg1JY5yFZABCUPIy9CFMdF8GBtXQJ5qkDWKIZTCAgLVqzA4SLTmZ8XcooBU3dYumrPg+aAWl2WRGLln4yhphM55m3e6oK5G7zdNEzc8CUMgKOyI53cVi+hVbqmGhsMNbQjM1b/GIDH6h1RiQYfpTJOuFCQAFzIBMmMbW1y5wpIkfHZp0siVYMksQkgudIpTVodkd3ZmYGYxApacL8seUpc8Y0KSTDSLi5MhopCadUDPASsF0jhIQxgRUoQmDWME5DlaAphc0PQJIWHArACi108eEo1AtpHk6RSaaImkEwI48eXp7VWN8AqJJp7v8fCQqDxuuVamlm7pK0U8CvKGR5oyZlaWn+7YVrHmWXnrZKZdQLptqHTQcmSFIhzhLdRYITNKwLMLQSndWoaAC9tYsldCTqDk0zB8+e8attwbDw1QqO4fN3P397x+46quu14Bdaa+lSxyp+FtJyOqmfDTpBcwMXSZJGo0xyi1F3Gj4c+bMXHH3nltueXPe8VuPnTv4n7dMXX7F+O/dWPd8BEHHMEoy50BJ3VWkX2eNisuktb3VaUzSWOWl8Y5hSaNltaOuYwDe8HDv9ddXTlmy7T1Lespl9rza+HEzXxzoOewdr59zjnj0UdHToxcLLU1xHBlk4ii5ojQGVqggWe2l6sWYmTkAB4muT0pn0d1Hk6zLlwwOZNO2y6ed+taDD5QBWSrDdXnf/sbq1QDG/82lTSKKalejPToc6Trkl027LmW0F2uHDsqYz4n+jtKI4a+uKEyVpV2W0ho3zu7rq73yigCIwAQCeNcggOopp+yePDnYu5fLpbYqWRvjZJRkRPbQ72qkWTo1oqHLMfMWsVPqymYdfGLJPb2WZYv9e1kgYBkOrhAAKtOniVmzpO9lDU6+3RkdjvLL2pIgo3shCLrcASxCeiQeg5iZJYEIDBmwCmAoIGDiJADCtoMpky0GgzhaNSUQVMSvaTMmsnftPs5Ek2kNFY+tROj7w9H+zcEk1v4N8+UALEGNOnvNwO1VoR6xlLZNU6cpbulUPCjFOHOdXngfO4qXulvb6ndtADKKpFnv744qjIKIwaQsDhGRgDc0Uq/VacpUZjAJyMAaP945dEbIX28yYBlBc6YlCmsBWsGkiC8lwmNdgmaVdGJ9YyWZdRBqgVGozaMmtmLISmYBksPDvHNnz+yjDgDELJtNmja9PGOm0k8cOACAwdQeu+fnJwqEyoV59CyL2pFWmyusT778VB8l51U3ammJCsEW2Nu40Tl27m7AAktm65hjbNdlwB8Z4cE9JASzsVQwfLdMxEd59qgIjnSdA80oZXpDziUVK5kRmUlZ8lWLBXBgzVr7mGOk45LHPtC7YIFSztuxg3fthG2ZGyVRB3WOvPS2FOHJ4lS1COYwKzI66soPSG1IA4ZkImHVV68qTeq3Z8+WzYYnqLToRMVQ27ypsX+vEJbagGUCEyQo/gAi/qi7EARBESfLqAdkVHX84VCgYBKRtJaG4YcgIzlKcnTWYZSnYFTZ7jhlNMEZTOWyt3Fjc8dO5wN/1Xjpj/b0GT0LFkhAAP4r6+AHfrkMZuUakO3LFHWfTc1j1QGrJKsxERJgo/sP+iesWI0VAQJsk+V5Q0/8euKyc2qAvWChO3Wa6o+hgQEbiLBDBEERgvRPAkEMySn1KgQlcSRUmq7FE/YAx5+4W9XMZN1mvS2xQjZJZilZSraI9t5/f+/8+d6kvt4lS6C8su/VXhjIyfcXsInd8Zu2z+S3wQhYBlpfjSWC17MCsbz2L5z4KcpObfXaxhtbxn/+c87Ji9XFkdc3ees3OKUyU0saRW4wP8DJ8mspZwr1VYGRiTdP6aTs7owlgo+iZJ2EdkerRWVfGWwJq+HtvOPO2dddG5+1Hl6zWu7fJ10XcdZBk9VBhwL76mGyUOPMB6m6KwKQ1NxK6FGSV4p/9LKRmWAm1v1U6LnCLmAJtuzSvnvvbQzuKvceojpl/1NPWYAkarN3ynYwsSaqZYmiDyQQMAexH9T8mqlDOD91UwjiSFrACDiU8P+UdVBZoYTtUB8FOUsEe3c33tiqtPGHR0Z+94ww9jugmg1VlJkFsyhiuXR7pGuSxZ9l42wJSHQItDpurKYnurTf+VYmaDbKJ54w8aTFAASw97lVjY0beyqODI2nFpFr2wdZJz/T7GbripF0CC8l1psZMzjlaLcJtvyhSxwIz+HLJo/R/+FlVC6rn3sefdTy/aBc0dONRU5aSG1zv4glUsRaTiKfws7SGzyWxXR8tIPT4Bb5qYQbEL4vXXfiR5bFbD3z5g8CtpQs2tf9YRkijgLFrE5J4ChxgxC5l3wchQkrjfNtsVlxjqxlmBNEzBT/aDbq5XefNG7BQsX51muvTjz77N4Pn+3Xa6knFSRzwDKIZEsppUxaw3zdCnNK5nC7PuK0JViC2DgUOzpKaNBa5EdJFRUlaXk8AWoAMz/+MSKhVjlbrv+2cKtHfve7Lzz5pNtscqkUCSDo9ijNypqRkWLSo8h8HOmcMpwG+jMAUfVjpHQVjMa0pVLY86h/ct+yc1X5oF4ffvKJHTfegEDO/Po1Nc+L2XUEmZLN3cludSuSvbCjgGLMqx2tpgxDEWfOW2a44TXGnXVmz2Gz1Mpr8Kkn6xs3OIFc/7m/X/j444MPPdhcubJUdWPZnDCHRl5XMiIrk48gTmRTAUCacytcLejz4G0gPdMUWpnWcldBRAJAIKUQ0y65OC646yf3WYG0HGf4yac233jT3LtXNMeN40ZTNU9SSq5RR1CRPXPTEmWRiUr6VU+1nzM9YL4D7vZgW9t1rtd44fwTn1ltVSoAatvf/MPChaXBXShXyPOHiBauWT28fsPGCy7ocSqSLGrzYkUoBUGqbm2HXGtj1gxTSOyArBYKUu+GiQMpI7yYvinLdhBQZ/RfdLFVqagbux54INi+g0plALJcdprNly64aOpHlk39xy8O1xtU2PokNeyMoPx9bEXqri2ZmSk/gjelmPGL6YiyxREA9po0pX/qhRcp+VLy4I/vsQFmYoYkSW5Vrl83cOElJzxw/9Ar62u/+EUlNF7tnQ6KghVDT2miwbBEegNSzt9rO4kHzWaFi9UCVoOZwdz0/fEfOa/n0MMkIIj2Pb1yaNUqqpSDSAKDy45z4MEHXvnKVQvv/5k1f2FzpEbG9iEzcyBZSg4CkpKkWmXn1d4RoVk8cVq525RM+9xUT0fLlteLruseKrwE8n3PqRz22c8iguTW22+H76PkRiwAAEFupbLt2uvcmTMWPfG/q5ac7K3bICzhB5KjDIQfukdiSz2dKNVRCAJKANk2l0vp6bVOONJXIKzvG3ZtDjhlBYm2bqLWwqKNmp437kPnTFi8WOk09OrGfT9/qBzFnwACAgBLMktZAdYtvyLwggWPPPzC+R+nPXuq8461Dz9i/KxZ9rSplQnj0dOLag+VSpDMDQ8jBxqDu0c2bNj9/HP1tc97g7srgOW6KUGsHu6Yz3tLGbdI3bMDIADJrN3xTCq6QDXLCZY+0czlywEELC0Sm2+5hfcfQLXKYJJg3w98rwkwUJo0oTzn6BnzjhOuM+6oOacODNS2bmvueFPWm3LHtpGdOw+89HJ9356g3giCgCBKlXKlb1Ll0MP6zzn3nV//en3Pnjd/8tMtP7ilNvBixXHiY666bjqOklZPxDfCLnu06k5mEYxp+VyU1KHbYLjmfOCDJzz+OBERYfiNN55bdGJ51yAzB0ADKE/ury6YP+G0949fcnLPUUfZlfLIzsHaKy8PPvFE9bjjjlx++XOf+vT2u+50AQFY0U56DAxWyT/AWbTo+B/eNun4+c2hAy9f9dUdN99cccokLKR1VtrQtg5+KwqnoV5Tt9YrZebr3zmMusMbgWwQ5nzpS5YgVdfmb36ztnOXLNmVuXOnLD190ukf7D12HoQY2bDxwOpVm2+6sTkwUNv6JnueDWwHan96edHNN22a+67XvnKVFciS63L0eKiMdsqIGeD62rUvXHzxac88Wx43bsFNN63+y+a3fv6wVXWRtERm1+iRl34yJ0SWz0FmZ5DWer1TO3eWSpK0bgsmv1ZzT//A4l/9Wsna/+prA5cvn/n+9/WdfXZl6rTa1q37n16561ePjzz/+8b2Ny11QFgIYdssBIiIuVavV087df5dd/p79v9p+WVDq1a5gHBdicTimojID0Ykn7Rm1aSFJwDY9tCDA+edXymXOPKp5l6BtiwLF3D6jLN9wCcOou2DNmjF6ywFA62LCsQcFAChKyAigDnwmkRH/9OXAQokW4J6Dj/8xFtvHXr1tTduv2vvLx+rb1hHgbQBy7KrjsMU1sxxM4icarX+9G+fOeHE2d+4bvEvH9ty332brr2uuWlTBbDLJRaCo/yE9Jro63OmTAmbeugsaZUgAUvolihsadg/ebbY2N3JmITdPicHAOGLbhgA+0HQrA8Dky+6cMrS0yVAgoY2vb7uX/51aOXTjT9vEkCJyKmUUA6fuGbtb0skM4Nt17HeGlr/uS9s+9GP5lx9zanPPbf9kUe23H770KpnZb2h9ksCoAkc/c9fdmceqgDQWL9B+k1UnHY1C2RKFQ89VHWnQKScmcsqpn/XY5Y0CQRC0Gw2/YBwyNLTp19yyfSPnl/pPUTdXXP++XseeMAVFlXKOYOhS46yYwAIzH6t7gHjz1h6+GWXTzplSWP3rr0rVw6uWVvbvbd32uQZHz1v2tIzVIn63t2rz/hQ/fnnyalkaZtKUawvANCDrjsZ5HMyLOUMm9/Gld1CAtj3m57HbrX/gk8cvvwye1K/1dvrTu4HMxG9+egjA+cs66lUWAjtKTvdQCZfGwWQir84PC+sbDEke82GBzhHHjHprLOmLT29+q53VQ+dUe4dB8BvevVdu/b8duX6b37D+/0LZcfJts0AUiKvRGfd7zpTIIIOMMyS3Qpz9SiVgqDZaAY91amXfurIK66wqtXNt/3XG4/+YvG9KybMnkOANzz8zJL3BC8OWK6ru8r4b5xrb3UW6/GQXhkYJKSUzYbPHADkuvbkvtKEPqtS8ev1xo7tzZ07S4DtODmN1DtFJz3/Nab3Z6lnUgENDdHU6PvkJ4/+2tdEpfz6Td/b/sPbhvfvX/iDH0yaPUcyE9Gr375++MWBHrfCGjrDc61qoRsePGtZk+iFTO3IUHyBIDiOBdjM7Pvyja2Nv2wJV7+W5VYqbK4qYzAX2LsOdfhZ1ZkMUegpnPwNbkD4wYjnVRedOPeGG3rnHP3ad76z9Zabse8tBsYtO/eUnz9EzCDaOzDw7GnvcWp1lEqRTB1P7WObeD9XIvcEhCFVFyF1FoKiCoC2/Jd2M3Nt2N0T0UT+SK1hW0ddc/VRX7xiy09++vsLLwy2bnNKgi3yJvTN/Y9vMUBE0vP+ePnl4q1hdircSg+ko8YkE3FFvFjxFuUnv2wCGCksHZTQvhO4OVLHO2adfO99lSmTV5133v7Hf+MCtltBIIcD77hvfWPCO+eoIq/8+9X7n3666rh6+Bdu/STeWgXEqBmVOY2eRjTPVFH8R4/js7CZWO5IRoC0dGKnSRdmRoBmvVFeuOCUxx7b9btn1px1prX/QI/jqDPc9aY3/dJLj/j03yrntf03v3793651SyVOej3zxF4R1EQs7YnvLvauFX/nWqIUjQybXHTStXqaQIygXisfd/x7n3zy1dt+uP7KK3uEIJU8gNUcGa4cP//4G25QOg39ZfMf/u4zJc+H43KHd+ykUDK7JBEupDjKDbTrrz+Lk2WDoMkMKXzGX9XC2m3CWLwhA/D9Zm/vyff/z6Yf37vuyit77BJsW7IkkF8b9vv7F6+4uzJxIgC/NrLmU5fKP28uuZUgdYM0pyI1TTRfGS+cU8dYLd3IeMa/CMlEB7XrYDMQUKZp5WiPPx7YGBEE1H3viC9+GYF86fLlVcuStqXqkfVaw3VPuvtHffPmBYBgXvvZz7z1xFOu47RNbh0vUY0xamCiJuEZjaUv6zYuf6qYCEK7KilP36tsc370n278JLNlTT//r1+79fsl3yfHZTAR/Fq9UXUXrlgx48yz1I78msv+YceKe3oqlUAzVSZeIlsTo6YDScMnFvff+QjKorEEpcxEolRp1ms+4LCUQVD3fTFj+rvvuGPGGWcywI3G2s9/Ycudd/SUS9FOfNSiDLxEjyemoKaF7qSkVlntcpTObkVVxRGki9etXhe7O22bgJLAvr/tofvnXfUVmnXY7kZjuGT3XXTR+57+3YwzzgQw9OdNK89dtvXOO3oqDkTnigIKzQ3S9rRV8rNI8KnvMOkndrLakinHeIKDVjiVvryzDtnPqwDC92tle9E99/S/9737XnrpkFnv6J01C4BXq23677s2XH2Nv3WrW3ElEYWJwERxpMG+SHeEY669ncYMIEzqkFkx/KZOId5H3VkAiCCbXgM89YJPHHr+x0rTpnq7B/eseW77ww8Pv/iiQyDXVU+hs3G0LMvKyLbMQ5bq8aqS0yWZkVd+Z+Uv+MLOutup9Cde4pDClCkirCfwGs1mFCBaQAmwnIoEMXG3acMs1IQ15ofKyllldbeeAc5FUPSj3dKFycysELHYokdYjtPDDGYQsXbqbBQJ1sTRj05dE39X74iJDn2kq93t27LMgbGZIJmDsbxIjAAgIGoLo9WyQN9kjXIGAUCJJ2Ey/JSJqUyLpiRoz0FlnbdJyWFob/PWaze3hw/y++B1ksZkiKIbyrFLozgq0yormRG92yfsvVwNZXq0lUXJ92flqxI2Ix5dSsk9mRjJNR6hxC7PWyGrlBaXJXaSdQQZFif/JEv7JisXVDfF73Qoxa1S6SQFFR9YdG93EqW6LKrv+qjutqVabBQS1CH9SsUcf1uxWLD+/t2MTomi8oi/zSaG/isLO4URFM4PUm/aUpeAcG04+qd+gcgTcRh3jkaU1A1MrgNMlGpl8VK8Z/zUWUcyEZRFNpB47Go0pDdVa3ByjdZSK1MMWhJUI8PuiPPu0XM3Onaib4Q062OuOrM0Cc8Iak7VxPhB84asv7ctoRYQ56EKxyeBhprIZ8WPsnSB3SK5LSYrkhySns/QKXoffBt7m7giZtWw+2xgzTyjEl1N91P67yInyLLe4qA/P2I+z5oSkRl6Rsk/Zo6PRShOHQXcTZYom2TrXFicUVbtMEa1sK3Rqch5hRStOM/MmjsDtiSovXDTDLQuGFGvrmJUxIi5OiBFc4GmornWp732Fmn+S2mr/fXNhmXIzHj9SOoz0nqrNdsR3k10QTo6EtI6IKVzpGGixvRZyu6YMZs0G58hv4gOdqCOUeVmKLJu5aMjyQmkZtwzykYNaM/B61EPwsM0LfkpzU61km3NNbpSmpnV1u5OcsOiW3tRnAINZVlWptt3g+fbnYjHeJNI/qTOUKF1pjTmTeQJjAKmUkXSMLpvip564CgxkYzytEgnRg23ydEpo3b1RGKW9YF+at9cxmmTV2h+vEOcFRiq6LiI1EqnDv8DFMX/p0qKgIStifo5R1xKkEmJjE07Zxj+dR7nIFoiIDwHz2TaDjO/Eyqh25HE/w/Y7omSZoG071FjIqYieEnAItdnhRdSsKOxal2Q3Itsr0WnsZ3PaqEjxRPpJA2LUDxvNUrOwtjRqcMpGmYwWBrQynr5UiKMyEdHRjGKDs20sURrfeTZmkQB9fSyD0CGW7MGSDKsT0vvdi/ZrrTuSTORlZPSb1kSbSlQ3IvlPMAYqpv9liwTOwHZ6IRrRbr10aVJQQCsDAG6tv8HcAoVaSJluIMAAAAASUVORK5CYII=' + }; + + // Create fragments from fragment JSON data + const fragment1 = JSON.parse("{\"orderDetails\": \"Quantity:{{quantity}}, Description:{{description}}, Amount:{{amount}}\"}"); + const fragment2 = JSON.parse("{\"customerDetails\": \"{{customerName}}, Visits: {{customerVisits}}\"}"); + + // Create parameters for the job + const params = new DocumentMergeParams({ + jsonDataForMerge, + outputFormat: OutputFormat.DOCX, + fragments: [fragment1, fragment2] + }); + + // Creates a new job instance + const job = new DocumentMergeJob({inputAsset, params}); + + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: DocumentMergeResult + }); + + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.asset; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + + // Creates a write stream and copy stream asset's content to it + const outputFilePath = "./documentMergeFragmentsOutput.docx"; + 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(); } +})(); ``` -#### 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/Document-Generation curl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \ @@ -723,7 +779,7 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/document --header 'Authorization: Bearer {{Placeholder for token}}' \ --data-raw '{ "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718", - "outputFormat": "pdf", + "outputFormat": "docx", "jsonDataForMerge": { "customerName": "Kane Miller", "customerVisits": 100, @@ -757,16 +813,13 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/document } ] }' - -// Legacy API can be found here -// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration ``` -#### Rest API with External Storage +#### REST API with External Storage ```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/Document-Generation curl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \ @@ -817,7 +870,4 @@ curl --location --request POST 'https://pdf-services.adobe.io/operation/document ] } }' - -// Legacy API can be found here -// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration ``` diff --git a/src/pages/overview/document-generation-api/quickstarts/nodejs/index.md b/src/pages/overview/document-generation-api/quickstarts/nodejs/index.md index defe2c436..c975de52f 100644 --- a/src/pages/overview/document-generation-api/quickstarts/nodejs/index.md +++ b/src/pages/overview/document-generation-api/quickstarts/nodejs/index.md @@ -10,7 +10,7 @@ To get started using Adobe Document Generation API, let's walk through a simple 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. @@ -116,28 +116,22 @@ Notice how the tokens in the Word document match up with values in our JSON. Whi 3) We'll begin by including our required dependencies: ```js -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); -const fs = require('fs'); +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + DocumentMergeParams, + OutputFormat, + DocumentMergeJob, + DocumentMergeResult, + SDKError, + ServiceUsageError, + ServiceApiError +} = 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 = './generatedReceipt.pdf'; - -// If our output already exists, remove it so we can run the application again. -if(fs.existsSync(OUTPUT)) fs.unlinkSync(OUTPUT); - -const INPUT = './receiptTemplate.docx'; - -const JSON_INPUT = require('./receipt.json'); -``` - -These lines are hard coded but in a real application would 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: +4) 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=` @@ -146,109 +140,153 @@ These lines are hard coded but in a real application would typically be dynamic. - `export PDF_SERVICES_CLIENT_ID=` - `export PDF_SERVICES_CLIENT_SECRET=` -4) Next, we setup the SDK to use our credentials. +5) 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 +}); -This code both points to the credentials downloaded previously as well as sets up an execution context object that will be used later. +// Creates a PDF Services instance +const pdfServices = new PDFServices({credentials}); +``` -5) Now, let's create the operation: +6) Now, let's upload the asset and create JSON data for merge: ```js -const documentMerge = PDFServicesSdk.DocumentMerge, - documentMergeOptions = documentMerge.options, - options = new documentMergeOptions.DocumentMergeOptions(JSON_INPUT, documentMergeOptions.OutputFormat.PDF); +// Creates an asset(s) from source file(s) and upload +readStream = fs.createReadStream("./receiptTemplate.docx"); +const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.DOCX +}); + +// Setup input data for the document merge process +const jsonDataForMerge = JSON.parse(fs.readFileSync('./receipt.json', 'utf-8')); +``` -// Create a new operation instance using the options instance. -const documentMergeOperation = documentMerge.Operation.createNew(options); +7) Now, let's create the parameters and the job: -// Set operation input document template from a source file. -const input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT); -documentMergeOperation.setInput(input); +```js +// Create parameters for the job +const params = new DocumentMergeParams({ + jsonDataForMerge, + outputFormat: OutputFormat.PDF +}); + +// Creates a new job instance +const job = new DocumentMergeJob({inputAsset, params}); ``` This set of code defines what we're doing (a document merge operation, the SDK's way of describing Document Generation), points to our local JSON file and specifies the output is a PDF. It also points to the Word file used as a template. -6) The next code block executes the operation: +8) The next code block submits the job and gets the job result: ```js -// Execute the operation and Save the result to the specified location. -documentMergeOperation.execute(executionContext) -.then(result => result.saveAsFile(OUTPUT)) -.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); - } +// Submit the job and get the job result +const pollingURL = await pdfServices.submit({job}); +const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: DocumentMergeResult }); -``` - -This code runs the document generation process and then stores the result PDF document to the file system. -![Example running at the command line](./shot9.png) +// Get content from the resulting asset(s) +const resultAsset = pdfServicesResponse.result.asset; +const streamAsset = await pdfServices.getContent({asset: resultAsset}); +``` -Here's the complete application (`documentmerge.js`): +9) The next code block saves the result at the specified location: ```js -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); -const fs = require('fs'); - -const OUTPUT = './generatedReceipt.pdf'; +// Creates a write stream and copy stream asset's content to it +const outputFilePath = "./generatePDFOutput.pdf"; +console.log(`Saving asset at ${outputFilePath}`); -// If our output already exists, remove it so we can run the application again. -if(fs.existsSync(OUTPUT)) fs.unlinkSync(OUTPUT); +const writeStream = fs.createWriteStream(outputFilePath); +streamAsset.readStream.pipe(writeStream); +``` -const INPUT = './receiptTemplate.docx'; +This code runs the Document Generation process and then stores the resulting PDF document to the file system. -const JSON_INPUT = require('./receipt.json'); +![Example running at the command line](./shot9.png) +Here's the complete application (`documentmerge.js`): -// 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(); +```js +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + DocumentMergeParams, + OutputFormat, + DocumentMergeJob, + DocumentMergeResult, + 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 + }); -// Create an ExecutionContext using credentials -const executionContext = PDFServicesSdk.ExecutionContext.create(credentials); + // Creates a PDF Services instance + const pdfServices = new PDFServices({credentials}); -// This creates an instance of the Export operation we're using, as well as specifying output type (DOCX) -const documentMerge = PDFServicesSdk.DocumentMerge, - documentMergeOptions = documentMerge.options, - options = new documentMergeOptions.DocumentMergeOptions(JSON_INPUT, documentMergeOptions.OutputFormat.PDF); + // Creates an asset(s) from source file(s) and upload + readStream = fs.createReadStream("./receiptTemplate.docx"); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.DOCX + }); -// Create a new operation instance using the options instance. -const documentMergeOperation = documentMerge.Operation.createNew(options); + // Setup input data for the document merge process + const jsonDataForMerge = JSON.parse(fs.readFileSync('./receipt.json', 'utf-8')); -// Set operation input document template from a source file. -const input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT); -documentMergeOperation.setInput(input); + // Create parameters for the job + const params = new DocumentMergeParams({ + jsonDataForMerge, + outputFormat: OutputFormat.PDF + }); + // Creates a new job instance + const job = new DocumentMergeJob({inputAsset, params}); -// Execute the operation and Save the result to the specified location. -documentMergeOperation.execute(executionContext) - .then(result => result.saveAsFile(OUTPUT)) - .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); - } + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: DocumentMergeResult }); + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.asset; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + + // Creates a write stream and copy stream asset's content to it + const outputFilePath = "./generatePDFOutput.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(); + } +})(); ``` ## Next Steps diff --git a/src/pages/overview/document-generation-api/quickstarts/nodejs/shot9.png b/src/pages/overview/document-generation-api/quickstarts/nodejs/shot9.png index 39aaa5a63..0c7e508e7 100644 Binary files a/src/pages/overview/document-generation-api/quickstarts/nodejs/shot9.png and b/src/pages/overview/document-generation-api/quickstarts/nodejs/shot9.png differ diff --git a/src/pages/overview/images/node_free_tier.png b/src/pages/overview/images/node_free_tier.png index 8a8e560c6..b1113333e 100644 Binary files a/src/pages/overview/images/node_free_tier.png and b/src/pages/overview/images/node_free_tier.png differ diff --git a/src/pages/overview/legacy-documentation/document-generation-api/quickstarts.md b/src/pages/overview/legacy-documentation/document-generation-api/quickstarts.md index 9fae4c60f..af53592a1 100644 --- a/src/pages/overview/legacy-documentation/document-generation-api/quickstarts.md +++ b/src/pages/overview/legacy-documentation/document-generation-api/quickstarts.md @@ -84,7 +84,7 @@ Please allow-list the following hostnames before using Adobe PDF Services SDK: + ##### Java @@ -268,7 +268,7 @@ The sample below generates the output document in the **PDF** format. Similarly, } ``` -##### Rest API +##### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -331,7 +331,7 @@ with the input JSON data. The sample below shows the use of **Fragments** in the word template and generates the output document in the **PDF** format. - + ##### Java @@ -587,7 +587,7 @@ The sample below shows the use of **Fragments** in the word template and generat ``` -##### Rest API +##### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-extract-api/howtos/extract-api.md b/src/pages/overview/legacy-documentation/pdf-extract-api/howtos/extract-api.md index 656fa0191..cb5709d19 100644 --- a/src/pages/overview/legacy-documentation/pdf-extract-api/howtos/extract-api.md +++ b/src/pages/overview/legacy-documentation/pdf-extract-api/howtos/extract-api.md @@ -143,7 +143,7 @@ schema](/extractJSONOutputSchema2.json)): The sample below extracts text element information from a PDF document and returns a JSON file. - + #### Java @@ -360,7 +360,7 @@ namespace ExtractTextInfoFromPDF logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -404,7 +404,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below extracts text and table element information from a PDF document and returns a JSON file along with table data in XLSX format. - + #### Java @@ -625,7 +625,7 @@ namespace ExtractTextTableInfoFromPDF logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -668,7 +668,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below extracts text and table element information as well as table renditions from a PDF Document. Note that the output is a zip containing the structured information in a JSON file along with table renditions in PNG and XLSX format. - + #### Java @@ -891,7 +891,7 @@ namespace ExtractTextTableInfoWithRenditionsFromPDF logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -935,7 +935,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below extracts text and table elements information as well as table and figure renditions from a PDF Document. Note that the output is a zip containing the structured information in a JSON file along with figure renditions as PNGs and table renditions in PNG and XLSX format. - + #### Java @@ -1157,7 +1157,7 @@ try { logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -1202,7 +1202,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below extracts table renditions and bounding boxes for characters present in text blocks (paragraphs, list, headings), in addition to text and table element information from a PDF Document. Note that the output is a zip containing the structured information along with table renditions in PNG and XLSX format. - + #### Java @@ -1424,7 +1424,7 @@ namespace ExtractTextTableInfoWithCharBoundsFromPDF logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -1469,7 +1469,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below adds option to get CSV output for tables in addition to extracting text and table element information as well as table renditions from a PDF Document. Note that the output is a zip containing the structured information along with table renditions in PNG and CSV format. - + #### Java @@ -1696,7 +1696,7 @@ namespace ExtractTextTableInfoWithTableStructureFromPDF ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -1741,7 +1741,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below adds an option to get styling information for each text element( Bold / Italics / Superscript etc) in addition to extracting text and table element information. Note that the output is a zip containing the structured information along with table renditions in PNG and XLSX format. Please see the [Styling JSON schema](/extractJSONOutputSchemaStylingInfo.json) for reference. - + #### Java @@ -1964,7 +1964,7 @@ namespace ExtractTextTableInfoWithStylingFromPDF logging.exception("Exception encountered while executing operation") ``` -#### Rest API +#### REST API ```javascript curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-extract-api/quickstarts.md b/src/pages/overview/legacy-documentation/pdf-extract-api/quickstarts.md index c0d871f02..7528957b7 100644 --- a/src/pages/overview/legacy-documentation/pdf-extract-api/quickstarts.md +++ b/src/pages/overview/legacy-documentation/pdf-extract-api/quickstarts.md @@ -331,7 +331,7 @@ After downloading the zip, you can either run the samples in the zip directly, o 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. diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/combine-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/combine-pdf.md index 3ac8a70c2..ceb53481d 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/combine-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/combine-pdf.md @@ -7,7 +7,7 @@ title: Combine PDF | How Tos | PDF Services API | Adobe PDF Services This sample combines up to 20 PDF files into a single PDF file. - + #### Java @@ -151,10 +151,10 @@ This sample combines up to 20 PDF files into a single PDF file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-combinePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -202,7 +202,7 @@ This combine sample combines specific pages from up to 20 different PDF files into a single PDF file. Optional arguments allow specifying page ranges for each file to combine in the output file. - + #### Java @@ -428,10 +428,10 @@ ranges for each file to combine in the output file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-combinePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/compress-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/compress-pdf.md index 0fb1c960f..999814ab6 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/compress-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/compress-pdf.md @@ -8,7 +8,7 @@ title: Compress PDF | How Tos | PDF Services API | Adobe PDF Services Compress PDFs to reduce the file size prior to performing workflow operations that use bandwidth or memory. - + #### Java @@ -145,10 +145,10 @@ operations that use bandwidth or memory. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-compressPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -183,7 +183,7 @@ compression level, prior to performing workflow operations that use bandwidth or memory. Refer to `CompressionLevel` in the API docs for a list of supported compression levels. - + #### Java @@ -338,10 +338,10 @@ list of supported compression levels. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-compressPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/create-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/create-pdf.md index f41b6e691..10cb4d470 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/create-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/create-pdf.md @@ -22,7 +22,7 @@ following formats: If a Microsoft Word/PowerPoint input file has an embedded TrueType font, the output pdf will also contain the same embedded TrueType font. For more information, refer [Benefits of embedding custom fonts](https://support.microsoft.com/en-us/office/benefits-of-embedding-custom-fonts-cb3982aa-ea76-4323-b008-86670f222dbc#OfficeVersion=Windows). - + #### Java @@ -160,10 +160,10 @@ const PDFservicesSdk = require('@adobe/pdfservices-node-sdk'); } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-createPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -205,7 +205,7 @@ file, the SDK supports the following formats: - + #### Java @@ -386,10 +386,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-createPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -432,7 +432,7 @@ the input file must be a zip file containing an index.html at the top level of the archive as well as any dependencies such as images, css files, and so on. - + #### Java @@ -620,10 +620,10 @@ const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -667,7 +667,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below creates a PDF file from a static HTML file with inline CSS. The file must be local. - + #### Java @@ -855,10 +855,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -902,7 +902,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below creates a PDF file from a HTML file specified via URL. - + #### Java @@ -1091,10 +1091,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -1147,7 +1147,7 @@ manipulate the HTML DOM, thus effectively updating the source HTML file. This mechanism can be used to provide data to the template HTML dynamically prior to PDF conversion. - + #### Java @@ -1353,10 +1353,10 @@ const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/delete-pages.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/delete-pages.md index 27d9d4977..466e9ded7 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/delete-pages.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/delete-pages.md @@ -7,7 +7,7 @@ title: Delete Pages | How Tos | PDF Services API | Adobe PDF Services The delete pages operation selectively removes pages from a PDF file. - + #### Java @@ -192,10 +192,10 @@ The delete pages operation selectively removes pages from a PDF file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/export-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/export-pdf.md index c7f5bb370..e2de7242f 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/export-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/export-pdf.md @@ -13,7 +13,7 @@ such as: - Text files - Images - + #### Java @@ -151,10 +151,10 @@ const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-exportPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -196,7 +196,7 @@ page. Each image file name ends with pages will generate 15 image files. The first file's name ends with "\_1" and the last file's name ends with "\_15". - + #### Java @@ -335,10 +335,10 @@ pages will generate 15 image files. The first file's name ends with } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-exportPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -375,7 +375,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below converts a PDF file to one or more jpeg or png images. - + #### Java @@ -527,10 +527,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-exportPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/insert-pages.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/insert-pages.md index b7a5e1166..aca8bb043 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/insert-pages.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/insert-pages.md @@ -8,7 +8,7 @@ title: Insert Pages | How Tos | PDF Services API | Adobe PDF Services The insert operation inserts additional pages from different PDFs into an existing PDF. - + #### Java @@ -227,10 +227,10 @@ an existing PDF. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-combinePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/linearize-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/linearize-pdf.md index 158277c31..53a8c4ea7 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/linearize-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/linearize-pdf.md @@ -8,7 +8,7 @@ title: Linearize PDF | How Tos | PDF Services API | Adobe PDF Services Linearizing a PDF creates a web-optimized PDF file which supports incremental access in network environments. - + #### Java @@ -145,10 +145,10 @@ incremental access in network environments. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-linearizePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/ocr-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/ocr-pdf.md index c1ed41f63..4c5e27bd9 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/ocr-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/ocr-pdf.md @@ -12,7 +12,7 @@ be `application/pdf`. This sample defaults to the en-us locale. For other languages, see [OCR with explicit language.](#ocr-with-explicit-language) - + #### Java @@ -150,10 +150,10 @@ This sample defaults to the en-us locale. For other languages, see [OCR with exp } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-ocr curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -202,7 +202,7 @@ are two types which produce a different result: unchanged. This type produces maximum fidelity to the original image. - + #### Java @@ -360,10 +360,10 @@ are two types which produce a different result: } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-ocr curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/pdf-properties.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/pdf-properties.md index a1a27f7a1..1f10d9a49 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/pdf-properties.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/pdf-properties.md @@ -7,7 +7,7 @@ title: PDF Properties | How Tos | PDF Services API | Adobe PDF Services The sample below fetches the properties of an input PDF, as a JSON file. - + #### Java @@ -147,10 +147,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-pdfProperties curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -187,7 +187,7 @@ curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith The sample below fetches the properties of an input PDF, as a JSON object. - + #### Java @@ -340,10 +340,10 @@ try { } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-pdfProperties curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/protect-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/protect-pdf.md index aa3384bec..868ed7a39 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/protect-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/protect-pdf.md @@ -8,7 +8,7 @@ title: Protect PDF | How Tos | PDF Services API | Adobe PDF Services You can password protect PDFs so that only users with a document open password can open the file. - + #### Java @@ -172,10 +172,10 @@ password can open the file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-protectPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -219,7 +219,7 @@ the PDF document. Refer to `ContentEncryption` and `Permission` in the API docs for a list of supported types of content to encrypt and types of document permissions. - + #### Java @@ -411,10 +411,10 @@ of document permissions. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-protectPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/remove-protection.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/remove-protection.md index 96b054fe7..07155f91f 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/remove-protection.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/remove-protection.md @@ -7,7 +7,7 @@ title: Remove Protection | How Tos | PDF Services API | Adobe PDF Services Use the below sample to remove security from a PDF document. - + #### Java @@ -159,10 +159,10 @@ Use the below sample to remove security from a PDF document. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-removeProtection curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/reorder-pages.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/reorder-pages.md index 56dc470ab..2a2746b5f 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/reorder-pages.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/reorder-pages.md @@ -8,7 +8,7 @@ title: Reorder Pages | How Tos | PDF Services API | Adobe PDF Services The reorder pages operation moves pages from one location to another in a PDF file. - + #### Java @@ -192,10 +192,10 @@ a PDF file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-combinePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/replace-pages.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/replace-pages.md index e9c3d16be..cf124773b 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/replace-pages.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/replace-pages.md @@ -8,7 +8,7 @@ title: Replace Pages | How Tos | PDF Services API | Adobe PDF Services The replace pages operation replaces pages in a PDF with pages from other PDF files. - + #### Java @@ -225,10 +225,10 @@ other PDF files. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-combinePDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/rotate-pages.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/rotate-pages.md index 55c06b7d8..71a00ebff 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/rotate-pages.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/rotate-pages.md @@ -8,7 +8,7 @@ title: Rotate Pages | How Tos | PDF Services API | Adobe PDF Services The rotate pages operation selectively rotates pages in PDF file. For example, you can change portrait view to landscape view. - + #### Java @@ -239,10 +239,10 @@ example, you can change portrait view to landscape view. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/split-pdf.md b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/split-pdf.md index 78de21fd4..8ae7188a7 100644 --- a/src/pages/overview/legacy-documentation/pdf-services-api/howtos/split-pdf.md +++ b/src/pages/overview/legacy-documentation/pdf-services-api/howtos/split-pdf.md @@ -9,7 +9,7 @@ This operation splits a PDF into multiple smaller documents. Simply use the page count to specify the maximum number of pages of each output file. - + #### Java @@ -178,10 +178,10 @@ file. ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-splitPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -220,7 +220,7 @@ As an alternative to creating smaller PDFs with a set number of pages, you can split PDFs into multiple smaller documents by specifying page ranges where each page range corresponds to a single output file. - + #### Java @@ -425,10 +425,10 @@ ranges where each page range corresponds to a single output file. } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-splitPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ @@ -474,7 +474,7 @@ pages or a page range, you can split PDFs by file count. In this case, the operation creates the specified number of files with each containing an identical number of pages (if possible). - + #### Java @@ -644,10 +644,10 @@ an identical number of pages (if possible). } ``` -#### Rest API +#### REST API ```javascript -// Please refer our Rest API docs for more information +// Please refer our REST API docs for more information // https://documentcloud.adobe.com/document-services/index.html#post-splitPDF curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \ diff --git a/src/pages/overview/pdf-accessibility-auto-tag-api/gettingstarted.md b/src/pages/overview/pdf-accessibility-auto-tag-api/gettingstarted.md index 070036f3f..83eb19e30 100644 --- a/src/pages/overview/pdf-accessibility-auto-tag-api/gettingstarted.md +++ b/src/pages/overview/pdf-accessibility-auto-tag-api/gettingstarted.md @@ -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-accessibility-auto-tag-api/howtos/accessibility-auto-tag-api.md b/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/accessibility-auto-tag-api.md index 6f6ec73f0..faf596515 100644 --- a/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/accessibility-auto-tag-api.md +++ b/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/accessibility-auto-tag-api.md @@ -63,7 +63,7 @@ The sample below generates a tagged PDF from a PDF. Please refer to the [API usage guide](../api-usage.md) to understand how to use our APIs. - + #### Java @@ -190,42 +190,67 @@ namespace AutotagPDF // Run the sample: // node src/autotagpdf/autotag-pdf.js -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + AutotagPDFJob, + AutotagPDFResult, + 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 + }); -try { - // Initial setup, create credentials instance. - const credentials = PDFServicesSdk.Credentials - .servicePrincipalCredentialsBuilder() - .withClientId("PDF_SERVICES_CLIENT_ID") - .withClientSecret("PDF_SERVICES_CLIENT_SECRET") - .build(); + // Creates a PDF Services instance + const pdfServices = new PDFServices({credentials}); - // Create an ExecutionContext using credentials and create a new operation instance. - const executionContext = PDFServicesSdk.ExecutionContext.create(credentials), - autotagPDF = PDFServicesSdk.AutotagPDF, - autotagPDFOperation = autotagPDF.Operation.createNew(); + // Creates an asset(s) from source file(s) and upload + readStream = fs.createReadStream("./autotagPDFInput.pdf"); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.PDF + }); - // Set operation input from a source file. - const input = PDFServicesSdk.FileRef.createFromLocalFile('autotagPDFInput.pdf'); - autotagPDFOperation.setInput(input); - - // Execute the operation and Save the result to the specified location. - autotagPDFOperation.execute(executionContext) - .then(result => { - result.taggedPDF.saveAsFile('autotagPDFOutput.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); - } + // Creates a new job instance + const job = new AutotagPDFJob({inputAsset}); + + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: AutotagPDFResult }); - -} catch (err) { - console.log('Exception encountered while executing operation', err); -} + + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.taggedPDF; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + + // Creates an output stream and copy stream asset's content to it + const outputFilePath = "./autotag-tagged.pdf"; + console.log(`Saving asset at ${outputFilePath}`); + + let 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 @@ -298,7 +323,7 @@ Here is a sample list of command line arguments and their description: - --shift_headings { If this argument is present then the headings will be shifted in the output PDF file } - + #### Java @@ -554,70 +579,100 @@ namespace AutotagPDFParameterised // Run the sample: // node src/autotag/autoag-pdf-parameterised.js -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); - +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + AutotagPDFParams, + AutotagPDFJob, + AutotagPDFResult, + SDKError, + ServiceUsageError, + ServiceApiError +} = require("@adobe/pdfservices-node-sdk"); +const fs = require("fs"); const args = process.argv; -try { - console.log("--input " + getInputFilePathFromCmdArgs(args)); - console.log("--output " + getOutputFilePathFromCmdArgs(args)); - console.log("--report " + getGenerateReportFromCmdArgs(args)); - console.log("--shift_headings " + getShiftHeadingsFromCmdArgs(args)); - - // 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), - autotagPDF = PDFServicesSdk.AutotagPDF, - autotagPDFOperation = autotagPDF.Operation.createNew(); - - // Set operation input from a source file. - const input = PDFServicesSdk.FileRef.createFromLocalFile(getInputFilePathFromCmdArgs(args)); - autotagPDFOperation.setInput(input); - - // Create Options - let autotagPDFOptionsBuilder = new PDFServicesSdk.AutotagPDF.options.AutotagPDFOptions.Builder(); - autotagPDFOptionsBuilder = getShiftHeadingsFromCmdArgs(args) ? autotagPDFOptionsBuilder.shiftHeadings() : autotagPDFOptionsBuilder; - autotagPDFOptionsBuilder = getGenerateReportFromCmdArgs(args) ? autotagPDFOptionsBuilder.generateReport() : autotagPDFOptionsBuilder; - - const autotagPDFOptions = autotagPDFOptionsBuilder.build(); - - // Set operation options - autotagPDFOperation.setOptions(autotagPDFOptions); - - let outputPath = getOutputFilePathFromCmdArgs(args); - // Execute the operation and Save the result to the specified location. - autotagPDFOperation.execute(executionContext) - .then(result => { - result.taggedPDF.saveAsFile(outputPath + 'AutotagPDFParamerterised-tagged.pdf'); - result.report?.saveAsFile(outputPath + 'AutotagPDFParamerterised-report.xlsx'); - }) - .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); - } +(async () => { + let readStream; + try { + console.log("--input " + getInputFilePathFromCmdArgs(args)); + console.log("--output " + getOutputFilePathFromCmdArgs(args)); + console.log("--report " + getGenerateReportFromCmdArgs(args)); + console.log("--shift_headings " + getShiftHeadingsFromCmdArgs(args)); + + // 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(getInputFilePathFromCmdArgs(args)); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.PDF + }); + + // Create parameters for the job + const params = new AutotagPDFParams({ + generateReport: getGenerateReportFromCmdArgs(args), + shiftHeadings: getShiftHeadingsFromCmdArgs(args) + }); + + // Creates a new job instance + const job = new AutotagPDFJob({inputAsset, params}); + + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: AutotagPDFResult + }); + + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.taggedPDF; + const resultAssetReport = pdfServicesResponse.result.report; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + const streamAssetReport = resultAssetReport + ? await pdfServices.getContent({asset: resultAssetReport}) + : undefined; + + // Creates an output stream and copy stream asset's content to it + const outputPath = getOutputFilePathFromCmdArgs(args); + const outputFilePath = outputPath + "autotagPDFInput-tagged.pdf"; + console.log(`Saving asset at ${outputFilePath}`); + + const writeStream = fs.createWriteStream(outputFilePath); + streamAsset.readStream.pipe(writeStream); + if (resultAssetReport) { + const outputFileReportPath = outputPath + "autotagPDFInput-report.xlsx"; + console.log(`Saving asset at ${outputFileReportPath}`); + + const writeStream = fs.createWriteStream(outputFileReportPath); + streamAssetReport.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 getInputFilePathFromCmdArgs(args) { let inputFilePath = "resources/autotagPdfInput.pdf"; let inputFilePathIndex = args.indexOf("--input"); if (inputFilePathIndex >= 0 && inputFilePathIndex < args.length - 1) { inputFilePath = args[inputFilePathIndex + 1]; - }else + } else console.log("input file not specified, using default value : autotagPdfInput.pdf"); - return inputFilePath; } @@ -626,9 +681,10 @@ function getOutputFilePathFromCmdArgs(args) { let outputFilePathIndex = args.indexOf("--output"); if (outputFilePathIndex >= 0 && outputFilePathIndex < args.length - 1) { outputFilePath = args[outputFilePathIndex + 1]; - }else - console.log("output path not specified, using default value : output/"); - + } else { + console.log("output path not specified, using default value :" + outputFilePath); + fs.mkdirSync(outputFilePath, {recursive: true}); + } return outputFilePath; } diff --git a/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/index.md b/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/index.md index ace3c5bbb..dd3755467 100644 --- a/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/index.md +++ b/src/pages/overview/pdf-accessibility-auto-tag-api/howtos/index.md @@ -87,13 +87,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: @@ -102,11 +97,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-accessibility-auto-tag-api/quickstarts/nodejs/index.md b/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/index.md index f01d529b7..a02edf535 100644 --- a/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/index.md +++ b/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/index.md @@ -10,7 +10,7 @@ To get started using Adobe PDF Accessibility Auto-Tag API, let's walk through a 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. @@ -40,7 +40,7 @@ To complete this guide, you will need: ![alt](./shot5_spc.png) -2) Take these the `pdfservices-api-credentials.json` and place it in a new directory. Remember that these credential files are important and should be stored safely. +2) Take the `pdfservices-api-credentials.json` and place it in a new directory. Remember that these credential files are important and should be stored safely. 3) At the command line, change to the directory you created, and initialize a new Node.js project with `npm init -y` @@ -65,27 +65,18 @@ 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 { + ServicePrincipalCredentials, + PDFServices, + MimeType, + AutotagPDFParams, + AutotagPDFJob, + AutotagPDFResult, +} = 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 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 INPUT_PDF = './Adobe Accessibility Auto-Tag API Sample.pdf'; -const OUTPUT_PATH = './output/AutotagPDF/'; - -//Remove if the output already exists. -if(fs.existsSync(OUTPUT_PATH)) fs.unlinkSync(OUTPUT_PATH); - -const TAGGED_PDF = OUTPUT_PATH + INPUT_PDF + "-tagged-pdf.pdf"; -const TAGGING_REPORT = OUTPUT_PATH + INPUT_PDF + "-tagging-report.xlsx"; -``` - -This defines what our output directory will be and optionally deletes it if it already exists. Then we define what PDF will be tagged. (You can download the source we used here.) 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,52 +85,74 @@ This defines what our output directory will be and optionally deletes it if it a - `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: -4) 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 -// Create a new operation instance. -const autotagPDFOperation = PDFServicesSdk.AutotagPDF.Operation.createNew(), - input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT_PDF); - -// Build autotagPDF options -const autotagPDFOptions = new PDFServicesSdk.AutotagPDF.options.AutotagPDFOptions.Builder() - .shiftHeadings() - .generateReport() - .build(); -autotagPDFOperation.setInput(input); -autotagPDFOperation.setOptions(options); +// Create parameters for the job +const params = new AutotagPDFParams({ + generateReport: true, + shiftHeadings: true +}); + +// Creates a new job instance +const job = new AutotagPDFJob({inputAsset, params}); ``` -This set of code defines what we're doing (an Auto-Tag operation), points to our local file and specifies the input is a PDF, and then defines options for the Auto-Tag call. PDF Accessibility Auto-Tag API has a few different options, but in this example, we're simply asking for a basic tagging operation, which returns the tagged PDF document and an XLSX report of the document. +This set of code defines what we're doing (an Auto-Tag operation), +it defines parameters for the Auto-Tag job. PDF Accessibility Auto-Tag API has a few different options, but in this example, we're simply asking for a basic tagging operation, which returns the tagged PDF document and an XLSX report of the document. + +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: AutotagPDFResult +}); + +// Get content from the resulting asset(s) +const resultAsset = pdfServicesResponse.result.taggedPDF; +const resultAssetReport = pdfServicesResponse.result.report; +const streamAsset = await pdfServices.getContent({asset: resultAsset}); +const streamAssetReport = await pdfServices.getContent({asset: resultAssetReport}); +``` -5) The next code block executes the operation: +7) The next code block saves the result at the specified location: ```js -// Execute the operation -autotagPDFOperation.execute(executionContext) - .then(result => { - result.taggedPDF.saveAsFile(TAGGED_PDF); - result.report.saveAsFile(TAGGING_REPORT); - }) - .then(() => { - console.log('Successfully tagged information in PDF.'); - }) - .catch(err => console.log(err)); +// Creates an output stream and copy stream asset's content to it +const outputFilePath = "./autotag-tagged.pdf"; +const outputFilePathReport = "./autotag-report.xlsx"; +console.log(`Saving asset at ${outputFilePath}`); +console.log(`Saving asset at ${outputFilePathReport}`); + +let writeStream = fs.createWriteStream(outputFilePath); +streamAsset.readStream.pipe(writeStream); +writeStream = fs.createWriteStream(outputFilePathReport); +streamAssetReport.readStream.pipe(writeStream); ``` ![Example running at the command line](./shot9_ga.png) @@ -147,48 +160,73 @@ autotagPDFOperation.execute(executionContext) Here's the complete application (`autotag-pdf.js`): ```js -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); - -const INPUT_PDF = './Adobe Accessibility Auto-Tag API Sample.pdf'; -const OUTPUT_PATH = './output/AutotagPDF/'; - -//Remove if the output already exists. -if(fs.existsSync(OUTPUT_PATH)) fs.unlinkSync(OUTPUT_PATH); - -const TAGGED_PDF = OUTPUT_PATH + INPUT_PDF + "-tagged-pdf.pdf"; -const TAGGING_REPORT = OUTPUT_PATH + INPUT_PDF + "-tagging-report.xlsx"; - -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 autotagPDFOperation = PDFServicesSdk.AutotagPDF.Operation.createNew(), - input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT_PDF); - -// Build autotagPDF options -const autotagPDFOptions = new PDFServicesSdk.AutotagPDF.options.AutotagPDFOptions.Builder() - .shiftHeadings() - .generateReport() - .build(); -autotagPDFOperation.setInput(input); -autotagPDFOperation.setOptions(options); - -// Execute the operation -autotagPDFOperation.execute(executionContext) - .then(result => { - result.taggedPDF.saveAsFile(TAGGED_PDF); - result.report.saveAsFile(TAGGING_REPORT); - }) - .then(() => { - console.log('Successfully tagged information in PDF.'); - }) - .catch(err => console.log(err)); +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + AutotagPDFParams, + AutotagPDFJob, + AutotagPDFResult, +} = 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("./Adobe_Accessibility_Auto_Tag_API_Sample.pdf"); + const inputAsset = await pdfServices.upload({ + readStream, + mimeType: MimeType.PDF + }); + + // Create parameters for the job + const params = new AutotagPDFParams({ + generateReport: true, + shiftHeadings: true + }); + + // Creates a new job instance + const job = new AutotagPDFJob({inputAsset, params}); + + // Submit the job and get the job result + const pollingURL = await pdfServices.submit({job}); + const pdfServicesResponse = await pdfServices.getJobResult({ + pollingURL, + resultType: AutotagPDFResult + }); + + // Get content from the resulting asset(s) + const resultAsset = pdfServicesResponse.result.taggedPDF; + const resultAssetReport = pdfServicesResponse.result.report; + const streamAsset = await pdfServices.getContent({asset: resultAsset}); + const streamAssetReport = await pdfServices.getContent({asset: resultAssetReport}); + + // Creates an output stream and copy stream asset's content to it + const outputFilePath = "./autotag-tagged.pdf"; + const outputFilePathReport = "./autotag-report.xlsx"; + console.log(`Saving asset at ${outputFilePath}`); + console.log(`Saving asset at ${outputFilePathReport}`); + + let writeStream = fs.createWriteStream(outputFilePath); + streamAsset.readStream.pipe(writeStream); + writeStream = fs.createWriteStream(outputFilePathReport); + streamAssetReport.readStream.pipe(writeStream); + } catch (err) { + console.log("Exception encountered while executing operation", err); + } finally { + readStream?.destroy(); + } +})(); ``` ## Next Steps diff --git a/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/shot9_ga.png b/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/shot9_ga.png index 2a7e0cc85..7523559a5 100644 Binary files a/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/shot9_ga.png and b/src/pages/overview/pdf-accessibility-auto-tag-api/quickstarts/nodejs/shot9_ga.png differ diff --git a/src/pages/overview/pdf-electronic-seal-api/gettingstarted.md b/src/pages/overview/pdf-electronic-seal-api/gettingstarted.md index 1fc48012e..6727232ec 100644 --- a/src/pages/overview/pdf-electronic-seal-api/gettingstarted.md +++ b/src/pages/overview/pdf-electronic-seal-api/gettingstarted.md @@ -66,9 +66,9 @@ PDF Electronic Seal API endpoints are authenticated endpoints. Getting an access 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' \ @@ -84,9 +84,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' \ @@ -100,9 +100,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}}' \ @@ -125,9 +125,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.electronicseal.jobstatus). - + -### Rest API +### REST API ```javascript curl --location -g --request GET 'https://pdf-services.adobe.io/operation/electronicseal/{{Placeholder for job id}}/status' \ @@ -150,9 +150,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}}' @@ -521,7 +521,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. @@ -557,7 +557,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-electronic-seal-api/howtos/electronic-seal-api.md b/src/pages/overview/pdf-electronic-seal-api/howtos/electronic-seal-api.md index fb49ae40a..2892f6d06 100644 --- a/src/pages/overview/pdf-electronic-seal-api/howtos/electronic-seal-api.md +++ b/src/pages/overview/pdf-electronic-seal-api/howtos/electronic-seal-api.md @@ -161,7 +161,7 @@ The sample below performs electronic seal operation with default appearance on a Please refer to the [API usage guide](../api-usage.md) to understand how to use our APIs. - + #### Java @@ -404,98 +404,146 @@ namespace ElectronicSeal // Run the sample: // node src/electronicseal/electronic-seal.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); - - const pdfElectronicSeal = PDFServicesSdk.PDFElectronicSeal, - options = pdfElectronicSeal.options; - - //Get the input document to perform the sealing operation - const sourceFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/sampleInvoice.pdf'), - - //Get the background seal image for signature , if required. - sealImageFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/sampleSealImage.png'); - - // 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) - .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); - } - }); - +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + DocumentLevelPermission, + FieldLocation, + FieldOptions, + CSCAuthContext, + CSCCredential, + PDFElectronicSealParams, + PDFElectronicSealJob, + PDFElectronicSealResult, + SDKError, + ServiceUsageError, + ServiceApiError +} = 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 + }); + + // 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 document level permission to be applied for output document + const documentLevelPermission = DocumentLevelPermission.FORM_FILLING; + + // Set the Seal Field Name to be created in input PDF document + const sealFieldName = "Signature1"; + + // Set the page number in input document for applying seal + const sealPageNumber = 1; + + // 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 + }); + + // Create FieldOptions instance with required details + const sealFieldOptions = new FieldOptions({ + visible: sealVisible, + location: fieldLocation, + fieldName: sealFieldName, + pageNumber: sealPageNumber, + }); + + // 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({ + certificateCredentials, + sealFieldOptions, + documentLevelPermission, + }); + + // 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) { - 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 { + sourceFileReadStream?.destroy(); + sealImageReadStream?.destroy(); + } +})(); ``` #### REST API @@ -540,7 +588,7 @@ The sample below performs electronic seal operation with customized appearance o Please refer to the [API usage guide](../api-usage.md) to understand how to use our APIs. - + #### Java @@ -800,109 +848,162 @@ namespace ElectronicSealWithAppearanceOptions ```javascript // Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample // Run the sample: -// node src/electronicseal/electronic-seal.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); - - const pdfElectronicSeal = PDFServicesSdk.PDFElectronicSeal, - options = pdfElectronicSeal.options; - - //Get the input document to perform the sealing operation - const sourceFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/sampleInvoice.pdf'), - - //Get the background seal image for signature , if required. - sealImageFile = PDFServicesSdk.FileRef.createFromLocalFile('resources/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); - } - }); - +// node src/electronicseal/electronic-seal-with-appearance-options.js + +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 + }); + + // 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 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 + ] + }); + + // Set the Seal Field Name to be created in input PDF document + const sealFieldName = "Signature1"; + + // Set the page number in input document for applying seal + const sealPageNumber = 1; + + // 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 + }); + + // Create FieldOptions instance with required details + const sealFieldOptions = new FieldOptions({ + visible: sealVisible, + location: fieldLocation, + fieldName: sealFieldName, + pageNumber: sealPageNumber, + }); + + // 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) { - 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 { + sourceFileReadStream?.destroy(); + sealImageReadStream?.destroy(); + } +})(); ``` #### REST API @@ -955,7 +1056,7 @@ The sample below performs electronic seal operation with a trusted timestamp on Please refer to the [API usage guide](../api-usage.md) to understand how to use our APIs. - + #### Java @@ -1072,7 +1173,172 @@ public class ElectronicSealWithTimeStampAuthority { ``` -#### Rest API +#### Node JS + +```javascript +// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample +// Run the sample: +// node src/electronicseal/electronic-seal-with-stamp-authority.js + +const { + ServicePrincipalCredentials, + PDFServices, + MimeType, + FieldLocation, + FieldOptions, + CSCAuthContext, + CSCCredential, + PDFElectronicSealParams, + PDFElectronicSealJob, + PDFElectronicSealResult, + DocumentLevelPermission, + TSABasicAuthCredentials, + RFC3161TSAOptions, + SDKError, + ServiceUsageError, + ServiceApiError, +} = 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 + }); + + // 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 document level permission to be applied for output document + const documentLevelPermission = DocumentLevelPermission.FORM_FILLING; + + // Set the Seal Field Name to be created in input PDF document + const sealFieldName = "Signature1"; + + // Set the page number in input document for applying seal + const sealPageNumber = 1; + + // 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 + }); + + // Create FieldOptions instance with required details + const sealFieldOptions = new FieldOptions({ + visible: sealVisible, + location: fieldLocation, + fieldName: sealFieldName, + pageNumber: sealPageNumber, + }); + + // 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 TSABasicAuthCredentials using username and password + const tsaBasicAuthCredentials = new TSABasicAuthCredentials({ + username: "", + password: "" + }); + + // Set the Time Stamp Authority Options using url and TSA Auth credentials + const tsaOptions = new RFC3161TSAOptions({ + url: "", + credentialAuthParameters: tsaBasicAuthCredentials + }); + + // Create parameters for the job + const params = new PDFElectronicSealParams({ + documentLevelPermission, + certificateCredentials, + sealFieldOptions, + tsaOptions + }); + + // 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(); + } +})(); +``` + +#### REST API ```javascript curl --location --request POST 'https://pdf-services.adobe.io/operation/electronicseal' \ --header 'x-api-key: {{Placeholder for client_id}}' \ diff --git a/src/pages/overview/pdf-electronic-seal-api/howtos/index.md b/src/pages/overview/pdf-electronic-seal-api/howtos/index.md index 8330786f7..904465193 100644 --- a/src/pages/overview/pdf-electronic-seal-api/howtos/index.md +++ b/src/pages/overview/pdf-electronic-seal-api/howtos/index.md @@ -86,14 +86,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: @@ -102,9 +96,7 @@ 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 +}) +``` \ No newline at end of file diff --git a/src/pages/overview/pdf-electronic-seal-api/quickstarts/nodejs/index.md b/src/pages/overview/pdf-electronic-seal-api/quickstarts/nodejs/index.md index e5a3d1f03..f6083bedc 100644 --- a/src/pages/overview/pdf-electronic-seal-api/quickstarts/nodejs/index.md +++ b/src/pages/overview/pdf-electronic-seal-api/quickstarts/nodejs/index.md @@ -10,7 +10,7 @@ To get started using Adobe PDF Electronic Seal API, let's walk through a simple 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,12 +63,26 @@ Now you're ready to begin coding. 1) We'll begin by including our required dependencies: ```javascript -const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); +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"); ``` -This line includes the Adobe PDF Services Node.js SDK - - 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=` @@ -82,262 +96,312 @@ This line includes the Adobe PDF Services Node.js SDK 3) Next, we setup the SDK to use our credentials. ```javascript - // 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); +// 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 and sets up an execution context object that will be used later. - -4) Let's define the electronic seal and options object to be used later: +4) Now, let's upload the assets: ```javascript -const pdfElectronicSeal = PDFServicesSdk.PDFElectronicSeal, - options = pdfElectronicSeal.options; - +const [sourceFileAsset, sealImageAsset] = await pdfServices.uploadAssets({ + streamAssets: [{ + readStream: sourceFileReadStream, + mimeType: MimeType.PDF + }, { + readStream: sealImageReadStream, + mimeType: MimeType.PNG + }] +}); ``` -5) Now, let's define our input fields: +5) Now, we will define the document level permission: ```javascript -//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'); - +// Set the document level permission to be applied for output document +const documentLevelPermission = DocumentLevelPermission.FORM_FILLING; ``` 6) Now, we will define seal field options: ```javascript -//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(); +// 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 + ] +}); + +// Set the Seal Field Name to be created in input PDF document +const sealFieldName = "Signature1"; + +// Set the page number in input document for applying seal +const sealPageNumber = 1; + +// 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 +}); + +// Create FieldOptions instance with required details +const sealFieldOptions = new FieldOptions({ + visible: sealVisible, + location: fieldLocation, + fieldName: sealFieldName, + pageNumber: sealPageNumber, +}); ``` 7) Next, we create a CSC Certificate Credentials instance: ```javascript -//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 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, +}); +``` -//Set the credential ID. -credentialID = ""; +8) Now, let's create the job with seal parameters using certificate credentials and field options and set the seal image asset: -//Set the PIN generated while creating credentials. -pin = ""; +```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)