Join our Beta program for the Import/Export PDF Form Data APIs
Sign up for access to try our latest set of APIs that import and export data from form fields at scale.
Why PDF Services API?
Create, secure, and convert PDF documents
Create a PDF from Microsoft Office documents, protect the content, and convert to other formats.
Modify PDFs and optimize output
Programmatically alter a document, such as reordering, inserting, and rotating pages, as well as compressing the file.
Leverage Adobe's cloud-based services
Access the same cloud-based APIs that power Adobe's end user applications to quickly deliver scalable, secure solutions.
Key features of Adobe PDF Services API
PDF content extraction
Extract text, images, tables, and more from native and scanned PDFs into a structured JSON file. PDF Extract API leverages AI technology to accurately identify text objects and understand the natural reading order of different elements such as headings, lists, and paragraphs spanning multiple columns or pages. Extract font styles with identification of metadata such as bold and italic text and their position within your PDF. Extracted content is output in a structured JSON file format with tables in CSV or XLSX and images saved as PNG.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","elementsToExtract": ["text"]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/extractpdf/extract-text-info-from-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./extractPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ExtractPDFParams({elementsToExtract: [ExtractElementType.TEXT]});// Creates a new job instanceconst job = new ExtractPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ExtractTextInfoFromPDF/// dotnet run ExtractTextInfoFromPDF.csprojnamespace ExtractTextInfoFromPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the logging.ConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"extractPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobExtractPDFParams extractPDFParams = ExtractPDFParams.ExtractPDFParamsBuilder().AddElementToExtract(ExtractElementType.TEXT).Build();// Creates a new job instanceExtractPDFJob extractPDFJob = new ExtractPDFJob(asset).SetParams(extractPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(extractPDFJob);PDFServicesResponse<ExtractPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ExtractPDFResult>(location, typeof(ExtractPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Resource;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/ExtractTextInfoFromPDF.zip";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.extractpdf.ExtractTextInfoFromPDFpublic class ExtractTextInfoFromPDF {private static final Logger LOGGER = LoggerFactory.getLogger(ExtractTextInfoFromPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/extractPdfInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobExtractPDFParams extractPDFParams = ExtractPDFParams.extractPDFParamsBuilder().addElementsToExtract(Arrays.asList(ExtractElementType.TEXT)).build();// Creates a new job instanceExtractPDFJob extractPDFJob = new ExtractPDFJob(asset).setParams(extractPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(extractPDFJob);PDFServicesResponse<ExtractPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ExtractPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getResource();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/ExtractTextInfoFromPDF.zip").toPath());LOGGER.info("Saving asset at output/ExtractTextInfoFromPDF.zip");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/extractpdf/extract_text_info_from_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ExtractTextInfoFromPDF:def __init__(self):try:file = open("extractPdfInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobextract_pdf_params = ExtractPDFParams(elements_to_extract=[ExtractElementType.TEXT],)# Creates a new job instanceextract_pdf_job = ExtractPDFJob(input_asset=input_asset, extract_pdf_params=extract_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(extract_pdf_job)pdf_services_response = pdf_services.get_job_result(location, ExtractPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_resource()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "extractTextInfoFromPDF.zip"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ExtractTextInfoFromPDF()
Adobe PDF Accessibility Auto-Tag API
Tag PDFs to improve accessibility. Identify the content structure and reading order, and tag tables, paragraphs, lists, headings, figures, and more to improve the reading experience of native or scanned PDFs with assistive technologies. Generate a tailored tagging report about added tags and any content that needs additional review.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our REST API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-Accessibility-Auto-Tagcurl --location --request POST 'https://pdf-services.adobe.io/operation/autotag' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"}'
Copied to your clipboard// Get the samples from https://github.com/adobe/pdfservices-node-sdk-samples// Run the sample:// node src/autotagpdf/autotag-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./autotagPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new AutotagPDFJob({inputAsset});// Submit the job and get the job resultconst 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 streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates an output stream and copy stream asset's content to itconst 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();}})();
Copied to your clipboard// Get the samples from https://github.com/adobe/PDFServices.NET.SDK.Samples// Run the sample:// cd AutotagPDF/// dotnet run AutotagPDF.csprojnamespace AutotagPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"autotagPdfInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceAutotagPDFJob autotagPDFJob = new AutotagPDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(autotagPDFJob);PDFServicesResponse<AutotagPDFResult> pdfServicesResponse =pdfServices.GetJobResult<AutotagPDFResult>(location, typeof(AutotagPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.TaggedPDF;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/autotagPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from https://github.com/adobe/pdfservices-java-sdk-samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.autotagpdf.AutotagPDFpublic class AutotagPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(AutotagPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/autotagPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceAutotagPDFJob autotagPDFJob = new AutotagPDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(autotagPDFJob);PDFServicesResponse<AutotagPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, AutotagPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getTaggedPDF();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/autotagPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/autotagPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/autotagpdf/autotag_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class AutoTagPDF:def __init__(self):try:file = open("autotagPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instanceautotag_pdf_job = AutotagPDFJob(input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(autotag_pdf_job)pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = (pdf_services_response.get_result().get_tagged_pdf())stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "autoTagPDFOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":AutoTagPDF()
Create a PDF file
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
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/createpdf/create-pdf-from-docx.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./createPDFInput.docx");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.DOCX});// Creates a new job instanceconst job = new CreatePDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CreatePDFFromDocx/// dotnet run CreatePDFFromDocx.csprojnamespace CreatePDFFromDocx{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"createPdfInput.docx");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());// Creates a new job instanceCreatePDFJob createPDFJob = new CreatePDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(createPDFJob);PDFServicesResponse<CreatePDFResult> pdfServicesResponse =pdfServices.GetJobResult<CreatePDFResult>(location, typeof(CreatePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/createPdfOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.createpdf.CreatePDFFromDOCXpublic class CreatePDFFromDOCX {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDOCX.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFInput.docx").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());// Creates a new job instanceCreatePDFJob createPDFJob = new CreatePDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(createPDFJob);PDFServicesResponse<CreatePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CreatePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFile.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/createPDFFromDOCX.pdf").toPath());LOGGER.info("Saving asset at output/createPDFFromDOCX.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing the operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/createpdf/create_pdf_from_docx.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CreatePDFFromDOCX:def __init__(self):try:file = open("./createPDFInput.docx", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)# Creates a new job instancecreate_pdf_job = CreatePDFJob(input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(create_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CreatePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CreatePDFFromDOCX.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CreatePDFFromDOCX()
Create a PDF file from HTML
Create PDFs from static and dynamic HTML, Zip, and URL.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","json": "{}","includeHeaderFooter": true,"pageLayout": {"pageWidth": 11,"pageHeight": 8.5}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/htmltopdf/static-html-to-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./createPDFFromStaticHtmlInput.zip");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.ZIP});// Create parameters for the jobconst params = getHTMLToPDFParams();// Creates a new job instanceconst job = new HTMLToPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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,});}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd StaticHTMLToPDF/// dotnet run StaticHTMLToPDF.csprojnamespace StaticHTMLToPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"createPDFFromStaticHtmlInput.zip");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.ZIP.GetMIMETypeValue());// Create parameters for the jobHTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();// Creates a new job instanceHTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(asset).SetParams(htmlToPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(htmlToPDFJob);PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/createPdfFromStaticHtmlOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static HTMLToPDFParams GetHTMLToPDFParams(){// Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).PageLayout pageLayout = new PageLayout();pageLayout.SetPageSize(8, 11.5);// Set the desired HTML-to-PDF conversion options.HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder().IncludeHeaderFooter(true).WithPageLayout(pageLayout).Build();return htmlToPDFParams;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.createpdf.CreatePDFFromStaticHTML// 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.htmltopdf.StaticHTMLToPDFpublic class StaticHTMLToPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(StaticHTMLToPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFFromStaticHtmlInput.zip").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.ZIP.getMediaType());// Create parameters for the jobHTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();// Creates a new job instanceHTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(asset).setParams(htmlToPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(htmLtoPDFJob);PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFile.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/staticHTMLToPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/staticHTMLToPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}private static HTMLToPDFParams getHTMLToPDFParams() {// Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)PageLayout pageLayout = new PageLayout();pageLayout.setPageSize(8, 11.5);return new HTMLToPDFParams.Builder().includeHeaderFooter(true).withPageLayout(pageLayout).build();}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/htmltopdf/static_html_to_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class StaticHTMLtoPDF:def __init__(self):try:file = open('./createPDFFromStaticHtmlInput.zip', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.ZIP)# Create parameters for the jobhtml_to_pdf_params = self.get_html_to_pdf_params()# Creates a new job instancehtml_to_pdf_job = HTMLtoPDFJob(input_asset=input_asset, html_to_pdf_params=html_to_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(html_to_pdf_job)pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'output/StaticHTMLToPDF.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')@staticmethoddef get_html_to_pdf_params() -> HTMLtoPDFParams:# Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)page_layout = PageLayout(page_height=11.5, page_width=8)return HTMLtoPDFParams(page_layout=page_layout, include_header_footer=True)if __name__ == "__main__":StaticHTMLtoPDF()
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Document-Generationcurl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","outputFormat": "pdf","jsonDataForMerge": {"customerName": "Kane Miller","customerVisits": 100,"itemsBought": [{"name": "Sprays","quantity": 50,"amount": 100},{"name": "Chemicals","quantity": 100,"amount": 200}],"totalAmount": 300,"previousBalance": 50,"lastThreeBillings": [100,200,300],"photograph": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP88h8AAu0B9XNPCQQAAAAASUVORK5CYII="}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/documentmerge/merge-document-to-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Setup input data for the document merge processconst jsonDataForMerge = {customerName: "Kane Miller",customerVisits: 100}// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./documentMergeTemplate.docx");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.DOCX});// Create parameters for the jobconst params = new DocumentMergeParams({jsonDataForMerge,outputFormat: OutputFormat.PDF});// Creates a new job instanceconst job = new DocumentMergeJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd MergeDocumentToPDF/// dotnet run MergeDocumentToPDF.csprojnamespace MergeDocumentToPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"documentMergeTemplate.docx");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());// Setup input data for the document merge processJObject jsonDataForMerge = JObject.Parse("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.DocumentMergeParamsBuilder().WithJsonDataForMerge(jsonDataForMerge).WithOutputFormat(OutputFormat.PDF).Build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submits the job and gets the job resultString location = pdfServices.Submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse =pdfServices.GetJobResult<DocumentMergeResult>(location, typeof(DocumentMergeResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/documentMergeOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.MergeDocumentToPDFpackage com.adobe.pdfservices.operation.samples.documentmerge;public class MergeDocumentToPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(MergeDocumentToPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/documentMergeTemplate.docx").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Setup input data for the document merge process.JSONObject jsonDataForMerge = new JSONObject("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.documentMergeParamsBuilder().withJsonDataForMerge(jsonDataForMerge).withOutputFormat(OutputFormat.PDF).build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submit the job and gets the job resultString location = pdfServices.submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse = pdfServices.getJobResult(location, DocumentMergeResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itOutputStream outputStream = Files.newOutputStream(new File("output/documentMergeOutput.pdf").toPath());IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/documentmerge/merge_document_to_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class MergeDocumentToPDF:def __init__(self):try:file = open("./salesOrderTemplate.docx", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)# Setup input data for the document merge processwith open("./salesOrder.json", "r") as file:content_string = file.read()json_data_for_merge = json.loads(content_string)# Create parameters for the jobdocument_merge_params = DocumentMergeParams(json_data_for_merge=json_data_for_merge, output_format=OutputFormat.PDF)# Creates a new job instancedocument_merge_job = DocumentMergeJob(input_asset=input_asset, document_merge_params=document_merge_params)# Submit the job and gets the job resultlocation = pdf_services.submit(document_merge_job)pdf_services_response = pdf_services.get_job_result(location, DocumentMergePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/MergeDocumentToPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":MergeDocumentToPDF()
PDF Electronic Seal API
Apply an electronic seal to documents at scale using a certificate issued by certain TSPs (Trust Service Providers) on Adobe’s Approved Trust List (AATL). The electronic seal helps verify the identity and integrity of documents.
See our public API Reference and quickly try our APIs using the Postman collections.
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer-stage.adobe.com/document-services/docs/apis/#tag/PDF-Electronic-Sealcurl --location --request POST 'https://pdf-services.adobe.io/operation/electronicseal' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"inputDocumentAssetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-xxxx-xxxx-087832fca718","sealImageAssetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-xxxx-xxxx-087832fca718","sealOptions": {"signatureFormat": "PKCS7","cscCredentialOptions": {"credentialId": "<CREDENTIAL_ID>","providerName": "<PROVIDER_NAME>","authorizationContext": {"tokenType": "Bearer","accessToken": "<ACCESS_TOKEN>"},"credentialAuthParameters": {"pin": "<PIN>"}},"sealFieldOptions": {"location": {"top": 300,"left": 50,"right": 250,"bottom": 100},"fieldName": "Signature1","pageNumber": 1},"sealAppearanceOptions": {"displayOptions": ["NAME","DATE","DISTINGUISHED_NAME","LABELS","SEAL_IMAGE"]}}}'
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/electronicseal/electronic-seal.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadsourceFileReadStream = 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 documentconst documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Set the Seal Field Name to be created in input PDF documentconst sealFieldName = "Signature1";// Set the page number in input document for applying sealconst sealPageNumber = 1;// Set if seal should be visible or invisibleconst sealVisible = true;// Create FieldLocation instance and set the coordinates for applying signatureconst fieldLocation = new FieldLocation({left: 150,top: 250,right: 350,bottom: 200});// Create FieldOptions instance with required detailsconst sealFieldOptions = new FieldOptions({visible: sealVisible,location: fieldLocation,fieldName: sealFieldName,pageNumber: sealPageNumber,});// Set the name of TSP Provider being usedconst providerName = "<PROVIDER_NAME>";// Set the access token to be used to access TSP provider hosted APIsconst accessToken = "<ACCESS_TOKEN>";// Set the credential IDconst credentialId = "<CREDENTIAL_ID>";// Set the PIN generated while creating credentialsconst pin = "<PIN>";// Create CSCAuthContext instance using access token and token typeconst authorizationContext = new CSCAuthContext({accessToken,tokenType: "Bearer"});// Create CertificateCredentials instance with required certificate detailsconst certificateCredentials = new CSCCredential({providerName,credentialId,pin,authorizationContext,});// Create parameters for the jobconst params = new PDFElectronicSealParams({certificateCredentials,sealFieldOptions,documentLevelPermission,});// Creates a new job instanceconst job = new PDFElectronicSealJob({inputAsset: sourceFileAsset,sealImageAsset,params,});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ElectronicSeal/// dotnet run ElectronicSeal.csprojnamespace ElectronicSeal{class Program{// Initialize the logger.private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"SampleInvoice.pdf");using Stream inputStreamSealImage = File.OpenRead(@"sampleSealImage.png");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset sealImageAsset =pdfServices.Upload(inputStreamSealImage, PDFServicesMediaType.PNG.GetMIMETypeValue());// Set the document level permission to be applied for output documentDocumentLevelPermission documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Sets the Seal Field Name to be created in input PDF document.String sealFieldName = "Signature1";// Sets the page number in input document for applying seal.int sealPageNumber = 1;// Sets if seal should be visible or invisible.bool sealVisible = true;// Creates FieldLocation instance and set the coordinates for applying signatureFieldLocation fieldLocation = new FieldLocation(150, 250, 350, 200);// Create FieldOptions instance with required details.FieldOptions fieldOptions = new FieldOptions.Builder(sealFieldName).SetVisible(sealVisible).SetFieldLocation(fieldLocation).SetPageNumber(sealPageNumber).Build();// Sets the name of TSP Provider being used.String providerName = "<PROVIDER_NAME>";// Sets the access token to be used to access TSP provider hosted APIs.String accessToken = "<ACCESS_TOKEN>";// Sets the credential ID.String credentialID = "<CREDENTIAL_ID>";// Sets the PIN generated while creating credentials.String pin = "<PIN>";// Creates CSCAuthContext instance using access token and token type.CSCAuthContext cscAuthContext = new CSCAuthContext(accessToken, "Bearer");// Create CertificateCredentials instance with required certificate details.CertificateCredentials certificateCredentials = CertificateCredentials.CSCCredentialBuilder().WithProviderName(providerName).WithCredentialID(credentialID).WithPin(pin).WithCSCAuthContext(cscAuthContext).Build();// Create parameters for the jobPDFElectronicSealParams pdfElectronicSealParams =PDFElectronicSealParams.PDFElectronicSealParamsBuilder(certificateCredentials, fieldOptions).WithDocumentLevelPermission(documentLevelPermission).Build();// Creates a new job instancePDFElectronicSealJob pdfElectronicSealJob = new PDFElectronicSealJob(asset, pdfElectronicSealParams);pdfElectronicSealJob.SetSealImageAsset(sealImageAsset);// Submits the job and gets the job resultString location = pdfServices.Submit(pdfElectronicSealJob);PDFServicesResponse<PDFElectronicSealResult> pdfServicesResponse =pdfServices.GetJobResult<PDFElectronicSealResult>(location, typeof(PDFElectronicSealResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/sealedOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.electronicseal.ElectronicSealpublic class ElectronicSeal {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ElectronicSeal.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/sampleInvoice.pdf").toPath());InputStream inputStreamSealImage = Files.newInputStream(new File("src/main/resources/sampleSealImage.png").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());Asset sealImageAsset = pdfServices.upload(inputStreamSealImage, PDFServicesMediaType.PNG.getMediaType());// Set the document level permission to be applied for output documentDocumentLevelPermission documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Sets the Seal Field Name to be created in input PDF document.String sealFieldName = "Signature1";// Sets the page number in input document for applying seal.Integer sealPageNumber = 1;// Sets if seal should be visible or invisible.Boolean sealVisible = true;// Creates FieldLocation instance and set the coordinates for applying signatureFieldLocation fieldLocation = new FieldLocation(150, 250, 350, 200);// Create FieldOptions instance with required details.FieldOptions fieldOptions = new FieldOptions.Builder(sealFieldName).setFieldLocation(fieldLocation).setPageNumber(sealPageNumber).setVisible(sealVisible).build();// Sets the name of TSP Provider being used.String providerName = "<PROVIDER_NAME>";// Sets the access token to be used to access TSP provider hosted APIs.String accessToken = "<ACCESS_TOKEN>";// Sets the credential ID.String credentialID = "<CREDENTIAL_ID>";// Sets the PIN generated while creating credentials.String pin = "<PIN>";// Creates CSCAuthContext instance using access token and token type.CSCAuthContext cscAuthContext = new CSCAuthContext(accessToken, "Bearer");// Create CertificateCredentials instance with required certificate details.CertificateCredentials certificateCredentials = CertificateCredentials.cscCredentialBuilder().withProviderName(providerName).withCredentialID(credentialID).withPin(pin).withCSCAuthContext(cscAuthContext).build();// Create parameters for the jobPDFElectronicSealParams pdfElectronicSealParams = PDFElectronicSealParams.pdfElectronicSealParamsBuilder(certificateCredentials, fieldOptions).withDocumentLevelPermission(documentLevelPermission).build();// Creates a new job instancePDFElectronicSealJob pdfElectronicSealJob = new PDFElectronicSealJob(asset, pdfElectronicSealParams);// Sets the optional input seal image for PDFElectronicSealOperation instancepdfElectronicSealJob.setSealImageAsset(sealImageAsset);// Submit the job and gets the job resultString location = pdfServices.submit(pdfElectronicSealJob);PDFServicesResponse<PDFElectronicSealResult> pdfServicesResponse = pdfServices.getJobResult(location, PDFElectronicSealResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/sealedOutput.pdf").toPath());LOGGER.info("Saving asset at output/sealedOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ElectronicSeal:def __init__(self):try:pdf_file = open("./sampleInvoice.pdf", "rb")file_input_stream = pdf_file.read()pdf_file.close()seal_image_file = open("./sampleSealImage.png", "rb")seal_image_input_stream = seal_image_file.read()seal_image_file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadasset = pdf_services.upload(input_stream=file_input_stream, mime_type=PDFServicesMediaType.PDF)seal_image_asset = pdf_services.upload(input_stream=seal_image_input_stream, mime_type=PDFServicesMediaType.PNG)# Set the document level permission to be applied for output documentdocument_level_permission = DocumentLevelPermission.FORM_FILLING# Sets the Seal Field Name to be created in input PDF document.seal_field_name = "Signature1"# Sets the page number in input document for applying seal.seal_page_number = 1# Sets if seal should be visible or invisible.seal_visible = True# Creates FieldLocation instance and set the coordinates for applying signaturefield_location = FieldLocation(150, 250, 350, 200)# Create FieldOptions instance with required details.field_options = FieldOptions(field_name=seal_field_name,field_location=field_location,page_number=seal_page_number,visible=seal_visible,)# Sets the name of TSP Provider being used.provider_name = "<PROVIDER_NAME>"# Sets the access token to be used to access TSP provider hosted APIs.access_token = "<ACCESS_TOKEN>"# Sets the credential ID.credential_id = "<CREDENTIAL_ID>"# Sets the PIN generated while creating credentials.pin = "<PIN>"# Creates CSCAuthContext instance using access token and token type.csc_auth_context = CSCAuthContext(access_token=access_token,token_type="Bearer",)# Create CertificateCredentials instance with required certificate details.certificate_credentials = CSCCredentials(provider_name=provider_name,credential_id=credential_id,pin=pin,csc_auth_context=csc_auth_context,)# Create parameters for the jobelectronic_seal_params = PDFElectronicSealParams(seal_certificate_credentials=certificate_credentials,seal_field_options=field_options,)# Creates a new job instanceelectronic_seal_job = PDFElectronicSealJob(input_asset=asset,electronic_seal_params=electronic_seal_params,seal_image_asset=seal_image_asset,)# Submit the job and gets the job resultlocation = pdf_services.submit(electronic_seal_job)pdf_services_response = pdf_services.get_job_result(location, ESealPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/ElectronicSeal.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ElectronicSeal()
Convert a PDF file to other formats
Convert existing PDFs to popular formats, such as Microsoft Word, Excel, and PowerPoint, as well as text and image
Support for PDF to DOC, PDF to DOCX, PDF to JPEG, PDF to PNG, PDF to PPTX, PDF to RTF, PDF to XLSX
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Export-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/exportpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/exportpdftoimages/export-pdf-to-jpeg.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./exportPDFToImageInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ExportPDFToImagesParams({targetFormat: ExportPDFToImagesTargetFormat.JPEG,outputType: ExportPDFToImagesOutputType.LIST_OF_PAGE_IMAGES});// Creates a new job instanceconst job = new ExportPDFToImagesJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ExportPDFToDocx/// dotnet run ExportPDFToDocx.csprojnamespace ExportPDFToDocx{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"exportPdfInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobExportPDFParams exportPDFParams = ExportPDFParams.ExportPDFParamsBuilder(ExportPDFTargetFormat.DOCX).Build();// Creates a new job instanceExportPDFJob exportPDFJob = new ExportPDFJob(asset, exportPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(exportPDFJob);PDFServicesResponse<ExportPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ExportPDFResult>(location, typeof(ExportPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itStream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + "/output/exportPdfOutput.docx");streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.exportpdf.ExportPDFToDOCXpublic class ExportPDFToDOCX {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ExportPDFToDOCX.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/exportPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobExportPDFParams exportPDFParams = ExportPDFParams.exportPDFParamsBuilder(ExportPDFTargetFormat.DOCX).build();// Creates a new job instanceExportPDFJob exportPDFJob = new ExportPDFJob(asset, exportPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(exportPDFJob);PDFServicesResponse<ExportPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ExportPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/exportPdfOutput.docx").toPath());LOGGER.info("Saving asset at output/exportPdfOutput.docx");IOUtils.copy(streamAsset.getInputStream(), outputStream);} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python python src/exportpdftoimages/export_pdf_to_jpeg.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ExportPDFToDOCX:def __init__(self):try:file = open("./exportPDFToImageInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobexport_pdf_to_images_params = ExportPDFtoImagesParams(export_pdf_to_images_target_format=ExportPDFToImagesTargetFormat.JPEG,export_pdf_to_images_output_type=ExportPDFToImagesOutputType.LIST_OF_PAGE_IMAGES,)# Creates a new job instanceexport_pdf_to_images_job = ExportPDFtoImagesJob(input_asset=input_asset,export_pdf_to_images_params=export_pdf_to_images_params,)# Submit the job and gets the job resultlocation = pdf_services.submit(export_pdf_to_images_job)pdf_services_response = pdf_services.get_job_result(location, ExportPDFtoImagesResult)# Get content from the resulting asset(s)result_assets = pdf_services_response.get_result().get_assets()output_file_path = "output/ExportPDFToImages"for (asset_index, asset) in enumerate(result_assets):save_output_file_path = f"{output_file_path}_{asset_index}.jpeg"stream_asset: StreamAsset = pdf_services.get_content(asset)# Creates an output stream and copy stream asset's content to itwith open(save_output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ExportPDFtoJPEG()
OCR a PDF file
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Ocrcurl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/ocr/ocr-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./ocrInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new OCRJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd OcrPDF/// dotnet run OcrPDF.csprojnamespace OcrPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"ocrInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceOCRJob ocrJob = new OCRJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(ocrJob);PDFServicesResponse<OCRResult> pdfServicesResponse =pdfServices.GetJobResult<OCRResult>(location, typeof(OCRResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/ocrOperationOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.ocrpdf.OcrPDFpublic class OcrPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/ocrInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceOCRJob ocrJob = new OCRJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(ocrJob);PDFServicesResponse<OCRResult> pdfServicesResponse = pdfServices.getJobResult(location, OCRResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/ocrOutput.pdf").toPath());LOGGER.info("Saving asset at output/ocrOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/ocrpdf/ocr_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class OcrPDF(object):def __init__(self):try:file = open("./ocrInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instanceocr_pdf_job = OCRPDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(ocr_pdf_job)pdf_services_response = pdf_services.get_job_result(location, OCRPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/OcrPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":OcrPDF()
Secure a PDf file and set restrictions
Secure a PDF file with a password encrypt the document. Set an owner password and restrictions on certain features like printing, editing and copying in the PDF document to prevent end users from modifying it.
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Protect-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/protectpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"passwordProtection": {"userPassword": "user_password"},"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/protectpdf/protect-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./protectPDFInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ProtectPDFParams({userPassword: "password",encryptionAlgorithm: EncryptionAlgorithm.AES_256});// Create a new job instanceconst job = new ProtectPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst outputFilePath = "./protectPDFOutput.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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ProtectPDF/// dotnet run ProtectPDF.csprojnamespace ProtectPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"protectPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobProtectPDFParams protectPDFParams = ProtectPDFParams.PasswordProtectParamsBuilder().SetUserPassword("password").SetEncryptionAlgorithm(EncryptionAlgorithm.AES_256).Build();// Creates a new job instanceProtectPDFJob protectPDFJob = new ProtectPDFJob(asset, protectPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(protectPDFJob);PDFServicesResponse<ProtectPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ProtectPDFResult>(location, typeof(ProtectPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/protectPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}// Generates a string containing a directory structure and file name for the output file.private static String CreateOutputFilePath(){String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");return ("/output/protect" + timeStamp + ".pdf");}}}
Copied to your clipboard// 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.protectpdf.ProtectPDFpublic class ProtectPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ProtectPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/protectPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobProtectPDFParams protectPDFParams = ProtectPDFParams.passwordProtectOptionsBuilder().setUserPassword("password").setEncryptionAlgorithm(EncryptionAlgorithm.AES_256).build();// Creates a new job instanceProtectPDFJob protectPDFJob = new ProtectPDFJob(asset, protectPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(protectPDFJob);PDFServicesResponse<ProtectPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ProtectPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/protectPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/protectPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/protectpdf/protect_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ProtectPDF:def __init__(self):try:file = open("./protectPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobprotect_pdf_params = PasswordProtectParams(user_password="password",encryption_algorithm=EncryptionAlgorithm.AES_256,content_encryption=ContentEncryption.ALL_CONTENT,)# Creates a new job instanceprotect_pdf_job = ProtectPDFJob(input_asset=input_asset, protect_pdf_params=protect_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(protect_pdf_job)pdf_services_response = pdf_services.get_job_result(location, ProtectPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/ProtectPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ProtectPDF()
Remove the password from a PDF file
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Remove-Protectioncurl --location --request POST 'https://pdf-services.adobe.io/operation/removeprotection' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/removeprotection/remove-protection.jsconst {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 instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./removeProtectionInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new RemoveProtectionParams({password: "password"});// Creates a new job instanceconst job = new RemoveProtectionJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd RemoveProtection/// dotnet run RemoveProtection.csprojnamespace RemoveProtection{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"removeProtectionInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobRemoveProtectionParams removeProtectionParams = new RemoveProtectionParams("password");// Creates a new job instanceRemoveProtectionJob removeProtectionJob = new RemoveProtectionJob(asset, removeProtectionParams);// Submits the job and gets the job resultString location = pdfServices.Submit(removeProtectionJob);PDFServicesResponse<RemoveProtectionResult> pdfServicesResponse =pdfServices.GetJobResult<RemoveProtectionResult>(location, typeof(RemoveProtectionResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/removeProtectionOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.removeprotection.RemoveProtectionpublic class RemoveProtection {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(RemoveProtection.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/removeProtectionInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobRemoveProtectionParams removeProtectionParams = new RemoveProtectionParams("password");// Creates a new job instanceRemoveProtectionJob removeProtectionJob = new RemoveProtectionJob(asset, removeProtectionParams);// Submit the job and gets the job resultString location = pdfServices.submit(removeProtectionJob);PDFServicesResponse<RemoveProtectionResult> pdfServicesResponse = pdfServices.getJobResult(location, RemoveProtectionResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/removeProtectionOutput.pdf").toPath());LOGGER.info("Saving asset at output/removeProtectionOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/removeprotection/remove_protection.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class RemoveProtection:def __init__(self):try:file = open('removeProtectionInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobremove_protection_params = RemoveProtectionParams(password="password")# Creates a new job instanceremove_protection_job = RemoveProtectionJob(input_asset=input_asset,remove_protection_params=remove_protection_params)# Submit the job and gets the job resultlocation = pdf_services.submit(remove_protection_job)pdf_services_response = pdf_services.get_job_result(location, RemoveProtectionResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'removeProtectionOutput.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":RemoveProtection()
Get the properties of a PDF file
Use this service to get the metadata properties of a PDF. Metadata including page count, PDF version, file size, compliance levels, font info, permissions and more are provided in JSON format for easy processing.
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-Propertiescurl --location --request POST 'https://pdf-services.adobe.io/operation/pdfproperties' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/pdfproperties/get-pdf-properties.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./pdfPropertiesInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new PDFPropertiesParams({includePageLevelProperties: true});// Creates a new job instanceconst job = new PDFPropertiesJob({inputAsset,params});// Submit the job and get the job resultconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd PDFPropertiesAsJSONObject/// dotnet run GetPDFProperties.csprojnamespace GetPDFProperties{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"pdfPropertiesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobPDFPropertiesParams pdfPropertiesParams = PDFPropertiesParams.PDFPropertiesParamsBuilder().IncludePageLevelProperties().Build();// Creates a new job instancePDFPropertiesJob pdfPropertiesJob = new PDFPropertiesJob(asset);pdfPropertiesJob.SetParams(pdfPropertiesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(pdfPropertiesJob);PDFServicesResponse<PDFPropertiesResult> pdfServicesResponse =pdfServices.GetJobResult<PDFPropertiesResult>(location, typeof(PDFPropertiesResult));PDFProperties pdfProperties = pdfServicesResponse.Result.PDFProperties;// Fetch the requisite properties of the specified PDF.Console.WriteLine("The resultant PDF Properties are: " + pdfProperties.ToString());}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.pdfproperties.GetPDFPropertiespublic class GetPDFProperties {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(GetPDFProperties.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/pdfPropertiesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Create parameters for the jobPDFPropertiesParams pdfPropertiesParams = PDFPropertiesParams.pdfPropertiesParamsBuilder().includePageLevelProperties().build();// Creates a new job instancePDFPropertiesJob pdfPropertiesJob = new PDFPropertiesJob(asset).setParams(pdfPropertiesParams);// Submit the job and gets the job resultString location = pdfServices.submit(pdfPropertiesJob);PDFServicesResponse<PDFPropertiesResult> pdfServicesResponse = pdfServices.getJobResult(location, PDFPropertiesResult.class);PDFProperties pdfProperties = pdfServicesResponse.getResult().getPdfProperties();// Fetch the requisite properties of the specified PDF.LOGGER.info("Size of the specified PDF file: {}", pdfProperties.getDocument().getFileSize());LOGGER.info("Version of the specified PDF file: {}", pdfProperties.getDocument().getPDFVersion());LOGGER.info("Page count of the specified PDF file: {}", pdfProperties.getDocument().getPageCount());} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples from https://www.github.com/adobe/pdfservices-sdk-python-samples# Run the sample:# python src/pdfproperties/get_pdf_properties.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class GetPDFProperties:def __init__(self):try:file = open("pdfPropertiesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)pdf_properties_params = PDFPropertiesParams(include_page_level_properties=True)# Creates a new job instancepdf_properties_job = PDFPropertiesJob(input_asset=input_asset, pdf_properties_params=pdf_properties_params)# Submit the job and gets the job resultlocation = pdf_services.submit(pdf_properties_job)pdf_services_response = pdf_services.get_job_result(location, PDFPropertiesResult)pdf_properties_result = pdf_services_response.get_result()# Fetch the requisite properties of the specified PDF.print("Size of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("file_size")))print("Version of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("pdf_version")))print("Page count of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("page_count")))except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":GetPDFProperties()
Check PDF Accessibility
Check accessibility of PDF documents to see if they meet the machine-verifiable requirements of PDF/UA and WCAG 2.0. Generate an accessibility report that checks over thirty items across four categories and reports them as ‘passed’, ‘failed’, or ‘needs manual check’. Option to embed the HTML report within the PDF or export it separately as a JSON file and to specify the pages in a PDF to be checked. The API leverages the same technology as the Accessibility Checker found in Acrobat Pro.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboardcurl --location --request POST 'https://pdf-services.adobe.io/operation/accessibilitychecker' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f1878678e68","pageStart":1,"pageEnd":5}'
Add a watermark to a PDF document
Add a watermark to a PDF document using a source watermark PDF. Specify the pages to which the watermark is to be applied. This is interoperable with the Acrobat Watermark tool. Watermarks are typically added to indicate the status, classification, or branding of a document.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboardcurl --location --request POST 'https://pdf-services.adobe.io/operation/addwatermark' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"inputDocumentAssetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f68","watermarkDocumentAssetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f1878678e68","pageRanges": [{"start": 2,"end": 5},{"start": 8,"end": 10}],"appearance": {"opacity": 50,"appearOnForeground": true}}'
Split a PDF into multiple files
Split a PDF document into multiple smaller documents by simply specifying either the number of files, pages per file, or page ranges.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Split-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","splitoption": {"pageCount": 9}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-splitPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/splitpdf/split-pdf-by-number-of-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./splitPDFInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new SplitPDFParams({pageCount: 2});// Creates a new job instanceconst job = new SplitPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst _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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd SplitPDFByNumberOfPages/// dotnet run SplitPDFByNumberOfPages.csprojnamespace SplitPDFByNumberOfPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"splitPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobSplitPDFParams splitPDFParams = new SplitPDFParams();splitPDFParams.SetPageCount(2);// Creates a new job instanceSplitPDFJob splitPDFJob = new SplitPDFJob(asset, splitPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(splitPDFJob);PDFServicesResponse<SplitPDFResult> pdfServicesResponse =pdfServices.GetJobResult<SplitPDFResult>(location, typeof(SplitPDFResult));List<IAsset> resultAssets = pdfServicesResponse.Result.Assets;// Save the result to the specified location.int index = 0;foreach (IAsset resultAsset in resultAssets){// Get content from the resulting asset(s)StreamAsset streamAsset = pdfServices.GetContent(resultAsset);Stream outputStream =File.OpenWrite(Directory.GetCurrentDirectory() + "/output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf");streamAsset.Stream.CopyTo(outputStream);outputStream.Close();index++;}}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.splitpdf.SplitPDFByNumberOfPagespublic class SplitPDFByNumberOfPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(SplitPDFByNumberOfPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/splitPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobSplitPDFParams splitPDFParams = new SplitPDFParams();// Sets the maximum number of pages each of the output files can havesplitPDFParams.setPageCount(2);// Creates a new job instanceSplitPDFJob splitPDFJob = new SplitPDFJob(asset, splitPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(splitPDFJob);PDFServicesResponse<SplitPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, SplitPDFResult.class);// Get content from the resulting asset(s)List<Asset> resultAssets = pdfServicesResponse.getResult().getAssets();Files.createDirectories(Paths.get("output/"));int index = 0;for (Asset resultAsset : resultAssets) {StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itOutputStream outputStream = Files.newOutputStream(new File("output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf").toPath());LOGGER.info("Saving asset at output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();index++;}} catch (IOException| ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/splitpdf/split_pdf_by_number_of_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class SplitPDFByNumberOfPages:def __init__(self):try:file = open('splitPDFInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream,mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobsplit_pdf_params = SplitPDFParams(page_count=2)# Creates a new job instancesplit_pdf_job = SplitPDFJob(input_asset, split_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(split_pdf_job)pdf_services_response = pdf_services.get_job_result(location, SplitPDFResult)# Get content from the resulting asset(s)result_assets = pdf_services_response.get_result().get_assets()# Creates an output stream and copy stream asset's content to itoutput_file_path = 'SplitPDFByNumberOfPagesOutput.pdf'for i, result_asset in enumerate(result_assets):stream_asset: StreamAsset = pdf_services.get_content(result_asset)with open(f"{output_file_path}_{i}.pdf", "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":SplitPDFByNumberOfPages()
Combine multiple documents into a pdf file
Combine two or more documents into a single PDF file
See our public API Reference and quickly try our APIs using the Postman collections.
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-46d6-87f2-087832fca718"},{"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-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/combinepdf/combine-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream1 = 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 jobconst params = new CombinePDFParams().addAsset(inputAsset1).addAsset(inputAsset2);// Create a new job instanceconst job = new CombinePDFJob({params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CombinePDF/// dotnet run CombinePDF.csprojnamespace CombinePDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream1 = File.OpenRead(@"combineFilesInput1.pdf");using Stream inputStream2 = File.OpenRead(@"combineFilesInput2.pdf");List<IAsset> assets = pdfServices.UploadAssets(new List<StreamAsset>(){new StreamAsset(inputStream1, PDFServicesMediaType.PDF.GetMIMETypeValue()),new StreamAsset(inputStream2, PDFServicesMediaType.PDF.GetMIMETypeValue())});// Create parameters for the jobCombinePDFParams combinePDFParams = CombinePDFParams.CombinePDFParamsBuilder().AddAsset(assets[0]).AddAsset(assets[1]).Build();// Creates a new job instanceCombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(combinePDFJob);PDFServicesResponse<CombinePDFResult> pdfServicesResponse =pdfServices.GetJobResult<CombinePDFResult>(location, typeof(CombinePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/combineFilesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.combinepdf.CombinePDFpublic class CombinePDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDF.class);public static void main(String[] args) {try (InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/combineFilesInput1.pdf").toPath());InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/combineFilesInput2.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadList<StreamAsset> streamAssets = new ArrayList<>();streamAssets.add(new StreamAsset(inputStream1, PDFServicesMediaType.PDF.getMediaType()));streamAssets.add(new StreamAsset(inputStream2, PDFServicesMediaType.PDF.getMediaType()));List<Asset> assets = pdfServices.uploadAssets(streamAssets);// Create parameters for the jobCombinePDFParams combinePDFParams = CombinePDFParams.combinePDFParamsBuilder().addAsset(assets.get(0)).addAsset(assets.get(1)).build();// Creates a new job instanceCombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(combinePDFJob);PDFServicesResponse<CombinePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CombinePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/combineFilesOutput.pdf").toPath());LOGGER.info("Saving asset at output/combineFilesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/combinepdf/combine_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CombinePDF:def __init__(self):try:file = open("./combineFilesInput1.pdf", "rb")input_stream_1 = file.read()file.close()file = open("./combineFilesInput2.pdf", "rb")input_stream_2 = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadstream_assets = [StreamAsset(input_stream_1, PDFServicesMediaType.PDF),StreamAsset(input_stream_2, PDFServicesMediaType.PDF),]assets = pdf_services.upload_assets(stream_assets)# Create parameters for the jobcombine_pdf_params = (CombinePDFParams().add_asset(assets[0])).add_asset(assets[1])# Creates a new job instancecombine_pdf_job = CombinePDFJob(combine_pdf_params=combine_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(combine_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CombinePDFResult)# Get content from the resulting asset(s)result_asset: CombinePDFResult = (pdf_services_response.get_result().get_asset())stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CombinePDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CombinePDF()
Compress a pdf file
Reduce the size of PDF files by compressing to smaller sizes for lower bandwidth viewing, downloading, and sharing.
Support for multiple compression levels to retain the quality of images and graphics
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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-compressPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/compresspdf/compress-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./compressPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new CompressPDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CompressPDF/// dotnet run CompressPDF.csprojnamespace CompressPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"compressPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse =pdfServices.GetJobResult<CompressPDFResult>(location, typeof(CompressPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/compressPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.compresspdf.CompressPDFpublic class CompressPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creating an output stream and copying stream asset content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/compressPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/compresspdf/compress_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CompressPDF:def __init__(self):try:file = open("./compressPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instancecompress_pdf_job = CompressPDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(compress_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CompressPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CompressPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CompressPDF()
Reorder pages within PDF files
Reorder the pages of a PDF file to reorganize.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 3,"end": 3},{"start": 1,"end": 1},{"start": 4,"end": 4}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/reorderpages/reorder-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 orderconst params = new ReorderPagesParams({asset: inputAsset,pageRanges: getPageRangeForReorder()});// Creates a new job instanceconst job = new ReorderPagesJob({params});// Submit the job and get the job resultconst 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 itconst 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 documentconst pageRanges = new PageRanges();// Add pages 3 to 4pageRanges.addRange(3, 4);// Add page 1pageRanges.addSinglePage(1);return pageRanges;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ReorderPages/// dotnet run ReorderPDFPages.csprojnamespace ReorderPDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"reorderPagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());PageRanges pageRanges = GetPageRangeForReorder();// Create parameters for the jobReorderPagesParams reorderPagesParams = ReorderPagesParams.ReorderPagesParamsBuilder(asset, pageRanges).Build();// Creates a new job instanceReorderPagesPDFJob reorderPagesPDFJob = new ReorderPagesPDFJob(reorderPagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(reorderPagesPDFJob);PDFServicesResponse<ReorderPagesResult> pdfServicesResponse =pdfServices.GetJobResult<ReorderPagesResult>(location, typeof(ReorderPagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/reorderPagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForReorder(){// Specify order of the pages for an output document.PageRanges pageRanges = new PageRanges();// Add pages 3 to 4.pageRanges.AddRange(3, 4);// Add page 1.pageRanges.AddSinglePage(1);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.reorderpages.ReorderPDFPagespublic class ReorderPDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ReorderPDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/reorderPagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());PageRanges pagesToReorder = getPageRangeForReorder();// Create parameters for the jobReorderPagesParams reorderPagesParams = ReorderPagesParams.reorderPagesParamsBuilder(asset, pagesToReorder) // Add the asset as input to the params, along with its page order.build();// Creates a new job instanceReorderPagesPDFJob reorderPagesPDFJob = new ReorderPagesPDFJob(reorderPagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(reorderPagesPDFJob);PDFServicesResponse<ReorderPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, ReorderPagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/reorderPagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/reorderPagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForReorder() {// Specify order of the pages for an output documentPageRanges pageRanges = new PageRanges();// Add pages 3 to 4pageRanges.addRange(3, 4);// Add page 1pageRanges.addSinglePage(1);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/reorderpages/reorder_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ReorderPDFPages:def __init__(self):try:file = open("reorderPagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)pages_to_reorder = self.get_page_range_for_reorder()# Create parameters for the jobreorder_pages_params = ReorderPagesParams(asset=input_asset, page_ranges=pages_to_reorder)# Creates a new job instancereorder_pages_job = ReorderPagesJob(reorder_pages_params=reorder_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(reorder_pages_job)pdf_services_response = pdf_services.get_job_result(location, ReorderPagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "reorderPagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_range_for_reorder() -> PageRanges:# Specify order of the pages for an output documentpage_ranges = PageRanges()# Add pages 3 to 4page_ranges.add_range(3, 4)# Add page 1page_ranges.add_single_page(1)return page_rangesif __name__ == "__main__":ReorderPDFPages()
Linearize a PDF file for fast web view
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Linearize-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/linearizepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/linearizepdf/linearize-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./linearizePDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new LinearizePDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd LinearizePDF/// dotnet run LinearizePDF.csprojnamespace LinearizePDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"linearizePDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceLinearizePDFJob linearizePDFJob = new LinearizePDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(linearizePDFJob);PDFServicesResponse<LinearizePDFResult> pdfServicesResponse =pdfServices.GetJobResult<LinearizePDFResult>(location, typeof(LinearizePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/linearizePDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.linearizepdf.LinearizePDFpublic class LinearizePDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(LinearizePDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/linearizePDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceLinearizePDFJob linearizePDFJob = new LinearizePDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(linearizePDFJob);PDFServicesResponse<LinearizePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, LinearizePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/linearizePDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/linearizePDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/linearizepdf/linearize_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class LinearizePDF:def __init__(self):try:file = open("./linearizePDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instancelinearize_pdf_job = LinearizePDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(linearize_pdf_job)pdf_services_response = pdf_services.get_job_result(location, LinearizePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/LinearizePDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":LinearizePDF()
Insert a page into a PDF document
Insert one or more pages into an existing document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1,"end": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 4}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 2}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/insertpages/insert-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadbaseReadStream = 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 jobconst 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 instanceconst job = new InsertPagesJob({params});// Submit the job and get the job resultconst 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 itconst outputFilePath = "./insertPagesOutput.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();firstReadStreamToInsert?.destroy();secondReadStreamToInsert?.destroy();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd InsertPDFPages/// dotnet run InsertPDFPages.csprojnamespace InsertPDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instance.Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder().WithClientId("PDF_SERVICES_CLIENT_ID").WithClientSecret("PDF_SERVICES_CLIENT_SECRET").Build();// Create an ExecutionContext using credentials.ExecutionContext executionContext = ExecutionContext.Create(credentials);// Create a new operation instanceInsertPagesOperation insertPagesOperation = InsertPagesOperation.CreateNew();// Set operation base input from a source file.FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf");insertPagesOperation.SetBaseInput(baseSourceFile);// Create a FileRef instance using a local file.FileRef firstFileToInsert = FileRef.CreateFromLocalFile(@"firstFileToInsertInput.pdf");PageRanges pageRanges = GetPageRangeForFirstFile();// 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(firstFileToInsert, pageRanges, 2);// Create a FileRef instance using a local file.FileRef secondFileToInsert = FileRef.CreateFromLocalFile(@"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(secondFileToInsert, 3);// Execute the operation.FileRef result = insertPagesOperation.Execute(executionContext);// Save the result to the specified location.result.SaveAs(Directory.GetCurrentDirectory() + "/output/insertPagesOutput.pdf");}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);// Catch more errors here . . .}private static PageRanges GetPageRangeForFirstFile(){// Specify which pages of the first file are to be inserted in the base file.PageRanges pageRanges = new PageRanges();// Add pages 1 to 3.pageRanges.AddRange(1, 3);// Add page 4.pageRanges.AddSinglePage(4);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.insertpages.InsertPDFPagespublic class InsertPDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class);public static void main(String[] args) {try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());InputStream firstInputStreamToInsert = Files.newInputStream(new File("src/main/resources/firstFileToInsertInput.pdf").toPath());InputStream secondInputStreamToInsert = Files.newInputStream(new File("src/main/resources/secondFileToInsertInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());Asset firstAssetToInsert = pdfServices.upload(firstInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());Asset secondAssetToInsert = pdfServices.upload(secondInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());PageRanges pageRanges = getPageRangeForFirstFile();// Create parameters for the jobInsertPagesParams insertPagesParams = InsertPagesParams.insertPagesParamsBuilder(baseAsset).addPagesToInsertAt(firstAssetToInsert, pageRanges, 2) // Add the first asset as input to the params, along with its page ranges and base page.addPagesToInsertAt(secondAssetToInsert, 3) // Add the seccond asset as input to the params, along with base page.build();// Creates a new job instanceInsertPagesPDFJob insertPagesJob = new InsertPagesPDFJob(insertPagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(insertPagesJob);PDFServicesResponse<InsertPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, InsertPagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/insertPagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/insertPagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForFirstFile() {// Specify which pages of the first file are to be inserted in the base filePageRanges pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4.pageRanges.addSinglePage(4);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/insertpages/insert_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class InsertPDFPages:def __init__(self):try:base_file = open("baseInput.pdf", "rb")base_input_stream = base_file.read()base_file.close()first_file_to_insert = open("firstFileToInsertInput.pdf", "rb")first_input_stream_to_insert = first_file_to_insert.read()first_file_to_insert.close()second_file_to_insert = open("secondFileToInsertInput.pdf", "rb")second_input_stream_to_insert = second_file_to_insert.read()second_file_to_insert.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadbase_asset = pdf_services.upload(input_stream=base_input_stream, mime_type=PDFServicesMediaType.PDF)first_asset_to_insert = pdf_services.upload(input_stream=first_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)second_asset_to_insert = pdf_services.upload(input_stream=second_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)page_ranges = self.get_page_range_for_first_file()# Create parameters for the jobinsert_pages_params = InsertPagesParams(base_asset=base_asset)# Add the first asset as input to the params, along with its page ranges and base pageinsert_pages_params.add_pages_to_insert(input_asset=first_asset_to_insert, page_ranges=page_ranges, base_page=2)# Add the second asset as input to the params, along with base pageinsert_pages_params.add_pages_to_insert(input_asset=second_asset_to_insert, base_page=3)# Creates a new job instanceinsert_pages_job = InsertPagesJob(insert_pages_params=insert_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(insert_pages_job)pdf_services_response = pdf_services.get_job_result(location, InsertPagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "insertpagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_range_for_first_file() -> PageRanges:# Specify which pages of the first file are to be included in the combined filepage_ranges_for_first_file = PageRanges()# Add pages 1 to 3page_ranges_for_first_file.add_range(1, 3)# Add single page 1page_ranges_for_first_file.add_single_page(1)return page_ranges_for_first_fileif __name__ == "__main__":InsertPDFPages()
Replace a page within a PDF file
Replace one or more pages with another page in an existing document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1,"end": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 2}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 3}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/replacepages/replace-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadbaseReadStream = 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 jobconst 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 instanceconst job = new ReplacePagesJob({params});// Submit the job and get the job resultconst 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 itconst 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 fileconst pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4pageRanges.addSinglePage(4);return pageRanges;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ReplacePDFPages/// dotnet run ReplacePDFPages.csprojnamespace ReplacePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream baseInputStream = File.OpenRead(@"baseInput.pdf");using Stream firstInputStream = File.OpenRead(@"replacePagesInput1.pdf");using Stream secondInputStream = File.OpenRead(@"replacePagesInput2.pdf");IAsset baseAsset = pdfServices.Upload(baseInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset firstAssetToReplace =pdfServices.Upload(firstInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset secondAssetToReplace =pdfServices.Upload(secondInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());PageRanges pageRanges = GetPageRangeForFirstFile();// Create parameters for the jobReplacePagesParams replacePagesParams = ReplacePagesParams.ReplacePagesParamsBuilder(baseAsset).AddPagesForReplace(firstAssetToReplace, pageRanges, 1).AddPagesForReplace(secondAssetToReplace, 3).Build();// Creates a new job instanceReplacePagesPDFJob replacePagesPDFJob = new ReplacePagesPDFJob(replacePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(replacePagesPDFJob);PDFServicesResponse<ReplacePagesResult> pdfServicesResponse =pdfServices.GetJobResult<ReplacePagesResult>(location, typeof(ReplacePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/replacePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForFirstFile(){// Specify pages of the first file for replacing the page of base PDF file.PageRanges pageRanges = new PageRanges();// Add pages 1 to 3.pageRanges.AddRange(1, 3);// Add page 4.pageRanges.AddSinglePage(4);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.replacepages.ReplacePDFPagespublic class ReplacePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ReplacePDFPages.class);public static void main(String[] args) {try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/replacePagesInput1.pdf").toPath());InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/replacePagesInput2.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());Asset asset1 = pdfServices.upload(inputStream1, PDFServicesMediaType.PDF.getMediaType());Asset asset2 = pdfServices.upload(inputStream2, PDFServicesMediaType.PDF.getMediaType());PageRanges pageRanges = getPageRangeForFirstFile();// Create parameters for the jobReplacePagesParams replacePagesParams = ReplacePagesParams.replacePagesParamsBuilder(baseAsset).addPagesForReplace(asset1, pageRanges, 1) // Add the first asset as input to the params, along with its page ranges and base page.addPagesForReplace(asset2, 3) // Add the second asset as input to the params, along with base page.build();// Creates a new job instanceReplacePagesPDFJob replacePagesPDFJob = new ReplacePagesPDFJob(replacePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(replacePagesPDFJob);PDFServicesResponse<ReplacePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, ReplacePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/replacePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/replacePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForFirstFile() {// Specify pages of the first file for replacing the page of base PDF filePageRanges pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4pageRanges.addSinglePage(4);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/replacepages/replace_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ReplacePDFPages:def __init__(self):try:base_file = open('baseInput.pdf', 'rb')base_input_stream = base_file.read()base_file.close()file_1 = open('replacePagesInput1.pdf', 'rb')input_stream_1 = file_1.read()file_1.close()file_2 = open('replacePagesInput2.pdf', 'rb')input_stream_2 = file_2.read()file_2.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadbase_asset = pdf_services.upload(input_stream=base_input_stream,mime_type=PDFServicesMediaType.PDF)asset_1 = pdf_services.upload(input_stream=input_stream_1,mime_type=PDFServicesMediaType.PDF)asset_2 = pdf_services.upload(input_stream=input_stream_2,mime_type=PDFServicesMediaType.PDF)page_ranges = self.get_page_range_for_first_file()# Create parameters for the jobreplace_pages_params = ReplacePagesParams(base_asset=base_asset)# Add the first asset as input to the params, along with its page ranges and base pagereplace_pages_params.add_pages_to_replace(input_asset=asset_1, page_ranges=page_ranges, base_page=1)# Add the second asset as input to the params, along with base pagereplace_pages_params.add_pages_to_replace(input_asset=asset_2, base_page=3)# Creates a new job instancereplace_pages_job = ReplacePagesJob(replace_pages_params=replace_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(replace_pages_job)pdf_services_response = pdf_services.get_job_result(location, ReplacePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "replacePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')@staticmethoddef get_page_range_for_first_file() -> PageRanges:# Specify page rangespage_ranges = PageRanges()# Add pages 1 to 3page_ranges.add_range(1, 3)# Add page 4page_ranges.add_single_page(4)return page_rangesif __name__ == "__main__":ReplacePDFPages()
Delete a page from a PDF file
Delete one or more pages from a document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulationcurl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageActions": [{"delete": {"pageRanges": [{"start": 1,"end": 2}]}}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/deletepages/delete-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 jobconst params = new DeletePagesParams({pageRanges: pageRangeForDeletion});// Creates a new job instanceconst job = new DeletePagesJob({inputAsset, params});// Submit the job and get the job resultconst 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 itconst 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;};
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd DeletePDFPages/// dotnet run DeletePDFPages.csprojnamespace DeletePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"deletePagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Delete pages of the document (as specified by PageRanges).PageRanges pageRangeForDeletion = GetPageRangeForDeletion();// Create parameters for the jobDeletePagesParams deletePagesParams = new DeletePagesParams(pageRangeForDeletion);// Creates a new job instanceDeletePagesJob deletePagesJob = new DeletePagesJob(asset, deletePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(deletePagesJob);PDFServicesResponse<DeletePagesResult> pdfServicesResponse =pdfServices.GetJobResult<DeletePagesResult>(location, typeof(DeletePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/deletePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForDeletion(){// Specify pages for deletion.PageRanges pageRangeForDeletion = new PageRanges();// Add page 1.pageRangeForDeletion.AddSinglePage(1);// Add pages 3 to 4.pageRangeForDeletion.AddRange(3, 4);return pageRangeForDeletion;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.deletepages.DeletePDFPagespublic class DeletePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(DeletePDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/deletePagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Delete pages of the document (as specified by PageRanges).PageRanges pageRangeForDeletion = getPageRangeForDeletion();// Create parameters for the jobDeletePagesParams deletePagesParams = new DeletePagesParams(pageRangeForDeletion);// Creates a new job instanceDeletePagesJob deletePagesJob = new DeletePagesJob(asset, deletePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(deletePagesJob);PDFServicesResponse<DeletePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, DeletePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/deletePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/deletePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForDeletion() {// Specify pages for deletionPageRanges pageRangeForDeletion = new PageRanges();// Add page 1pageRangeForDeletion.addSinglePage(1);// Add pages 3 to 4pageRangeForDeletion.addRange(3, 4);return pageRangeForDeletion;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/deletepages/delete_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class DeletePDFPages:def __init__(self):try:file = open("deletePagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Delete pages of the document (as specified by PageRanges).page_ranges_for_deletion = self.get_page_ranges_for_deletion()# Create parameters for the jobdelete_pages_params = DeletePagesParams(page_ranges=page_ranges_for_deletion)# Creates a new job instancedelete_pages_job = DeletePagesJob(input_asset=input_asset, delete_pages_params=delete_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(delete_pages_job)pdf_services_response = pdf_services.get_job_result(location, DeletePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "deletePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_ranges_for_deletion() -> PageRanges:# Specify pages for deletionpage_range_for_deletion = PageRanges()# Add page 1page_range_for_deletion.add_single_page(1)# Add pages 3 to 4page_range_for_deletion.add_range(3, 4)return page_range_for_deletionif __name__ == "__main__":DeletePDFPages()
Rotate a page in a PDF file
Rotate a page in an existing document.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulationcurl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718f","pageActions": [{"rotate": {"angle": 90,"pageRanges": [{"start": 1}]}},{"rotate": {"angle": 180,"pageRanges": [{"start": 2,"end": 2}]}}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/rotatepages/rotate-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 fileconst firstPageRange = getFirstPageRangeForRotation();// Second set of page ranges for rotating the specified pages of the input PDF fileconst secondPageRange = getSecondPageRangeForRotation();// Create parameters for the jobconst params = new RotatePagesParams().setAngleToRotatePagesBy(Angle._90, firstPageRange).setAngleToRotatePagesBy(Angle._180, secondPageRange);// Creates a new job instanceconst job = new RotatePagesJob({inputAsset, params});// Submit the job and get the job resultconst 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 itconst 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 PageRanges();// Add page 1.firstPageRange.addSinglePage(1);// Add pages 3 to 4.firstPageRange.addRange(3, 4);return firstPageRange;}function getSecondPageRangeForRotation() {// Specify pages for rotation.const secondPageRange = new PageRanges();// Add page 2.secondPageRange.addSinglePage(2);return secondPageRange;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd RotatePDFPages/// dotnet run RotatePDFPages.csprojnamespace RotatePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"rotatePagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of// the input PDF file.PageRanges firstPageRange = GetFirstPageRangeForRotation();// Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of// the input PDF file.PageRanges secondPageRange = GetSecondPageRangeForRotation();// Create parameters for the jobRotatePagesParams rotatePagesParams = RotatePagesParams.RotatePagesParamsBuilder().withAngleToRotatePagesBy(Angle._90, firstPageRange).withAngleToRotatePagesBy(Angle._180, secondPageRange).Build();// Creates a new job instanceRotatePagesJob rotatePagesJob = new RotatePagesJob(asset, rotatePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(rotatePagesJob);PDFServicesResponse<RotatePagesResult> pdfServicesResponse =pdfServices.GetJobResult<RotatePagesResult>(location, typeof(RotatePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/rotatePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}private static PageRanges GetFirstPageRangeForRotation(){// Specify pages for rotation.PageRanges firstPageRange = new PageRanges();// Add page 1.firstPageRange.AddSinglePage(1);// Add pages 3 to 4.firstPageRange.AddRange(3, 4);return firstPageRange;}private static PageRanges GetSecondPageRangeForRotation(){// Specify pages for rotation.PageRanges secondPageRange = new PageRanges();// Add page 2.secondPageRange.AddSinglePage(2);return secondPageRange;}// Generates a string containing a directory structure and file name for the output file.private static String CreateOutputFilePath(){String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");return ("/output/rotate" + timeStamp + ".pdf");}}}
Copied to your clipboard// 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.rotatepages.RotatePDFPagespublic class RotatePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(RotatePDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/rotatePagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// First set of page ranges for rotating the specified pages of the input PDF file.PageRanges firstPageRange = getFirstPageRangeForRotation();// Second set of page ranges for rotating the specified pages of the input PDF file.PageRanges secondPageRange = getSecondPageRangeForRotation();// Create parameters for the jobRotatePagesParams rotatePagesParams = RotatePagesParams.rotatePagesParamsBuilder().withAngleToRotatePagesBy(Angle._90, firstPageRange).withAngleToRotatePagesBy(Angle._180, secondPageRange).build();// Creates a new job instanceRotatePagesJob rotatePagesJob = new RotatePagesJob(asset, rotatePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(rotatePagesJob);PDFServicesResponse<RotatePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, RotatePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/rotatePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/rotatePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getFirstPageRangeForRotation() {// Specify pages for rotationPageRanges firstPageRange = new PageRanges();// Add page 1firstPageRange.addSinglePage(1);// Add pages 3 to 4firstPageRange.addRange(3, 4);return firstPageRange;}private static PageRanges getSecondPageRangeForRotation() {// Specify pages for rotation.PageRanges secondPageRange = new PageRanges();// Add page 2.secondPageRange.addSinglePage(2);return secondPageRange;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/rotatepages/rotate_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class RotatePDFPages:def __init__(self):try:file = open("rotatePagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# First set of page ranges for rotating the specified pages of the input PDF file.first_page_range: PageRanges = self.get_first_page_range_for_rotation()# Second set of page ranges for rotating the specified pages of the input PDF file.second_page_range: PageRanges = self.get_second_page_range_for_rotation()# Create parameters for the jobrotate_pages_params = RotatePagesParams()rotate_pages_params.add_angle_to_rotate_for_page_ranges(angle=Angle.ANGLE_90, page_ranges=first_page_range)rotate_pages_params.add_angle_to_rotate_for_page_ranges(angle=Angle.ANGLE_180, page_ranges=second_page_range)# Creates a new job instancereorder_pages_job = RotatePagesJob(input_asset=input_asset, rotate_pages_params=rotate_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(reorder_pages_job)pdf_services_response = pdf_services.get_job_result(location, RotatePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "rotatePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_first_page_range_for_rotation() -> PageRanges:# Specify pages for rotationfirst_page_range = PageRanges()# Add page 1first_page_range.add_single_page(1)# Add pages 3 to 4first_page_range.add_range(3, 4)return first_page_range@staticmethoddef get_second_page_range_for_rotation() -> PageRanges:# Specify pages for rotationsecond_page_range = PageRanges()# Add page 2second_page_range.add_single_page(2)return second_page_rangeif __name__ == "__main__":RotatePDFPages()
PDF content extraction
Extract text, images, tables, and more from native and scanned PDFs into a structured JSON file. PDF Extract API leverages AI technology to accurately identify text objects and understand the natural reading order of different elements such as headings, lists, and paragraphs spanning multiple columns or pages. Extract font styles with identification of metadata such as bold and italic text and their position within your PDF. Extracted content is output in a structured JSON file format with tables in CSV or XLSX and images saved as PNG.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Extract-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/extractpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","elementsToExtract": ["text"]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-extractPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/extractpdf/extract-text-info-from-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./extractPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ExtractPDFParams({elementsToExtract: [ExtractElementType.TEXT]});// Creates a new job instanceconst job = new ExtractPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ExtractTextInfoFromPDF/// dotnet run ExtractTextInfoFromPDF.csprojnamespace ExtractTextInfoFromPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the logging.ConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"extractPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobExtractPDFParams extractPDFParams = ExtractPDFParams.ExtractPDFParamsBuilder().AddElementToExtract(ExtractElementType.TEXT).Build();// Creates a new job instanceExtractPDFJob extractPDFJob = new ExtractPDFJob(asset).SetParams(extractPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(extractPDFJob);PDFServicesResponse<ExtractPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ExtractPDFResult>(location, typeof(ExtractPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Resource;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/ExtractTextInfoFromPDF.zip";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.extractpdf.ExtractTextInfoFromPDFpublic class ExtractTextInfoFromPDF {private static final Logger LOGGER = LoggerFactory.getLogger(ExtractTextInfoFromPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/extractPdfInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobExtractPDFParams extractPDFParams = ExtractPDFParams.extractPDFParamsBuilder().addElementsToExtract(Arrays.asList(ExtractElementType.TEXT)).build();// Creates a new job instanceExtractPDFJob extractPDFJob = new ExtractPDFJob(asset).setParams(extractPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(extractPDFJob);PDFServicesResponse<ExtractPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ExtractPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getResource();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/ExtractTextInfoFromPDF.zip").toPath());LOGGER.info("Saving asset at output/ExtractTextInfoFromPDF.zip");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/extractpdf/extract_text_info_from_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ExtractTextInfoFromPDF:def __init__(self):try:file = open("extractPdfInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobextract_pdf_params = ExtractPDFParams(elements_to_extract=[ExtractElementType.TEXT],)# Creates a new job instanceextract_pdf_job = ExtractPDFJob(input_asset=input_asset, extract_pdf_params=extract_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(extract_pdf_job)pdf_services_response = pdf_services.get_job_result(location, ExtractPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_resource()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "extractTextInfoFromPDF.zip"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ExtractTextInfoFromPDF()
Adobe PDF Accessibility Auto-Tag API
Tag PDFs to improve accessibility. Identify the content structure and reading order, and tag tables, paragraphs, lists, headings, figures, and more to improve the reading experience of native or scanned PDFs with assistive technologies. Generate a tailored tagging report about added tags and any content that needs additional review.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our REST API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-Accessibility-Auto-Tagcurl --location --request POST 'https://pdf-services.adobe.io/operation/autotag' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"}'
Copied to your clipboard// Get the samples from https://github.com/adobe/pdfservices-node-sdk-samples// Run the sample:// node src/autotagpdf/autotag-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./autotagPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new AutotagPDFJob({inputAsset});// Submit the job and get the job resultconst 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 streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates an output stream and copy stream asset's content to itconst 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();}})();
Copied to your clipboard// Get the samples from https://github.com/adobe/PDFServices.NET.SDK.Samples// Run the sample:// cd AutotagPDF/// dotnet run AutotagPDF.csprojnamespace AutotagPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"autotagPdfInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceAutotagPDFJob autotagPDFJob = new AutotagPDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(autotagPDFJob);PDFServicesResponse<AutotagPDFResult> pdfServicesResponse =pdfServices.GetJobResult<AutotagPDFResult>(location, typeof(AutotagPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.TaggedPDF;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/autotagPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from https://github.com/adobe/pdfservices-java-sdk-samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.autotagpdf.AutotagPDFpublic class AutotagPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(AutotagPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/autotagPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceAutotagPDFJob autotagPDFJob = new AutotagPDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(autotagPDFJob);PDFServicesResponse<AutotagPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, AutotagPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getTaggedPDF();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/autotagPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/autotagPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/autotagpdf/autotag_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class AutoTagPDF:def __init__(self):try:file = open("autotagPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instanceautotag_pdf_job = AutotagPDFJob(input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(autotag_pdf_job)pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = (pdf_services_response.get_result().get_tagged_pdf())stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "autoTagPDFOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":AutoTagPDF()
Create a PDF file
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
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/createpdf/create-pdf-from-docx.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./createPDFInput.docx");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.DOCX});// Creates a new job instanceconst job = new CreatePDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CreatePDFFromDocx/// dotnet run CreatePDFFromDocx.csprojnamespace CreatePDFFromDocx{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"createPdfInput.docx");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());// Creates a new job instanceCreatePDFJob createPDFJob = new CreatePDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(createPDFJob);PDFServicesResponse<CreatePDFResult> pdfServicesResponse =pdfServices.GetJobResult<CreatePDFResult>(location, typeof(CreatePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/createPdfOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.createpdf.CreatePDFFromDOCXpublic class CreatePDFFromDOCX {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDOCX.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFInput.docx").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());// Creates a new job instanceCreatePDFJob createPDFJob = new CreatePDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(createPDFJob);PDFServicesResponse<CreatePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CreatePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFile.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/createPDFFromDOCX.pdf").toPath());LOGGER.info("Saving asset at output/createPDFFromDOCX.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing the operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/createpdf/create_pdf_from_docx.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CreatePDFFromDOCX:def __init__(self):try:file = open("./createPDFInput.docx", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)# Creates a new job instancecreate_pdf_job = CreatePDFJob(input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(create_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CreatePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CreatePDFFromDOCX.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CreatePDFFromDOCX()
Create a PDF file from HTML
Create PDFs from static and dynamic HTML, Zip, and URL.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","json": "{}","includeHeaderFooter": true,"pageLayout": {"pageWidth": 11,"pageHeight": 8.5}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-htmlToPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/htmltopdf/static-html-to-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./createPDFFromStaticHtmlInput.zip");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.ZIP});// Create parameters for the jobconst params = getHTMLToPDFParams();// Creates a new job instanceconst job = new HTMLToPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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,});}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd StaticHTMLToPDF/// dotnet run StaticHTMLToPDF.csprojnamespace StaticHTMLToPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"createPDFFromStaticHtmlInput.zip");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.ZIP.GetMIMETypeValue());// Create parameters for the jobHTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();// Creates a new job instanceHTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(asset).SetParams(htmlToPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(htmlToPDFJob);PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/createPdfFromStaticHtmlOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static HTMLToPDFParams GetHTMLToPDFParams(){// Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).PageLayout pageLayout = new PageLayout();pageLayout.SetPageSize(8, 11.5);// Set the desired HTML-to-PDF conversion options.HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder().IncludeHeaderFooter(true).WithPageLayout(pageLayout).Build();return htmlToPDFParams;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.createpdf.CreatePDFFromStaticHTML// 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.htmltopdf.StaticHTMLToPDFpublic class StaticHTMLToPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(StaticHTMLToPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFFromStaticHtmlInput.zip").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.ZIP.getMediaType());// Create parameters for the jobHTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();// Creates a new job instanceHTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(asset).setParams(htmlToPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(htmLtoPDFJob);PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFile.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/staticHTMLToPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/staticHTMLToPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}private static HTMLToPDFParams getHTMLToPDFParams() {// Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)PageLayout pageLayout = new PageLayout();pageLayout.setPageSize(8, 11.5);return new HTMLToPDFParams.Builder().includeHeaderFooter(true).withPageLayout(pageLayout).build();}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/htmltopdf/static_html_to_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class StaticHTMLtoPDF:def __init__(self):try:file = open('./createPDFFromStaticHtmlInput.zip', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.ZIP)# Create parameters for the jobhtml_to_pdf_params = self.get_html_to_pdf_params()# Creates a new job instancehtml_to_pdf_job = HTMLtoPDFJob(input_asset=input_asset, html_to_pdf_params=html_to_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(html_to_pdf_job)pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'output/StaticHTMLToPDF.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')@staticmethoddef get_html_to_pdf_params() -> HTMLtoPDFParams:# Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)page_layout = PageLayout(page_height=11.5, page_width=8)return HTMLtoPDFParams(page_layout=page_layout, include_header_footer=True)if __name__ == "__main__":StaticHTMLtoPDF()
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Document-Generationcurl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","outputFormat": "pdf","jsonDataForMerge": {"customerName": "Kane Miller","customerVisits": 100,"itemsBought": [{"name": "Sprays","quantity": 50,"amount": 100},{"name": "Chemicals","quantity": 100,"amount": 200}],"totalAmount": 300,"previousBalance": 50,"lastThreeBillings": [100,200,300],"photograph": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP88h8AAu0B9XNPCQQAAAAASUVORK5CYII="}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/documentmerge/merge-document-to-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Setup input data for the document merge processconst jsonDataForMerge = {customerName: "Kane Miller",customerVisits: 100}// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./documentMergeTemplate.docx");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.DOCX});// Create parameters for the jobconst params = new DocumentMergeParams({jsonDataForMerge,outputFormat: OutputFormat.PDF});// Creates a new job instanceconst job = new DocumentMergeJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd MergeDocumentToPDF/// dotnet run MergeDocumentToPDF.csprojnamespace MergeDocumentToPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"documentMergeTemplate.docx");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());// Setup input data for the document merge processJObject jsonDataForMerge = JObject.Parse("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.DocumentMergeParamsBuilder().WithJsonDataForMerge(jsonDataForMerge).WithOutputFormat(OutputFormat.PDF).Build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submits the job and gets the job resultString location = pdfServices.Submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse =pdfServices.GetJobResult<DocumentMergeResult>(location, typeof(DocumentMergeResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/documentMergeOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.MergeDocumentToPDFpackage com.adobe.pdfservices.operation.samples.documentmerge;public class MergeDocumentToPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(MergeDocumentToPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/documentMergeTemplate.docx").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Setup input data for the document merge process.JSONObject jsonDataForMerge = new JSONObject("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.documentMergeParamsBuilder().withJsonDataForMerge(jsonDataForMerge).withOutputFormat(OutputFormat.PDF).build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submit the job and gets the job resultString location = pdfServices.submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse = pdfServices.getJobResult(location, DocumentMergeResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itOutputStream outputStream = Files.newOutputStream(new File("output/documentMergeOutput.pdf").toPath());IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/documentmerge/merge_document_to_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class MergeDocumentToPDF:def __init__(self):try:file = open("./salesOrderTemplate.docx", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)# Setup input data for the document merge processwith open("./salesOrder.json", "r") as file:content_string = file.read()json_data_for_merge = json.loads(content_string)# Create parameters for the jobdocument_merge_params = DocumentMergeParams(json_data_for_merge=json_data_for_merge, output_format=OutputFormat.PDF)# Creates a new job instancedocument_merge_job = DocumentMergeJob(input_asset=input_asset, document_merge_params=document_merge_params)# Submit the job and gets the job resultlocation = pdf_services.submit(document_merge_job)pdf_services_response = pdf_services.get_job_result(location, DocumentMergePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/MergeDocumentToPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":MergeDocumentToPDF()
PDF Electronic Seal API
Apply an electronic seal to documents at scale using a certificate issued by certain TSPs (Trust Service Providers) on Adobe’s Approved Trust List (AATL). The electronic seal helps verify the identity and integrity of documents.
See our public API Reference and quickly try our APIs using the Postman collections.
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer-stage.adobe.com/document-services/docs/apis/#tag/PDF-Electronic-Sealcurl --location --request POST 'https://pdf-services.adobe.io/operation/electronicseal' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"inputDocumentAssetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-xxxx-xxxx-087832fca718","sealImageAssetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-xxxx-xxxx-087832fca718","sealOptions": {"signatureFormat": "PKCS7","cscCredentialOptions": {"credentialId": "<CREDENTIAL_ID>","providerName": "<PROVIDER_NAME>","authorizationContext": {"tokenType": "Bearer","accessToken": "<ACCESS_TOKEN>"},"credentialAuthParameters": {"pin": "<PIN>"}},"sealFieldOptions": {"location": {"top": 300,"left": 50,"right": 250,"bottom": 100},"fieldName": "Signature1","pageNumber": 1},"sealAppearanceOptions": {"displayOptions": ["NAME","DATE","DISTINGUISHED_NAME","LABELS","SEAL_IMAGE"]}}}'
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/electronicseal/electronic-seal.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadsourceFileReadStream = 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 documentconst documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Set the Seal Field Name to be created in input PDF documentconst sealFieldName = "Signature1";// Set the page number in input document for applying sealconst sealPageNumber = 1;// Set if seal should be visible or invisibleconst sealVisible = true;// Create FieldLocation instance and set the coordinates for applying signatureconst fieldLocation = new FieldLocation({left: 150,top: 250,right: 350,bottom: 200});// Create FieldOptions instance with required detailsconst sealFieldOptions = new FieldOptions({visible: sealVisible,location: fieldLocation,fieldName: sealFieldName,pageNumber: sealPageNumber,});// Set the name of TSP Provider being usedconst providerName = "<PROVIDER_NAME>";// Set the access token to be used to access TSP provider hosted APIsconst accessToken = "<ACCESS_TOKEN>";// Set the credential IDconst credentialId = "<CREDENTIAL_ID>";// Set the PIN generated while creating credentialsconst pin = "<PIN>";// Create CSCAuthContext instance using access token and token typeconst authorizationContext = new CSCAuthContext({accessToken,tokenType: "Bearer"});// Create CertificateCredentials instance with required certificate detailsconst certificateCredentials = new CSCCredential({providerName,credentialId,pin,authorizationContext,});// Create parameters for the jobconst params = new PDFElectronicSealParams({certificateCredentials,sealFieldOptions,documentLevelPermission,});// Creates a new job instanceconst job = new PDFElectronicSealJob({inputAsset: sourceFileAsset,sealImageAsset,params,});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ElectronicSeal/// dotnet run ElectronicSeal.csprojnamespace ElectronicSeal{class Program{// Initialize the logger.private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"SampleInvoice.pdf");using Stream inputStreamSealImage = File.OpenRead(@"sampleSealImage.png");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset sealImageAsset =pdfServices.Upload(inputStreamSealImage, PDFServicesMediaType.PNG.GetMIMETypeValue());// Set the document level permission to be applied for output documentDocumentLevelPermission documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Sets the Seal Field Name to be created in input PDF document.String sealFieldName = "Signature1";// Sets the page number in input document for applying seal.int sealPageNumber = 1;// Sets if seal should be visible or invisible.bool sealVisible = true;// Creates FieldLocation instance and set the coordinates for applying signatureFieldLocation fieldLocation = new FieldLocation(150, 250, 350, 200);// Create FieldOptions instance with required details.FieldOptions fieldOptions = new FieldOptions.Builder(sealFieldName).SetVisible(sealVisible).SetFieldLocation(fieldLocation).SetPageNumber(sealPageNumber).Build();// Sets the name of TSP Provider being used.String providerName = "<PROVIDER_NAME>";// Sets the access token to be used to access TSP provider hosted APIs.String accessToken = "<ACCESS_TOKEN>";// Sets the credential ID.String credentialID = "<CREDENTIAL_ID>";// Sets the PIN generated while creating credentials.String pin = "<PIN>";// Creates CSCAuthContext instance using access token and token type.CSCAuthContext cscAuthContext = new CSCAuthContext(accessToken, "Bearer");// Create CertificateCredentials instance with required certificate details.CertificateCredentials certificateCredentials = CertificateCredentials.CSCCredentialBuilder().WithProviderName(providerName).WithCredentialID(credentialID).WithPin(pin).WithCSCAuthContext(cscAuthContext).Build();// Create parameters for the jobPDFElectronicSealParams pdfElectronicSealParams =PDFElectronicSealParams.PDFElectronicSealParamsBuilder(certificateCredentials, fieldOptions).WithDocumentLevelPermission(documentLevelPermission).Build();// Creates a new job instancePDFElectronicSealJob pdfElectronicSealJob = new PDFElectronicSealJob(asset, pdfElectronicSealParams);pdfElectronicSealJob.SetSealImageAsset(sealImageAsset);// Submits the job and gets the job resultString location = pdfServices.Submit(pdfElectronicSealJob);PDFServicesResponse<PDFElectronicSealResult> pdfServicesResponse =pdfServices.GetJobResult<PDFElectronicSealResult>(location, typeof(PDFElectronicSealResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/sealedOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.electronicseal.ElectronicSealpublic class ElectronicSeal {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ElectronicSeal.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/sampleInvoice.pdf").toPath());InputStream inputStreamSealImage = Files.newInputStream(new File("src/main/resources/sampleSealImage.png").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());Asset sealImageAsset = pdfServices.upload(inputStreamSealImage, PDFServicesMediaType.PNG.getMediaType());// Set the document level permission to be applied for output documentDocumentLevelPermission documentLevelPermission = DocumentLevelPermission.FORM_FILLING;// Sets the Seal Field Name to be created in input PDF document.String sealFieldName = "Signature1";// Sets the page number in input document for applying seal.Integer sealPageNumber = 1;// Sets if seal should be visible or invisible.Boolean sealVisible = true;// Creates FieldLocation instance and set the coordinates for applying signatureFieldLocation fieldLocation = new FieldLocation(150, 250, 350, 200);// Create FieldOptions instance with required details.FieldOptions fieldOptions = new FieldOptions.Builder(sealFieldName).setFieldLocation(fieldLocation).setPageNumber(sealPageNumber).setVisible(sealVisible).build();// Sets the name of TSP Provider being used.String providerName = "<PROVIDER_NAME>";// Sets the access token to be used to access TSP provider hosted APIs.String accessToken = "<ACCESS_TOKEN>";// Sets the credential ID.String credentialID = "<CREDENTIAL_ID>";// Sets the PIN generated while creating credentials.String pin = "<PIN>";// Creates CSCAuthContext instance using access token and token type.CSCAuthContext cscAuthContext = new CSCAuthContext(accessToken, "Bearer");// Create CertificateCredentials instance with required certificate details.CertificateCredentials certificateCredentials = CertificateCredentials.cscCredentialBuilder().withProviderName(providerName).withCredentialID(credentialID).withPin(pin).withCSCAuthContext(cscAuthContext).build();// Create parameters for the jobPDFElectronicSealParams pdfElectronicSealParams = PDFElectronicSealParams.pdfElectronicSealParamsBuilder(certificateCredentials, fieldOptions).withDocumentLevelPermission(documentLevelPermission).build();// Creates a new job instancePDFElectronicSealJob pdfElectronicSealJob = new PDFElectronicSealJob(asset, pdfElectronicSealParams);// Sets the optional input seal image for PDFElectronicSealOperation instancepdfElectronicSealJob.setSealImageAsset(sealImageAsset);// Submit the job and gets the job resultString location = pdfServices.submit(pdfElectronicSealJob);PDFServicesResponse<PDFElectronicSealResult> pdfServicesResponse = pdfServices.getJobResult(location, PDFElectronicSealResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/sealedOutput.pdf").toPath());LOGGER.info("Saving asset at output/sealedOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ElectronicSeal:def __init__(self):try:pdf_file = open("./sampleInvoice.pdf", "rb")file_input_stream = pdf_file.read()pdf_file.close()seal_image_file = open("./sampleSealImage.png", "rb")seal_image_input_stream = seal_image_file.read()seal_image_file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadasset = pdf_services.upload(input_stream=file_input_stream, mime_type=PDFServicesMediaType.PDF)seal_image_asset = pdf_services.upload(input_stream=seal_image_input_stream, mime_type=PDFServicesMediaType.PNG)# Set the document level permission to be applied for output documentdocument_level_permission = DocumentLevelPermission.FORM_FILLING# Sets the Seal Field Name to be created in input PDF document.seal_field_name = "Signature1"# Sets the page number in input document for applying seal.seal_page_number = 1# Sets if seal should be visible or invisible.seal_visible = True# Creates FieldLocation instance and set the coordinates for applying signaturefield_location = FieldLocation(150, 250, 350, 200)# Create FieldOptions instance with required details.field_options = FieldOptions(field_name=seal_field_name,field_location=field_location,page_number=seal_page_number,visible=seal_visible,)# Sets the name of TSP Provider being used.provider_name = "<PROVIDER_NAME>"# Sets the access token to be used to access TSP provider hosted APIs.access_token = "<ACCESS_TOKEN>"# Sets the credential ID.credential_id = "<CREDENTIAL_ID>"# Sets the PIN generated while creating credentials.pin = "<PIN>"# Creates CSCAuthContext instance using access token and token type.csc_auth_context = CSCAuthContext(access_token=access_token,token_type="Bearer",)# Create CertificateCredentials instance with required certificate details.certificate_credentials = CSCCredentials(provider_name=provider_name,credential_id=credential_id,pin=pin,csc_auth_context=csc_auth_context,)# Create parameters for the jobelectronic_seal_params = PDFElectronicSealParams(seal_certificate_credentials=certificate_credentials,seal_field_options=field_options,)# Creates a new job instanceelectronic_seal_job = PDFElectronicSealJob(input_asset=asset,electronic_seal_params=electronic_seal_params,seal_image_asset=seal_image_asset,)# Submit the job and gets the job resultlocation = pdf_services.submit(electronic_seal_job)pdf_services_response = pdf_services.get_job_result(location, ESealPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/ElectronicSeal.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ElectronicSeal()
Convert a PDF file to other formats
Convert existing PDFs to popular formats, such as Microsoft Word, Excel, and PowerPoint, as well as text and image
Support for PDF to DOC, PDF to DOCX, PDF to JPEG, PDF to PNG, PDF to PPTX, PDF to RTF, PDF to XLSX
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Export-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/exportpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/exportpdftoimages/export-pdf-to-jpeg.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./exportPDFToImageInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ExportPDFToImagesParams({targetFormat: ExportPDFToImagesTargetFormat.JPEG,outputType: ExportPDFToImagesOutputType.LIST_OF_PAGE_IMAGES});// Creates a new job instanceconst job = new ExportPDFToImagesJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ExportPDFToDocx/// dotnet run ExportPDFToDocx.csprojnamespace ExportPDFToDocx{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"exportPdfInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobExportPDFParams exportPDFParams = ExportPDFParams.ExportPDFParamsBuilder(ExportPDFTargetFormat.DOCX).Build();// Creates a new job instanceExportPDFJob exportPDFJob = new ExportPDFJob(asset, exportPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(exportPDFJob);PDFServicesResponse<ExportPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ExportPDFResult>(location, typeof(ExportPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itStream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + "/output/exportPdfOutput.docx");streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.exportpdf.ExportPDFToDOCXpublic class ExportPDFToDOCX {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ExportPDFToDOCX.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/exportPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobExportPDFParams exportPDFParams = ExportPDFParams.exportPDFParamsBuilder(ExportPDFTargetFormat.DOCX).build();// Creates a new job instanceExportPDFJob exportPDFJob = new ExportPDFJob(asset, exportPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(exportPDFJob);PDFServicesResponse<ExportPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ExportPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/exportPdfOutput.docx").toPath());LOGGER.info("Saving asset at output/exportPdfOutput.docx");IOUtils.copy(streamAsset.getInputStream(), outputStream);} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python python src/exportpdftoimages/export_pdf_to_jpeg.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ExportPDFToDOCX:def __init__(self):try:file = open("./exportPDFToImageInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobexport_pdf_to_images_params = ExportPDFtoImagesParams(export_pdf_to_images_target_format=ExportPDFToImagesTargetFormat.JPEG,export_pdf_to_images_output_type=ExportPDFToImagesOutputType.LIST_OF_PAGE_IMAGES,)# Creates a new job instanceexport_pdf_to_images_job = ExportPDFtoImagesJob(input_asset=input_asset,export_pdf_to_images_params=export_pdf_to_images_params,)# Submit the job and gets the job resultlocation = pdf_services.submit(export_pdf_to_images_job)pdf_services_response = pdf_services.get_job_result(location, ExportPDFtoImagesResult)# Get content from the resulting asset(s)result_assets = pdf_services_response.get_result().get_assets()output_file_path = "output/ExportPDFToImages"for (asset_index, asset) in enumerate(result_assets):save_output_file_path = f"{output_file_path}_{asset_index}.jpeg"stream_asset: StreamAsset = pdf_services.get_content(asset)# Creates an output stream and copy stream asset's content to itwith open(save_output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ExportPDFtoJPEG()
OCR a PDF file
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Ocrcurl --location --request POST 'https://pdf-services.adobe.io/operation/ocr' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/ocr/ocr-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./ocrInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new OCRJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd OcrPDF/// dotnet run OcrPDF.csprojnamespace OcrPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"ocrInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceOCRJob ocrJob = new OCRJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(ocrJob);PDFServicesResponse<OCRResult> pdfServicesResponse =pdfServices.GetJobResult<OCRResult>(location, typeof(OCRResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/ocrOperationOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.ocrpdf.OcrPDFpublic class OcrPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/ocrInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceOCRJob ocrJob = new OCRJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(ocrJob);PDFServicesResponse<OCRResult> pdfServicesResponse = pdfServices.getJobResult(location, OCRResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/ocrOutput.pdf").toPath());LOGGER.info("Saving asset at output/ocrOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/ocrpdf/ocr_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class OcrPDF(object):def __init__(self):try:file = open("./ocrInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instanceocr_pdf_job = OCRPDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(ocr_pdf_job)pdf_services_response = pdf_services.get_job_result(location, OCRPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/OcrPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":OcrPDF()
Secure a PDf file and set restrictions
Secure a PDF file with a password encrypt the document. Set an owner password and restrictions on certain features like printing, editing and copying in the PDF document to prevent end users from modifying it.
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Protect-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/protectpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"passwordProtection": {"userPassword": "user_password"},"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/protectpdf/protect-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./protectPDFInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new ProtectPDFParams({userPassword: "password",encryptionAlgorithm: EncryptionAlgorithm.AES_256});// Create a new job instanceconst job = new ProtectPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst outputFilePath = "./protectPDFOutput.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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ProtectPDF/// dotnet run ProtectPDF.csprojnamespace ProtectPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"protectPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobProtectPDFParams protectPDFParams = ProtectPDFParams.PasswordProtectParamsBuilder().SetUserPassword("password").SetEncryptionAlgorithm(EncryptionAlgorithm.AES_256).Build();// Creates a new job instanceProtectPDFJob protectPDFJob = new ProtectPDFJob(asset, protectPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(protectPDFJob);PDFServicesResponse<ProtectPDFResult> pdfServicesResponse =pdfServices.GetJobResult<ProtectPDFResult>(location, typeof(ProtectPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/protectPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}// Generates a string containing a directory structure and file name for the output file.private static String CreateOutputFilePath(){String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");return ("/output/protect" + timeStamp + ".pdf");}}}
Copied to your clipboard// 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.protectpdf.ProtectPDFpublic class ProtectPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ProtectPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/protectPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobProtectPDFParams protectPDFParams = ProtectPDFParams.passwordProtectOptionsBuilder().setUserPassword("password").setEncryptionAlgorithm(EncryptionAlgorithm.AES_256).build();// Creates a new job instanceProtectPDFJob protectPDFJob = new ProtectPDFJob(asset, protectPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(protectPDFJob);PDFServicesResponse<ProtectPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, ProtectPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/protectPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/protectPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/protectpdf/protect_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ProtectPDF:def __init__(self):try:file = open("./protectPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobprotect_pdf_params = PasswordProtectParams(user_password="password",encryption_algorithm=EncryptionAlgorithm.AES_256,content_encryption=ContentEncryption.ALL_CONTENT,)# Creates a new job instanceprotect_pdf_job = ProtectPDFJob(input_asset=input_asset, protect_pdf_params=protect_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(protect_pdf_job)pdf_services_response = pdf_services.get_job_result(location, ProtectPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/ProtectPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":ProtectPDF()
Remove the password from a PDF file
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Remove-Protectioncurl --location --request POST 'https://pdf-services.adobe.io/operation/removeprotection' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/removeprotection/remove-protection.jsconst {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 instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./removeProtectionInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new RemoveProtectionParams({password: "password"});// Creates a new job instanceconst job = new RemoveProtectionJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd RemoveProtection/// dotnet run RemoveProtection.csprojnamespace RemoveProtection{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"removeProtectionInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobRemoveProtectionParams removeProtectionParams = new RemoveProtectionParams("password");// Creates a new job instanceRemoveProtectionJob removeProtectionJob = new RemoveProtectionJob(asset, removeProtectionParams);// Submits the job and gets the job resultString location = pdfServices.Submit(removeProtectionJob);PDFServicesResponse<RemoveProtectionResult> pdfServicesResponse =pdfServices.GetJobResult<RemoveProtectionResult>(location, typeof(RemoveProtectionResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/removeProtectionOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.removeprotection.RemoveProtectionpublic class RemoveProtection {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(RemoveProtection.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/removeProtectionInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobRemoveProtectionParams removeProtectionParams = new RemoveProtectionParams("password");// Creates a new job instanceRemoveProtectionJob removeProtectionJob = new RemoveProtectionJob(asset, removeProtectionParams);// Submit the job and gets the job resultString location = pdfServices.submit(removeProtectionJob);PDFServicesResponse<RemoveProtectionResult> pdfServicesResponse = pdfServices.getJobResult(location, RemoveProtectionResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/removeProtectionOutput.pdf").toPath());LOGGER.info("Saving asset at output/removeProtectionOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/removeprotection/remove_protection.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class RemoveProtection:def __init__(self):try:file = open('removeProtectionInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobremove_protection_params = RemoveProtectionParams(password="password")# Creates a new job instanceremove_protection_job = RemoveProtectionJob(input_asset=input_asset,remove_protection_params=remove_protection_params)# Submit the job and gets the job resultlocation = pdf_services.submit(remove_protection_job)pdf_services_response = pdf_services.get_job_result(location, RemoveProtectionResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'removeProtectionOutput.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":RemoveProtection()
Get the properties of a PDF file
Use this service to get the metadata properties of a PDF. Metadata including page count, PDF version, file size, compliance levels, font info, permissions and more are provided in JSON format for easy processing.
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/PDF-Propertiescurl --location --request POST 'https://pdf-services.adobe.io/operation/pdfproperties' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/pdfproperties/get-pdf-properties.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./pdfPropertiesInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new PDFPropertiesParams({includePageLevelProperties: true});// Creates a new job instanceconst job = new PDFPropertiesJob({inputAsset,params});// Submit the job and get the job resultconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd PDFPropertiesAsJSONObject/// dotnet run GetPDFProperties.csprojnamespace GetPDFProperties{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"pdfPropertiesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobPDFPropertiesParams pdfPropertiesParams = PDFPropertiesParams.PDFPropertiesParamsBuilder().IncludePageLevelProperties().Build();// Creates a new job instancePDFPropertiesJob pdfPropertiesJob = new PDFPropertiesJob(asset);pdfPropertiesJob.SetParams(pdfPropertiesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(pdfPropertiesJob);PDFServicesResponse<PDFPropertiesResult> pdfServicesResponse =pdfServices.GetJobResult<PDFPropertiesResult>(location, typeof(PDFPropertiesResult));PDFProperties pdfProperties = pdfServicesResponse.Result.PDFProperties;// Fetch the requisite properties of the specified PDF.Console.WriteLine("The resultant PDF Properties are: " + pdfProperties.ToString());}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.pdfproperties.GetPDFPropertiespublic class GetPDFProperties {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(GetPDFProperties.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/pdfPropertiesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Create parameters for the jobPDFPropertiesParams pdfPropertiesParams = PDFPropertiesParams.pdfPropertiesParamsBuilder().includePageLevelProperties().build();// Creates a new job instancePDFPropertiesJob pdfPropertiesJob = new PDFPropertiesJob(asset).setParams(pdfPropertiesParams);// Submit the job and gets the job resultString location = pdfServices.submit(pdfPropertiesJob);PDFServicesResponse<PDFPropertiesResult> pdfServicesResponse = pdfServices.getJobResult(location, PDFPropertiesResult.class);PDFProperties pdfProperties = pdfServicesResponse.getResult().getPdfProperties();// Fetch the requisite properties of the specified PDF.LOGGER.info("Size of the specified PDF file: {}", pdfProperties.getDocument().getFileSize());LOGGER.info("Version of the specified PDF file: {}", pdfProperties.getDocument().getPDFVersion());LOGGER.info("Page count of the specified PDF file: {}", pdfProperties.getDocument().getPageCount());} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples from https://www.github.com/adobe/pdfservices-sdk-python-samples# Run the sample:# python src/pdfproperties/get_pdf_properties.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class GetPDFProperties:def __init__(self):try:file = open("pdfPropertiesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)pdf_properties_params = PDFPropertiesParams(include_page_level_properties=True)# Creates a new job instancepdf_properties_job = PDFPropertiesJob(input_asset=input_asset, pdf_properties_params=pdf_properties_params)# Submit the job and gets the job resultlocation = pdf_services.submit(pdf_properties_job)pdf_services_response = pdf_services.get_job_result(location, PDFPropertiesResult)pdf_properties_result = pdf_services_response.get_result()# Fetch the requisite properties of the specified PDF.print("Size of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("file_size")))print("Version of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("pdf_version")))print("Page count of the specified PDF file:"+ str(pdf_properties_result.get_pdf_properties_dict().get("document").get("page_count")))except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":GetPDFProperties()
Check PDF Accessibility
Check accessibility of PDF documents to see if they meet the machine-verifiable requirements of PDF/UA and WCAG 2.0. Generate an accessibility report that checks over thirty items across four categories and reports them as ‘passed’, ‘failed’, or ‘needs manual check’. Option to embed the HTML report within the PDF or export it separately as a JSON file and to specify the pages in a PDF to be checked. The API leverages the same technology as the Accessibility Checker found in Acrobat Pro.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboardcurl --location --request POST 'https://pdf-services.adobe.io/operation/accessibilitychecker' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f1878678e68","pageStart":1,"pageEnd":5}'
Add a watermark to a PDF document
Add a watermark to a PDF document using a source watermark PDF. Specify the pages to which the watermark is to be applied. This is interoperable with the Acrobat Watermark tool. Watermarks are typically added to indicate the status, classification, or branding of a document.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboardcurl --location --request POST 'https://pdf-services.adobe.io/operation/addwatermark' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"inputDocumentAssetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f68","watermarkDocumentAssetID": "urn:aaid:AS:UE1:54cbf87f-d7f5-4918-8e4b-9f1878678e68","pageRanges": [{"start": 2,"end": 5},{"start": 8,"end": 10}],"appearance": {"opacity": 50,"appearOnForeground": true}}'
Split a PDF into multiple files
Split a PDF document into multiple smaller documents by simply specifying either the number of files, pages per file, or page ranges.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Split-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/splitpdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","splitoption": {"pageCount": 9}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-splitPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/splitpdf/split-pdf-by-number-of-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./splitPDFInput.pdf")const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Create parameters for the jobconst params = new SplitPDFParams({pageCount: 2});// Creates a new job instanceconst job = new SplitPDFJob({inputAsset,params});// Submit the job and get the job resultconst 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 itconst _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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd SplitPDFByNumberOfPages/// dotnet run SplitPDFByNumberOfPages.csprojnamespace SplitPDFByNumberOfPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"splitPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobSplitPDFParams splitPDFParams = new SplitPDFParams();splitPDFParams.SetPageCount(2);// Creates a new job instanceSplitPDFJob splitPDFJob = new SplitPDFJob(asset, splitPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(splitPDFJob);PDFServicesResponse<SplitPDFResult> pdfServicesResponse =pdfServices.GetJobResult<SplitPDFResult>(location, typeof(SplitPDFResult));List<IAsset> resultAssets = pdfServicesResponse.Result.Assets;// Save the result to the specified location.int index = 0;foreach (IAsset resultAsset in resultAssets){// Get content from the resulting asset(s)StreamAsset streamAsset = pdfServices.GetContent(resultAsset);Stream outputStream =File.OpenWrite(Directory.GetCurrentDirectory() + "/output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf");streamAsset.Stream.CopyTo(outputStream);outputStream.Close();index++;}}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.splitpdf.SplitPDFByNumberOfPagespublic class SplitPDFByNumberOfPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(SplitPDFByNumberOfPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/splitPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobSplitPDFParams splitPDFParams = new SplitPDFParams();// Sets the maximum number of pages each of the output files can havesplitPDFParams.setPageCount(2);// Creates a new job instanceSplitPDFJob splitPDFJob = new SplitPDFJob(asset, splitPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(splitPDFJob);PDFServicesResponse<SplitPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, SplitPDFResult.class);// Get content from the resulting asset(s)List<Asset> resultAssets = pdfServicesResponse.getResult().getAssets();Files.createDirectories(Paths.get("output/"));int index = 0;for (Asset resultAsset : resultAssets) {StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itOutputStream outputStream = Files.newOutputStream(new File("output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf").toPath());LOGGER.info("Saving asset at output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();index++;}} catch (IOException| ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/splitpdf/split_pdf_by_number_of_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class SplitPDFByNumberOfPages:def __init__(self):try:file = open('splitPDFInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream,mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobsplit_pdf_params = SplitPDFParams(page_count=2)# Creates a new job instancesplit_pdf_job = SplitPDFJob(input_asset, split_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(split_pdf_job)pdf_services_response = pdf_services.get_job_result(location, SplitPDFResult)# Get content from the resulting asset(s)result_assets = pdf_services_response.get_result().get_assets()# Creates an output stream and copy stream asset's content to itoutput_file_path = 'SplitPDFByNumberOfPagesOutput.pdf'for i, result_asset in enumerate(result_assets):stream_asset: StreamAsset = pdf_services.get_content(result_asset)with open(f"{output_file_path}_{i}.pdf", "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":SplitPDFByNumberOfPages()
Combine multiple documents into a pdf file
Combine two or more documents into a single PDF file
See our public API Reference and quickly try our APIs using the Postman collections.
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-46d6-87f2-087832fca718"},{"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-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/combinepdf/combine-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream1 = 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 jobconst params = new CombinePDFParams().addAsset(inputAsset1).addAsset(inputAsset2);// Create a new job instanceconst job = new CombinePDFJob({params});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CombinePDF/// dotnet run CombinePDF.csprojnamespace CombinePDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream1 = File.OpenRead(@"combineFilesInput1.pdf");using Stream inputStream2 = File.OpenRead(@"combineFilesInput2.pdf");List<IAsset> assets = pdfServices.UploadAssets(new List<StreamAsset>(){new StreamAsset(inputStream1, PDFServicesMediaType.PDF.GetMIMETypeValue()),new StreamAsset(inputStream2, PDFServicesMediaType.PDF.GetMIMETypeValue())});// Create parameters for the jobCombinePDFParams combinePDFParams = CombinePDFParams.CombinePDFParamsBuilder().AddAsset(assets[0]).AddAsset(assets[1]).Build();// Creates a new job instanceCombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(combinePDFJob);PDFServicesResponse<CombinePDFResult> pdfServicesResponse =pdfServices.GetJobResult<CombinePDFResult>(location, typeof(CombinePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/combineFilesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.combinepdf.CombinePDFpublic class CombinePDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDF.class);public static void main(String[] args) {try (InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/combineFilesInput1.pdf").toPath());InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/combineFilesInput2.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadList<StreamAsset> streamAssets = new ArrayList<>();streamAssets.add(new StreamAsset(inputStream1, PDFServicesMediaType.PDF.getMediaType()));streamAssets.add(new StreamAsset(inputStream2, PDFServicesMediaType.PDF.getMediaType()));List<Asset> assets = pdfServices.uploadAssets(streamAssets);// Create parameters for the jobCombinePDFParams combinePDFParams = CombinePDFParams.combinePDFParamsBuilder().addAsset(assets.get(0)).addAsset(assets.get(1)).build();// Creates a new job instanceCombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(combinePDFJob);PDFServicesResponse<CombinePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CombinePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/combineFilesOutput.pdf").toPath());LOGGER.info("Saving asset at output/combineFilesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/combinepdf/combine_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CombinePDF:def __init__(self):try:file = open("./combineFilesInput1.pdf", "rb")input_stream_1 = file.read()file.close()file = open("./combineFilesInput2.pdf", "rb")input_stream_2 = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadstream_assets = [StreamAsset(input_stream_1, PDFServicesMediaType.PDF),StreamAsset(input_stream_2, PDFServicesMediaType.PDF),]assets = pdf_services.upload_assets(stream_assets)# Create parameters for the jobcombine_pdf_params = (CombinePDFParams().add_asset(assets[0])).add_asset(assets[1])# Creates a new job instancecombine_pdf_job = CombinePDFJob(combine_pdf_params=combine_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(combine_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CombinePDFResult)# Get content from the resulting asset(s)result_asset: CombinePDFResult = (pdf_services_response.get_result().get_asset())stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CombinePDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CombinePDF()
Compress a pdf file
Reduce the size of PDF files by compressing to smaller sizes for lower bandwidth viewing, downloading, and sharing.
Support for multiple compression levels to retain the quality of images and graphics
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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-compressPDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/compresspdf/compress-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./compressPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new CompressPDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CompressPDF/// dotnet run CompressPDF.csprojnamespace CompressPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"compressPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse =pdfServices.GetJobResult<CompressPDFResult>(location, typeof(CompressPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/compressPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.compresspdf.CompressPDFpublic class CompressPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creating an output stream and copying stream asset content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/compressPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/compresspdf/compress_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CompressPDF:def __init__(self):try:file = open("./compressPDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instancecompress_pdf_job = CompressPDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(compress_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CompressPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/CompressPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":CompressPDF()
Reorder pages within PDF files
Reorder the pages of a PDF file to reorganize.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 3,"end": 3},{"start": 1,"end": 1},{"start": 4,"end": 4}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/reorderpages/reorder-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 orderconst params = new ReorderPagesParams({asset: inputAsset,pageRanges: getPageRangeForReorder()});// Creates a new job instanceconst job = new ReorderPagesJob({params});// Submit the job and get the job resultconst 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 itconst 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 documentconst pageRanges = new PageRanges();// Add pages 3 to 4pageRanges.addRange(3, 4);// Add page 1pageRanges.addSinglePage(1);return pageRanges;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ReorderPages/// dotnet run ReorderPDFPages.csprojnamespace ReorderPDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"reorderPagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());PageRanges pageRanges = GetPageRangeForReorder();// Create parameters for the jobReorderPagesParams reorderPagesParams = ReorderPagesParams.ReorderPagesParamsBuilder(asset, pageRanges).Build();// Creates a new job instanceReorderPagesPDFJob reorderPagesPDFJob = new ReorderPagesPDFJob(reorderPagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(reorderPagesPDFJob);PDFServicesResponse<ReorderPagesResult> pdfServicesResponse =pdfServices.GetJobResult<ReorderPagesResult>(location, typeof(ReorderPagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/reorderPagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForReorder(){// Specify order of the pages for an output document.PageRanges pageRanges = new PageRanges();// Add pages 3 to 4.pageRanges.AddRange(3, 4);// Add page 1.pageRanges.AddSinglePage(1);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.reorderpages.ReorderPDFPagespublic class ReorderPDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ReorderPDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/reorderPagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());PageRanges pagesToReorder = getPageRangeForReorder();// Create parameters for the jobReorderPagesParams reorderPagesParams = ReorderPagesParams.reorderPagesParamsBuilder(asset, pagesToReorder) // Add the asset as input to the params, along with its page order.build();// Creates a new job instanceReorderPagesPDFJob reorderPagesPDFJob = new ReorderPagesPDFJob(reorderPagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(reorderPagesPDFJob);PDFServicesResponse<ReorderPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, ReorderPagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/reorderPagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/reorderPagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForReorder() {// Specify order of the pages for an output documentPageRanges pageRanges = new PageRanges();// Add pages 3 to 4pageRanges.addRange(3, 4);// Add page 1pageRanges.addSinglePage(1);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/reorderpages/reorder_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ReorderPDFPages:def __init__(self):try:file = open("reorderPagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)pages_to_reorder = self.get_page_range_for_reorder()# Create parameters for the jobreorder_pages_params = ReorderPagesParams(asset=input_asset, page_ranges=pages_to_reorder)# Creates a new job instancereorder_pages_job = ReorderPagesJob(reorder_pages_params=reorder_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(reorder_pages_job)pdf_services_response = pdf_services.get_job_result(location, ReorderPagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "reorderPagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_range_for_reorder() -> PageRanges:# Specify order of the pages for an output documentpage_ranges = PageRanges()# Add pages 3 to 4page_ranges.add_range(3, 4)# Add page 1page_ranges.add_single_page(1)return page_rangesif __name__ == "__main__":ReorderPDFPages()
Linearize a PDF file for fast web view
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.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Linearize-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/linearizepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--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
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/linearizepdf/linearize-pdf.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./linearizePDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new LinearizePDFJob({inputAsset});// Submit the job and get the job resultconst 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 itconst 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();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd LinearizePDF/// dotnet run LinearizePDF.csprojnamespace LinearizePDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"linearizePDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceLinearizePDFJob linearizePDFJob = new LinearizePDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(linearizePDFJob);PDFServicesResponse<LinearizePDFResult> pdfServicesResponse =pdfServices.GetJobResult<LinearizePDFResult>(location, typeof(LinearizePDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/linearizePDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.linearizepdf.LinearizePDFpublic class LinearizePDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(LinearizePDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/linearizePDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceLinearizePDFJob linearizePDFJob = new LinearizePDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(linearizePDFJob);PDFServicesResponse<LinearizePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, LinearizePDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/linearizePDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/linearizePDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/linearizepdf/linearize_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class LinearizePDF:def __init__(self):try:file = open("./linearizePDFInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Creates a new job instancelinearize_pdf_job = LinearizePDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(linearize_pdf_job)pdf_services_response = pdf_services.get_job_result(location, LinearizePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/LinearizePDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":LinearizePDF()
Insert a page into a PDF document
Insert one or more pages into an existing document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1,"end": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 4}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 2}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/insertpages/insert-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadbaseReadStream = 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 jobconst 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 instanceconst job = new InsertPagesJob({params});// Submit the job and get the job resultconst 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 itconst outputFilePath = "./insertPagesOutput.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();firstReadStreamToInsert?.destroy();secondReadStreamToInsert?.destroy();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd InsertPDFPages/// dotnet run InsertPDFPages.csprojnamespace InsertPDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instance.Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder().WithClientId("PDF_SERVICES_CLIENT_ID").WithClientSecret("PDF_SERVICES_CLIENT_SECRET").Build();// Create an ExecutionContext using credentials.ExecutionContext executionContext = ExecutionContext.Create(credentials);// Create a new operation instanceInsertPagesOperation insertPagesOperation = InsertPagesOperation.CreateNew();// Set operation base input from a source file.FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf");insertPagesOperation.SetBaseInput(baseSourceFile);// Create a FileRef instance using a local file.FileRef firstFileToInsert = FileRef.CreateFromLocalFile(@"firstFileToInsertInput.pdf");PageRanges pageRanges = GetPageRangeForFirstFile();// 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(firstFileToInsert, pageRanges, 2);// Create a FileRef instance using a local file.FileRef secondFileToInsert = FileRef.CreateFromLocalFile(@"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(secondFileToInsert, 3);// Execute the operation.FileRef result = insertPagesOperation.Execute(executionContext);// Save the result to the specified location.result.SaveAs(Directory.GetCurrentDirectory() + "/output/insertPagesOutput.pdf");}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);// Catch more errors here . . .}private static PageRanges GetPageRangeForFirstFile(){// Specify which pages of the first file are to be inserted in the base file.PageRanges pageRanges = new PageRanges();// Add pages 1 to 3.pageRanges.AddRange(1, 3);// Add page 4.pageRanges.AddSinglePage(4);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.insertpages.InsertPDFPagespublic class InsertPDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class);public static void main(String[] args) {try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());InputStream firstInputStreamToInsert = Files.newInputStream(new File("src/main/resources/firstFileToInsertInput.pdf").toPath());InputStream secondInputStreamToInsert = Files.newInputStream(new File("src/main/resources/secondFileToInsertInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());Asset firstAssetToInsert = pdfServices.upload(firstInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());Asset secondAssetToInsert = pdfServices.upload(secondInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());PageRanges pageRanges = getPageRangeForFirstFile();// Create parameters for the jobInsertPagesParams insertPagesParams = InsertPagesParams.insertPagesParamsBuilder(baseAsset).addPagesToInsertAt(firstAssetToInsert, pageRanges, 2) // Add the first asset as input to the params, along with its page ranges and base page.addPagesToInsertAt(secondAssetToInsert, 3) // Add the seccond asset as input to the params, along with base page.build();// Creates a new job instanceInsertPagesPDFJob insertPagesJob = new InsertPagesPDFJob(insertPagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(insertPagesJob);PDFServicesResponse<InsertPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, InsertPagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/insertPagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/insertPagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForFirstFile() {// Specify which pages of the first file are to be inserted in the base filePageRanges pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4.pageRanges.addSinglePage(4);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/insertpages/insert_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class InsertPDFPages:def __init__(self):try:base_file = open("baseInput.pdf", "rb")base_input_stream = base_file.read()base_file.close()first_file_to_insert = open("firstFileToInsertInput.pdf", "rb")first_input_stream_to_insert = first_file_to_insert.read()first_file_to_insert.close()second_file_to_insert = open("secondFileToInsertInput.pdf", "rb")second_input_stream_to_insert = second_file_to_insert.read()second_file_to_insert.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadbase_asset = pdf_services.upload(input_stream=base_input_stream, mime_type=PDFServicesMediaType.PDF)first_asset_to_insert = pdf_services.upload(input_stream=first_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)second_asset_to_insert = pdf_services.upload(input_stream=second_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)page_ranges = self.get_page_range_for_first_file()# Create parameters for the jobinsert_pages_params = InsertPagesParams(base_asset=base_asset)# Add the first asset as input to the params, along with its page ranges and base pageinsert_pages_params.add_pages_to_insert(input_asset=first_asset_to_insert, page_ranges=page_ranges, base_page=2)# Add the second asset as input to the params, along with base pageinsert_pages_params.add_pages_to_insert(input_asset=second_asset_to_insert, base_page=3)# Creates a new job instanceinsert_pages_job = InsertPagesJob(insert_pages_params=insert_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(insert_pages_job)pdf_services_response = pdf_services.get_job_result(location, InsertPagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "insertpagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_range_for_first_file() -> PageRanges:# Specify which pages of the first file are to be included in the combined filepage_ranges_for_first_file = PageRanges()# Add pages 1 to 3page_ranges_for_first_file.add_range(1, 3)# Add single page 1page_ranges_for_first_file.add_single_page(1)return page_ranges_for_first_fileif __name__ == "__main__":InsertPDFPages()
Replace a page within a PDF file
Replace one or more pages with another page in an existing document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1,"end": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 2}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 3}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/replacepages/replace-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadbaseReadStream = 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 jobconst 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 instanceconst job = new ReplacePagesJob({params});// Submit the job and get the job resultconst 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 itconst 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 fileconst pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4pageRanges.addSinglePage(4);return pageRanges;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd ReplacePDFPages/// dotnet run ReplacePDFPages.csprojnamespace ReplacePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream baseInputStream = File.OpenRead(@"baseInput.pdf");using Stream firstInputStream = File.OpenRead(@"replacePagesInput1.pdf");using Stream secondInputStream = File.OpenRead(@"replacePagesInput2.pdf");IAsset baseAsset = pdfServices.Upload(baseInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset firstAssetToReplace =pdfServices.Upload(firstInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());IAsset secondAssetToReplace =pdfServices.Upload(secondInputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());PageRanges pageRanges = GetPageRangeForFirstFile();// Create parameters for the jobReplacePagesParams replacePagesParams = ReplacePagesParams.ReplacePagesParamsBuilder(baseAsset).AddPagesForReplace(firstAssetToReplace, pageRanges, 1).AddPagesForReplace(secondAssetToReplace, 3).Build();// Creates a new job instanceReplacePagesPDFJob replacePagesPDFJob = new ReplacePagesPDFJob(replacePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(replacePagesPDFJob);PDFServicesResponse<ReplacePagesResult> pdfServicesResponse =pdfServices.GetJobResult<ReplacePagesResult>(location, typeof(ReplacePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/replacePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForFirstFile(){// Specify pages of the first file for replacing the page of base PDF file.PageRanges pageRanges = new PageRanges();// Add pages 1 to 3.pageRanges.AddRange(1, 3);// Add page 4.pageRanges.AddSinglePage(4);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.replacepages.ReplacePDFPagespublic class ReplacePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(ReplacePDFPages.class);public static void main(String[] args) {try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/replacePagesInput1.pdf").toPath());InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/replacePagesInput2.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());Asset asset1 = pdfServices.upload(inputStream1, PDFServicesMediaType.PDF.getMediaType());Asset asset2 = pdfServices.upload(inputStream2, PDFServicesMediaType.PDF.getMediaType());PageRanges pageRanges = getPageRangeForFirstFile();// Create parameters for the jobReplacePagesParams replacePagesParams = ReplacePagesParams.replacePagesParamsBuilder(baseAsset).addPagesForReplace(asset1, pageRanges, 1) // Add the first asset as input to the params, along with its page ranges and base page.addPagesForReplace(asset2, 3) // Add the second asset as input to the params, along with base page.build();// Creates a new job instanceReplacePagesPDFJob replacePagesPDFJob = new ReplacePagesPDFJob(replacePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(replacePagesPDFJob);PDFServicesResponse<ReplacePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, ReplacePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/replacePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/replacePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForFirstFile() {// Specify pages of the first file for replacing the page of base PDF filePageRanges pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4pageRanges.addSinglePage(4);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/replacepages/replace_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class ReplacePDFPages:def __init__(self):try:base_file = open('baseInput.pdf', 'rb')base_input_stream = base_file.read()base_file.close()file_1 = open('replacePagesInput1.pdf', 'rb')input_stream_1 = file_1.read()file_1.close()file_2 = open('replacePagesInput2.pdf', 'rb')input_stream_2 = file_2.read()file_2.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadbase_asset = pdf_services.upload(input_stream=base_input_stream,mime_type=PDFServicesMediaType.PDF)asset_1 = pdf_services.upload(input_stream=input_stream_1,mime_type=PDFServicesMediaType.PDF)asset_2 = pdf_services.upload(input_stream=input_stream_2,mime_type=PDFServicesMediaType.PDF)page_ranges = self.get_page_range_for_first_file()# Create parameters for the jobreplace_pages_params = ReplacePagesParams(base_asset=base_asset)# Add the first asset as input to the params, along with its page ranges and base pagereplace_pages_params.add_pages_to_replace(input_asset=asset_1, page_ranges=page_ranges, base_page=1)# Add the second asset as input to the params, along with base pagereplace_pages_params.add_pages_to_replace(input_asset=asset_2, base_page=3)# Creates a new job instancereplace_pages_job = ReplacePagesJob(replace_pages_params=replace_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(replace_pages_job)pdf_services_response = pdf_services.get_job_result(location, ReplacePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "replacePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')@staticmethoddef get_page_range_for_first_file() -> PageRanges:# Specify page rangespage_ranges = PageRanges()# Add pages 1 to 3page_ranges.add_range(1, 3)# Add page 4page_ranges.add_single_page(4)return page_rangesif __name__ == "__main__":ReplacePDFPages()
Delete a page from a PDF file
Delete one or more pages from a document
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulationcurl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageActions": [{"delete": {"pageRanges": [{"start": 1,"end": 2}]}}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/deletepages/delete-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 jobconst params = new DeletePagesParams({pageRanges: pageRangeForDeletion});// Creates a new job instanceconst job = new DeletePagesJob({inputAsset, params});// Submit the job and get the job resultconst 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 itconst 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;};
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd DeletePDFPages/// dotnet run DeletePDFPages.csprojnamespace DeletePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"deletePagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Delete pages of the document (as specified by PageRanges).PageRanges pageRangeForDeletion = GetPageRangeForDeletion();// Create parameters for the jobDeletePagesParams deletePagesParams = new DeletePagesParams(pageRangeForDeletion);// Creates a new job instanceDeletePagesJob deletePagesJob = new DeletePagesJob(asset, deletePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(deletePagesJob);PDFServicesResponse<DeletePagesResult> pdfServicesResponse =pdfServices.GetJobResult<DeletePagesResult>(location, typeof(DeletePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/deletePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}private static PageRanges GetPageRangeForDeletion(){// Specify pages for deletion.PageRanges pageRangeForDeletion = new PageRanges();// Add page 1.pageRangeForDeletion.AddSinglePage(1);// Add pages 3 to 4.pageRangeForDeletion.AddRange(3, 4);return pageRangeForDeletion;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// 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.deletepages.DeletePDFPagespublic class DeletePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(DeletePDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/deletePagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Delete pages of the document (as specified by PageRanges).PageRanges pageRangeForDeletion = getPageRangeForDeletion();// Create parameters for the jobDeletePagesParams deletePagesParams = new DeletePagesParams(pageRangeForDeletion);// Creates a new job instanceDeletePagesJob deletePagesJob = new DeletePagesJob(asset, deletePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(deletePagesJob);PDFServicesResponse<DeletePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, DeletePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/deletePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/deletePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForDeletion() {// Specify pages for deletionPageRanges pageRangeForDeletion = new PageRanges();// Add page 1pageRangeForDeletion.addSinglePage(1);// Add pages 3 to 4pageRangeForDeletion.addRange(3, 4);return pageRangeForDeletion;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/deletepages/delete_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class DeletePDFPages:def __init__(self):try:file = open("deletePagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# Delete pages of the document (as specified by PageRanges).page_ranges_for_deletion = self.get_page_ranges_for_deletion()# Create parameters for the jobdelete_pages_params = DeletePagesParams(page_ranges=page_ranges_for_deletion)# Creates a new job instancedelete_pages_job = DeletePagesJob(input_asset=input_asset, delete_pages_params=delete_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(delete_pages_job)pdf_services_response = pdf_services.get_job_result(location, DeletePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "deletePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_ranges_for_deletion() -> PageRanges:# Specify pages for deletionpage_range_for_deletion = PageRanges()# Add page 1page_range_for_deletion.add_single_page(1)# Add pages 3 to 4page_range_for_deletion.add_range(3, 4)return page_range_for_deletionif __name__ == "__main__":DeletePDFPages()
Rotate a page in a PDF file
Rotate a page in an existing document.
See our public API Reference and quickly try our APIs using the Postman collections
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Page-Manipulationcurl --location --request POST 'https://pdf-services.adobe.io/operation/pagemanipulation' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718f","pageActions": [{"rotate": {"angle": 90,"pageRanges": [{"start": 1}]}},{"rotate": {"angle": 180,"pageRanges": [{"start": 2,"end": 2}]}}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-pageManipulation
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/rotatepages/rotate-pdf-pages.jsconst {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 instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = 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 fileconst firstPageRange = getFirstPageRangeForRotation();// Second set of page ranges for rotating the specified pages of the input PDF fileconst secondPageRange = getSecondPageRangeForRotation();// Create parameters for the jobconst params = new RotatePagesParams().setAngleToRotatePagesBy(Angle._90, firstPageRange).setAngleToRotatePagesBy(Angle._180, secondPageRange);// Creates a new job instanceconst job = new RotatePagesJob({inputAsset, params});// Submit the job and get the job resultconst 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 itconst 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 PageRanges();// Add page 1.firstPageRange.addSinglePage(1);// Add pages 3 to 4.firstPageRange.addRange(3, 4);return firstPageRange;}function getSecondPageRangeForRotation() {// Specify pages for rotation.const secondPageRange = new PageRanges();// Add page 2.secondPageRange.addSinglePage(2);return secondPageRange;}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd RotatePDFPages/// dotnet run RotatePDFPages.csprojnamespace RotatePDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"rotatePagesInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of// the input PDF file.PageRanges firstPageRange = GetFirstPageRangeForRotation();// Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of// the input PDF file.PageRanges secondPageRange = GetSecondPageRangeForRotation();// Create parameters for the jobRotatePagesParams rotatePagesParams = RotatePagesParams.RotatePagesParamsBuilder().withAngleToRotatePagesBy(Angle._90, firstPageRange).withAngleToRotatePagesBy(Angle._180, secondPageRange).Build();// Creates a new job instanceRotatePagesJob rotatePagesJob = new RotatePagesJob(asset, rotatePagesParams);// Submits the job and gets the job resultString location = pdfServices.Submit(rotatePagesJob);PDFServicesResponse<RotatePagesResult> pdfServicesResponse =pdfServices.GetJobResult<RotatePagesResult>(location, typeof(RotatePagesResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/rotatePagesOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}private static PageRanges GetFirstPageRangeForRotation(){// Specify pages for rotation.PageRanges firstPageRange = new PageRanges();// Add page 1.firstPageRange.AddSinglePage(1);// Add pages 3 to 4.firstPageRange.AddRange(3, 4);return firstPageRange;}private static PageRanges GetSecondPageRangeForRotation(){// Specify pages for rotation.PageRanges secondPageRange = new PageRanges();// Add page 2.secondPageRange.AddSinglePage(2);return secondPageRange;}// Generates a string containing a directory structure and file name for the output file.private static String CreateOutputFilePath(){String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");return ("/output/rotate" + timeStamp + ".pdf");}}}
Copied to your clipboard// 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.rotatepages.RotatePDFPagespublic class RotatePDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(RotatePDFPages.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/rotatePagesInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// First set of page ranges for rotating the specified pages of the input PDF file.PageRanges firstPageRange = getFirstPageRangeForRotation();// Second set of page ranges for rotating the specified pages of the input PDF file.PageRanges secondPageRange = getSecondPageRangeForRotation();// Create parameters for the jobRotatePagesParams rotatePagesParams = RotatePagesParams.rotatePagesParamsBuilder().withAngleToRotatePagesBy(Angle._90, firstPageRange).withAngleToRotatePagesBy(Angle._180, secondPageRange).build();// Creates a new job instanceRotatePagesJob rotatePagesJob = new RotatePagesJob(asset, rotatePagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(rotatePagesJob);PDFServicesResponse<RotatePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, RotatePagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/rotatePagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/rotatePagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getFirstPageRangeForRotation() {// Specify pages for rotationPageRanges firstPageRange = new PageRanges();// Add page 1firstPageRange.addSinglePage(1);// Add pages 3 to 4firstPageRange.addRange(3, 4);return firstPageRange;}private static PageRanges getSecondPageRangeForRotation() {// Specify pages for rotation.PageRanges secondPageRange = new PageRanges();// Add page 2.secondPageRange.addSinglePage(2);return secondPageRange;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/rotatepages/rotate_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class RotatePDFPages:def __init__(self):try:file = open("rotatePagesInput.pdf", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.PDF)# First set of page ranges for rotating the specified pages of the input PDF file.first_page_range: PageRanges = self.get_first_page_range_for_rotation()# Second set of page ranges for rotating the specified pages of the input PDF file.second_page_range: PageRanges = self.get_second_page_range_for_rotation()# Create parameters for the jobrotate_pages_params = RotatePagesParams()rotate_pages_params.add_angle_to_rotate_for_page_ranges(angle=Angle.ANGLE_90, page_ranges=first_page_range)rotate_pages_params.add_angle_to_rotate_for_page_ranges(angle=Angle.ANGLE_180, page_ranges=second_page_range)# Creates a new job instancereorder_pages_job = RotatePagesJob(input_asset=input_asset, rotate_pages_params=rotate_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(reorder_pages_job)pdf_services_response = pdf_services.get_job_result(location, RotatePagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "rotatePagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_first_page_range_for_rotation() -> PageRanges:# Specify pages for rotationfirst_page_range = PageRanges()# Add page 1first_page_range.add_single_page(1)# Add pages 3 to 4first_page_range.add_range(3, 4)return first_page_range@staticmethoddef get_second_page_range_for_rotation() -> PageRanges:# Specify pages for rotationsecond_page_range = PageRanges()# Add page 2second_page_range.add_single_page(2)return second_page_rangeif __name__ == "__main__":RotatePDFPages()
Adobe PDF Extract API
A new web service that allows you to unlock content structure and table data from any PDF document with machine learning.
Leverage Adobe Sensei for a rich understanding of content structure with higher quality input to other systems.
Easily Extract content to JSON format for further processing into other applications or databases.
Identify more document elements than OCR with extraction of headings, paragraphs, lists, and more.
Use cases for PDF Services API
Report creation and editing
Create and embed reports for internal or external consumption, sharing, and review.
Search and Indexing
Create searchable indexes from digital documents to quickly locate critical content for compliance and other downstream processing.
Digital content publishing
Publish whitepapers and marketing content with end-user interactivity, security controls, and analytics.
Job posting
Automate job posting with supporting documents such as PDF brochures, relevant job supplements, and company details.