The samples and documentation here should get you quickly up and running with the PDF Tools SDK. These code examples illustrate how to perform PDF actions using the SDK, including:
Creating a PDF from multiple formats, including HTML, Microsoft Office documents, and text files
Exporting a PDF to other formats or an image
Combining entire PDFs or specified page ranges
Using OCR to make a PDF file searchable with a custom locale
Compress and Linearize PDFs
Protect PDFs with password(s) and Remove password protection from PDFs
Common page operations, including inserting, replacing, deleting, reordering, and rotating
Splitting PDFs into multiple files
The SDK supports providing the authentication credentials at runtime. Doing so allows fetching the credentials from a secret server during runtime instead of storing them in a file. Please refer the following samples for details.
The APIs use inferred timeout properties and provide defaults. However, the SDK supports custom timeouts for the API calls. You can tailor the timeout settings for your environment and network speed. In addition to the details below, you can refer to working code samples:
Available properties:
connectTimeout: Default: 2000. The maximum allowed time in milliseconds for creating an initial HTTPS connection.
socketTimeout: Default: 10000. The maximum allowed time in milliseconds between two successive HTTP response packets.
Override the timeout properties via a custom ClientConfig
class:
ClientConfig clientConfig = ClientConfig.builder()
.withConnectTimeout(3000)
.withSocketTimeout(20000)
.build();
Available properties:
timeout: Default: 400000. The maximum allowed time in milliseconds for establishing a connection, sending a request, and getting a response.
readWriteTimeout: Default: 10000. The maximum allowed time in milliseconds to read or write data after connection is established.
Override the timeout properties via a custom ClientConfig
class:
ClientConfig clientConfig = ClientConfig.ConfigBuilder()
.timeout(500000)
.readWriteTimeout(15000)
.Build();
Available properties:
connectTimeout: Default: 10000. The maximum allowed time in milliseconds for creating an initial HTTPS connection.
readTimeout: Default: 10000. The maximum allowed time in milliseconds between two successive HTTP response packets.
Override the timeout properties via a custom ClientConfig
class:
const clientConfig = PDFToolsSdk.ClientConfig
.clientConfigBuilder()
.withConnectTimeout(15000)
.withReadTimeout(15000)
.build();
Use the sample below to create PDFs from Microsoft Office documents (Word, Excel and PowerPoint) and other supported file formats. While the example shows .docx file conversion, the SDK supports the following formats:
Microsoft Word (DOC, DOCX)
Microsoft PowerPoint (PPT, PPTX)
Microsoft Excel (XLS, XLSX)
Text (TXT, RTF)
Image (BMP, JPEG, GIF, TIFF, PNG)
//Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CreatePDFFromDOCX { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDOCX.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CreatePDFOperation createPdfOperation = CreatePDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/createPDFInput.docx"); createPdfOperation.setInput(source); // Execute the operation. FileRef result = createPdfOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/createPDFFromDOCX.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CreatePDFFromDocx { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CreatePDFOperation createPdfOperation = CreatePDFOperation.CreateNew(); // Set operation input from a source file. FileRef source = FileRef.CreateFromLocalFile(@"createPdfInput.docx"); createPdfOperation.SetInput(source); // Execute the operation. FileRef result = createPdfOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/createPdfOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), createPdfOperation = PDFToolsSdk.CreatePDF.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/createPDFInput.docx'); createPdfOperation.setInput(input); // Execute the operation and Save the result to the specified location. createPdfOperation.execute(executionContext) .then(result => result.saveAsFile('output/createPDFFromDOCX.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The sample below creates a PDF file from a static HTML file. The file must be local. Since HTML/web pages typically contain external assets, the input file must be a zip file containing an index.html at the top level of the archive as well as any dependencies such as images, css files, and so on.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CreatePDFFromStaticHTML { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromStaticHTML.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CreatePDFOperation htmlToPDFOperation = CreatePDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/createPDFFromStaticHtmlInput.zip"); htmlToPDFOperation.setInput(source); // Provide any custom configuration options for the operation. setCustomOptions(htmlToPDFOperation); // Execute the operation. FileRef result = htmlToPDFOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/createPDFFromStaticHtmlOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } private static void setCustomOptions(CreatePDFOperation htmlToPDFOperation) { // 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. CreatePDFOptions htmlToPdfOptions = CreatePDFOptions.htmlOptionsBuilder() .includeHeaderFooter(true) .withPageLayout(pageLayout) .build(); htmlToPDFOperation.setOptions(htmlToPdfOptions); } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CreatePDFFromStaticHtml { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CreatePDFOperation htmlToPDFOperation = CreatePDFOperation.CreateNew(); // Set operation input from a source file. FileRef source = FileRef.CreateFromLocalFile(@"createPDFFromStaticHtmlInput.zip"); htmlToPDFOperation.SetInput(source); // Provide any custom configuration options for the operation. SetCustomOptions(htmlToPDFOperation); // Execute the operation. FileRef result = htmlToPDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/createPdfFromStaticHtmlOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } private static void SetCustomOptions(CreatePDFOperation htmlToPDFOperation) { // 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. CreatePDFOptions htmlToPdfOptions = CreatePDFOptions.HtmlOptionsBuilder() .IncludeHeaderFooter(true) .WithPageLayout(pageLayout) . Build(); htmlToPDFOperation.SetOptions(htmlToPdfOptions); } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const setCustomOptions = (htmlToPDFOperation) => { // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation). const pageLayout = new PDFToolsSdk.CreatePDF.options.PageLayout(); pageLayout.setPageSize(8, 11.5); // Set the desired HTML-to-PDF conversion options. const htmlToPdfOptions = new PDFToolsSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder() .includesHeaderFooter(true) .withPageLayout(pageLayout) .build(); htmlToPDFOperation.setOptions(htmlToPdfOptions); }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), htmlToPDFOperation = PDFToolsSdk.CreatePDF.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/createPDFFromStaticHtmlInput.zip'); htmlToPDFOperation.setInput(input); // Provide any custom configuration options for the operation. setCustomOptions(htmlToPDFOperation); // Execute the operation and Save the result to the specified location. htmlToPDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/createPdfFromStaticHtmlOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
To support workflows with dynamic data, CreatePDFFromDynamicHTML
creates PDFs from dynamic HTML. It’s a common scenario for enterprise to provide end users with an HTML template with form fields. This API allows you to capture the users unique data entries and then save it as PDF. Collected data is stored in a JSON file, and the source HTML file must include <script src='./json.js' type='text/javascript'></script>
. Refer to the API docs for usage.
The sample CreatePDFFromDynamicHTML
converts a zip file, containing the input HTML file and its resources, along with the input data to a PDF file. The input data is used by the JavaScript in the HTML file to manipulate the HTML DOM, thus effectively updating the source HTML file. This mechanism can be used to provide data to the template HTML dynamically prior to PDF conversion.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CreatePDFFromDynamicHTML { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDynamicHTML.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CreatePDFOperation htmlToPDFOperation = CreatePDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/createPDFFromDynamicHtmlInput.zip"); htmlToPDFOperation.setInput(source); // Provide any custom configuration options for the operation. setCustomOptions(htmlToPDFOperation); // Execute the operation. FileRef result = htmlToPDFOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/createPDFFromDynamicHtmlOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } private static void setCustomOptions(CreatePDFOperation htmlToPDFOperation) { // 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 dataToMerge field that needs to be populated in the HTML before its conversion JSONObject dataToMerge = new JSONObject(); dataToMerge.put("title","Create, Convert PDFs and More!"); dataToMerge.put("sub_title","Easily integrate PDF actions within your document workflows."); // Set the desired HTML-to-PDF conversion options. CreatePDFOptions htmlToPdfOptions = CreatePDFOptions.htmlOptionsBuilder() .includeHeaderFooter(true) .withPageLayout(pageLayout) .withDataToMerge(dataToMerge) .build(); htmlToPDFOperation.setOptions(htmlToPdfOptions); } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CreatePDFFromDynamicHtml { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CreatePDFOperation htmlToPDFOperation = CreatePDFOperation.CreateNew(); // Set operation input from a source file. FileRef source = FileRef.CreateFromLocalFile(@"createPDFFromDynamicHtmlInput.zip"); htmlToPDFOperation.SetInput(source); // Provide any custom configuration options for the operation. SetCustomOptions(htmlToPDFOperation); // Execute the operation. FileRef result = htmlToPDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/createPdfFromDynamicHtmlOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // errors continued. . . } private static void SetCustomOptions(CreatePDFOperation htmlToPDFOperation) { // 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 dataToMerge field that needs to be populated in the HTML before its conversion JObject dataToMerge = new JObject { { "title", "Create, Convert PDFs and More!" }, { "sub_title", "Easily integrate PDF actions within your document workflows." } }; // Set the desired HTML-to-PDF conversion options. CreatePDFOptions htmlToPdfOptions = CreatePDFOptions.HtmlOptionsBuilder() .IncludeHeaderFooter(true) .WithPageLayout(pageLayout) .WithDataToMerge(dataToMerge) .Build(); htmlToPDFOperation.SetOptions(htmlToPdfOptions); } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const setCustomOptions = (htmlToPDFOperation) => { // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation). const pageLayout = new PDFToolsSdk.CreatePDF.options.PageLayout(); pageLayout.setPageSize(8, 11.5); //Set the dataToMerge field that needs to be populated in the HTML before its conversion. const dataToMerge = { "title":"Create, Convert PDFs and More!", "sub_title": "Easily integrate PDF actions within your document workflows." }; // Set the desired HTML-to-PDF conversion options. const htmlToPdfOptions = new PDFToolsSdk.CreatePDF.options.html.CreatePDFFromHtmlOptions.Builder() .includesHeaderFooter(true) .withPageLayout(pageLayout) .withDataToMerge(dataToMerge) .build(); htmlToPDFOperation.setOptions(htmlToPdfOptions); }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), htmlToPDFOperation = PDFToolsSdk.CreatePDF.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/createPDFFromDynamicHtmlInput.zip'); htmlToPDFOperation.setInput(input); // Provide any custom configuration options for the operation. setCustomOptions(htmlToPDFOperation); // Execute the operation and Save the result to the specified location. htmlToPDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/createPdfFromDynamicHtmlOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The sample below converts a PDF file into a number of supported formats such as:
Microsoft Office file formats
Text files
Images
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class ExportPDFToDOCX { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ExportPDFToDOCX.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); ExportPDFOperation exportPdfOperation = ExportPDFOperation.createNew(ExportPDFTargetFormat.DOCX); // Set operation input from a local PDF file FileRef sourceFileRef = FileRef.createFromLocalFile("src/main/resources/exportPDFInput.pdf"); exportPdfOperation.setInput(sourceFileRef); // Execute the operation. FileRef result = exportPdfOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/exportPdfOutput.docx"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ExportPDFToDocx { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); ExportPDFOperation exportPdfOperation = ExportPDFOperation.CreateNew(ExportPDFTargetFormat.DOCX); // Set operation input from a local PDF file FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"exportPdfInput.pdf"); exportPdfOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = exportPdfOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/exportPdfOutput.docx"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), exportPDF = PDFToolsSdk.ExportPDF, exportPdfOperation = exportPDF.Operation.createNew(exportPDF.SupportedTargetFormats.DOCX); // Set operation input from a source file const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/exportPDFInput.pdf'); exportPdfOperation.setInput(input); // Execute the operation and Save the result to the specified location. exportPdfOperation.execute(executionContext) .then(result => result.saveAsFile('output/exportPdfOutput.docx')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The sample below converts a PDF file to one or more jpeg or png images. Exporting to an image produces a zip archive containing one image per page. Each image file name ends with “_<unpadded_page_index_number>”. For example, a PDF file with 15 pages will generate 15 image files. The first file’s name ends with “_1” and the last file’s name ends with “_15”.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples package com.adobe.platform.operation.samples.exportpdf; public class ExportPDFToJPEG { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ExportPDFToJPEG.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); ExportPDFOperation exportPdfOperation = ExportPDFOperation.createNew(ExportPDFTargetFormat.JPEG); // Set operation input from a source file. FileRef sourceFileRef = FileRef.createFromLocalFile("src/main/resources/exportPDFToImageInput.pdf"); exportPdfOperation.setInput(sourceFileRef); // Execute the operation. FileRef result = exportPdfOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/exportPDFToJPEG.zip"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ExportPDFToImage { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); ExportPDFOperation exportPdfOperation = ExportPDFOperation.CreateNew(ExportPDFTargetFormat.JPEG); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"exportPdfToImageInput.pdf"); exportPdfOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = exportPdfOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/exportPdfToImageOutput.zip"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), exportPDF = PDFToolsSdk.ExportPDF, exportPdfOperation = exportPDF.Operation.createNew(exportPDF.SupportedTargetFormats.JPEG); // Set operation input from a source file const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/exportPDFToImageInput.pdf'); exportPdfOperation.setInput(input); // Execute the operation and Save the result to the specified location. exportPdfOperation.execute(executionContext) .then(result => result.saveAsFile('output/exportPDFToJPEG.zip')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
This sample combines up to 20 PDF files into a single PDF file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CombinePDF { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDF.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CombineFilesOperation combineFilesOperation = CombineFilesOperation.createNew(); // Add operation input from source files. FileRef combineSource1 = FileRef.createFromLocalFile("src/main/resources/combineFilesInput1.pdf"); FileRef combineSource2 = FileRef.createFromLocalFile("src/main/resources/combineFilesInput2.pdf"); combineFilesOperation.addInput(combineSource1); combineFilesOperation.addInput(combineSource2); // Execute the operation. FileRef result = combineFilesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/combineFilesOutput.pdf"); } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CombinePDF { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CombineFilesOperation combineFilesOperation = CombineFilesOperation.CreateNew(); // Add operation input from source files. FileRef combineSource1 = FileRef.CreateFromLocalFile(@"combineFilesInput1.pdf"); FileRef combineSource2 = FileRef.CreateFromLocalFile(@"combineFilesInput2.pdf"); combineFilesOperation.AddInput(combineSource1); combineFilesOperation.AddInput(combineSource2); // Execute the operation. FileRef result = combineFilesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/combineFilesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), combineFilesOperation = PDFToolsSdk.CombineFiles.Operation.createNew(); // Set operation input from a source file. const combineSource1 = PDFToolsSdk.FileRef.createFromLocalFile('resources/combineFilesInput1.pdf'), combineSource2 = PDFToolsSdk.FileRef.createFromLocalFile('resources/combineFilesInput2.pdf'); combineFilesOperation.addInput(combineSource1); combineFilesOperation.addInput(combineSource2); // Execute the operation and Save the result to the specified location. combineFilesOperation.execute(executionContext) .then(result => result.saveAsFile('output/combineFilesOutput.pdf')) .catch(err => { if (err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
This combine sample combines specific pages from up to 20 different PDF files into a single PDF file. Optional arguments allow specifying page ranges for each file to combine in the output file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CombinePDFWithPageRanges { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDFWithPageRanges.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CombineFilesOperation combineFilesOperation = CombineFilesOperation.createNew(); // Create a FileRef instance from a local file. FileRef firstFileToCombine = FileRef.createFromLocalFile("src/main/resources/combineFileWithPageRangeInput1.pdf"); PageRanges pageRangesForFirstFile = getPageRangeForFirstFile(); // Add the first file as input to the operation, along with its page range. combineFilesOperation.addInput(firstFileToCombine, pageRangesForFirstFile); // Create a second FileRef instance using a local file. FileRef secondFileToCombine = FileRef.createFromLocalFile("src/main/resources/combineFileWithPageRangeInput2.pdf"); PageRanges pageRangesForSecondFile = getPageRangeForSecondFile(); // Add the second file as input to the operation, along with its page range. combineFilesOperation.addInput(secondFileToCombine, pageRangesForSecondFile); // Execute the operation. FileRef result = combineFilesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/combineFilesWithPageOptionsOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } private static PageRanges getPageRangeForSecondFile() { // Specify which pages of the second file are to be included in the combined file. PageRanges pageRangesForSecondFile = new PageRanges(); // Add all pages including and after page 3. pageRangesForSecondFile.addAllFrom(3); return pageRangesForSecondFile; } private static PageRanges getPageRangeForFirstFile() { // Specify which pages of the first file are to be included in the combined file. PageRanges pageRangesForFirstFile = new PageRanges(); // Add page 1. pageRangesForFirstFile.addSinglePage(1); // Add page 2. pageRangesForFirstFile.addSinglePage(2); // Add pages 3 to 4. pageRangesForFirstFile.addRange(3, 4); return pageRangesForFirstFile; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CombinePDFWithPageRanges { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CombineFilesOperation combineFilesOperation = CombineFilesOperation.CreateNew(); // Create a FileRef instance from a local file. FileRef firstFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput1.pdf"); PageRanges pageRangesForFirstFile = GetPageRangeForFirstFile(); // Add the first file as input to the operation, along with its page range. combineFilesOperation.AddInput(firstFileToCombine, pageRangesForFirstFile); // Create a second FileRef instance using a local file. FileRef secondFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput2.pdf"); PageRanges pageRangesForSecondFile = GetPageRangeForSecondFile(); // Add the second file as input to the operation, along with its page range. combineFilesOperation.AddInput(secondFileToCombine, pageRangesForSecondFile); // Execute the operation. FileRef result = combineFilesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/combineFilesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } private static PageRanges GetPageRangeForSecondFile() { // Specify which pages of the second file are to be included in the combined file. PageRanges pageRangesForSecondFile = new PageRanges(); // Add all pages including and after page 5. pageRangesForSecondFile.AddAllFrom(5); return pageRangesForSecondFile; } private static PageRanges GetPageRangeForFirstFile() { // Specify which pages of the first file are to be included in the combined file. PageRanges pageRangesForFirstFile = new PageRanges(); // Add page 2. pageRangesForFirstFile.AddSinglePage(2); // Add page 3. pageRangesForFirstFile.AddSinglePage(3); // Add pages 5 to 7. pageRangesForFirstFile.AddRange(5, 7); return pageRangesForFirstFile; } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRangesForFirstFile = () => { // Specify which pages of the first file are to be included in the combined file. const pageRangesForFirstFile = new PDFToolsSdk.PageRanges(); // Add page 1. pageRangesForFirstFile.addSinglePage(1); // Add page 2. pageRangesForFirstFile.addSinglePage(2); // Add pages 3 to 4. pageRangesForFirstFile.addPageRange(3, 4); return pageRangesForFirstFile; }; const getPageRangesForSecondFile = () => { // Specify which pages of the second file are to be included in the combined file. const pageRangesForSecondFile = new PDFToolsSdk.PageRanges(); // Add all pages including and after page 3. pageRangesForSecondFile.addAllFrom(3); return pageRangesForSecondFile; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), combineFilesOperation = PDFToolsSdk.CombineFiles.Operation.createNew(); // Create a FileRef instance from a local file. const combineSource1 = PDFToolsSdk.FileRef.createFromLocalFile('resources/combineFilesInput1.pdf'), pageRangesForFirstFile = getPageRangesForFirstFile(); // Add the first file as input to the operation, along with its page range. combineFilesOperation.addInput(combineSource1, pageRangesForFirstFile); // Create a second FileRef instance using a local file. const combineSource2 = PDFToolsSdk.FileRef.createFromLocalFile('resources/combineFilesInput2.pdf'), pageRangesForSecondFile = getPageRangesForSecondFile(); // Add the second file as input to the operation, along with its page range. combineFilesOperation.addInput(combineSource2, pageRangesForSecondFile); // Execute the operation and Save the result to the specified location. combineFilesOperation.execute(executionContext) .then(result => result.saveAsFile('output/combineFilesWithPageRangesOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
Optical character recognition (OCR) converts images to text so that you and your users can fully interact with the PDF file. After performing OCR, the PDF may be fully editable and searchable. The input format must be application/pdf
.
This sample defaults to the en-us locale. For other languages, see OCR with explicit language.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class OcrPDF { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDF.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); OCROperation ocrOperation = OCROperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/ocrInput.pdf"); ocrOperation.setInput(source); // Execute the operation FileRef result = ocrOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/ocrOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace OcrPDF { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); OCROperation ocrOperation = OCROperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"ocrInput.pdf"); ocrOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = ocrOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/ocrOperationOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here. . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), ocrOperation = PDFToolsSdk.OCR.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf'); ocrOperation.setInput(input); // Execute the operation and Save the result to the specified location. ocrOperation.execute(executionContext) .then(result => result.saveAsFile('output/ocrOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
You can perform OCR on files in other languages, including German, French, Danish, and other languages. Refer to OCRSupportedLocale
and OCRSupportedType
in the API docs for a list of supported OCR locales and OCR types.
As shown in the OcrPDFWithOptions sample, when you make a PDF file searchable, you specify both the locale (language) and the type. There are two types which produce a different result:
One type ensures that text is searchable and selectable, but modifies the original image during the cleanup process (for example, deskews it) before placing an invisible text layer over it. This type removes unwanted artifacts and may result in a more readable document in some scenarios.
The second (EXACT) type, also overlays a searchable text layer over the original image, but in this case, the original image is unchanged. This type produces maximum fidelity to the original image.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class OcrPDFWithOptions { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDFWithOptions.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); OCROperation ocrOperation = OCROperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/ocrInput.pdf"); ocrOperation.setInput(source); // Build OCR options from supported locales and OCR-types and set them into the operation OCROptions ocrOptions = OCROptions.ocrOptionsBuilder() .withOCRLocale(OCRSupportedLocale.EN_US) .withOCRType(OCRSupportedType.SEARCHABLE_IMAGE_EXACT) .build(); ocrOperation.setOptions(ocrOptions); // Execute the operation FileRef result = ocrOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/ocrWithOptionsOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace OcrPDFWithOptions { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); OCROperation ocrOperation = OCROperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"ocrWithOptionsInput.pdf"); ocrOperation.SetInput(sourceFileRef); // Build OCR options from supported locales and OCR-types and set them into the operation OCROptions ocrOptions = OCROptions.OCROptionsBuilder() .WithOcrLocale(OCRSupportedLocale.EN_US) .WithOcrType(OCRSupportedType.SEARCHABLE_IMAGE_EXACT) .Build(); ocrOperation.SetOptions(ocrOptions); // Execute the operation. FileRef result = ocrOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/ocrOperationWithOptionsOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); //Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), ocrOperation = PDFToolsSdk.OCR.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf'); ocrOperation.setInput(input); // Provide any custom configuration options for the operation. const options = new PDFToolsSdk.OCR.options.OCROptions.Builder() .withOcrType(PDFToolsSdk.OCR.options.OCRSupportedType.SEARCHABLE_IMAGE_EXACT) .withOcrLang(PDFToolsSdk.OCR.options.OCRSupportedLocale.EN_US) .build(); ocrOperation.setOptions(options); // Execute the operation and Save the result to the specified location. ocrOperation.execute(executionContext) .then(result => result.saveAsFile('output/ocrWithOptionsOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
Compress PDFs to reduce the file size prior to performing workflow operations that use bandwidth or memory.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class CompressPDF { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDF.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); CompressPDFOperation compressPDFOperation = CompressPDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/compressPDFInput.pdf"); compressPDFOperation.setInput(source); // Execute the operation FileRef result = compressPDFOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/compressPDFOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace CompressPDF { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"compressPDFInput.pdf"); compressPDFOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = compressPDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/compressPDFOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), compressPDF = PDFToolsSdk.CompressPDF, compressPDFOperation = compressPDF.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/compressPDFInput.pdf'); compressPDFOperation.setInput(input); // Execute the operation and Save the result to the specified location. compressPDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/compressPDFOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
Linearizing a PDF creates a web-optimized PDF file which supports incremental access in network environments.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class LinearizePDF { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(LinearizePDF.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); LinearizePDFOperation linearizePDFOperation = LinearizePDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/linearizePDFInput.pdf"); linearizePDFOperation.setInput(source); // Execute the operation FileRef result = linearizePDFOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/linearizePDFOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace LinearizePDF { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); LinearizePDFOperation linearizePDFOperation = LinearizePDFOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"linearizePDFInput.pdf"); linearizePDFOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = linearizePDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/linearizePDFOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), linearizePDF = PDFToolsSdk.LinearizePDF, linearizePDFOperation = linearizePDF.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/linearizePDFInput.pdf'); linearizePDFOperation.setInput(input); // Execute the operation and Save the result to the specified location. linearizePDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/linearizePDFOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
You can password protect PDFs so that only users with a document open password can open the file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class ProtectPDF { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ProtectPDF.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.create(credentials); // Build ProtectPDF options by setting a User Password and Encryption // Algorithm (used for encrypting the PDF file). ProtectPDFOptions protectPDFOptions = ProtectPDFOptions.passwordProtectOptionsBuilder() .setUserPassword("encryptPassword") .setEncryptionAlgorithm(EncryptionAlgorithm.AES_256) .build(); // Create a new operation instance. ProtectPDFOperation protectPDFOperation = ProtectPDFOperation.createNew(protectPDFOptions); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/protectPDFInput.pdf"); protectPDFOperation.setInput(source); // Execute the operation FileRef result = protectPDFOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/protectPDFOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ProtectPDF { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Build ProtectPDF options by setting a User Password and Encryption // Algorithm (used for encrypting the PDF file). ProtectPDFOptions protectPDFOptions = ProtectPDFOptions.PasswordProtectOptionsBuilder() .SetUserPassword("encryptPassword") .SetEncryptionAlgorithm(EncryptionAlgorithm.AES_256) .Build(); // Create a new operation instance ProtectPDFOperation protectPDFOperation = ProtectPDFOperation.CreateNew(protectPDFOptions); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"protectPDFInput.pdf"); protectPDFOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = protectPDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/protectPDFOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Build ProtectPDF options by setting a User Password and Encryption // Algorithm (used for encrypting the PDF file). const protectPDF = PDFToolsSdk.ProtectPDF, options = new protectPDF.options.PasswordProtectOptions.Builder() .setUserPassword("encryptPassword") .setEncryptionAlgorithm(PDFToolsSdk.ProtectPDF.options.EncryptionAlgorithm.AES_256) .build(); // Create a new operation instance. const protectPDFOperation = protectPDF.Operation.createNew(options); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/protectPDFInput.pdf'); protectPDFOperation.setInput(input); // Execute the operation and Save the result to the specified location. protectPDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/protectPDFOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
You can secure a PDF file with owner/permissions password and set the restriction on certain features like printing, editing and copying in the PDF document. Refer to ContentEncryption
and Permission
in the API docs for a list of supported types of content to encrypt and types of document permissions.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class ProtectPDFWithOwnerPassword { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ProtectPDFWithOwnerPassword.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.create(credentials); // Create new permissions instance and add the required permissions Permissions permissions = Permissions.createNew(); permissions.addPermission(Permission.PRINT_LOW_QUALITY); permissions.addPermission(Permission.EDIT_DOCUMENT_ASSEMBLY); permissions.addPermission(Permission.COPY_CONTENT); // Build ProtectPDF options by setting an Owner/Permissions Password, Permissions, // Encryption Algorithm (used for encrypting the PDF file) and specifying the type of content to encrypt. ProtectPDFOptions protectPDFOptions = ProtectPDFOptions.passwordProtectOptionsBuilder() .setOwnerPassword("password") .setPermissions(permissions) .setEncryptionAlgorithm(EncryptionAlgorithm.AES_256) .setContentEncryption(ContentEncryption.ALL_CONTENT_EXCEPT_METADATA) .build(); // Create a new operation instance. ProtectPDFOperation protectPDFOperation = ProtectPDFOperation.createNew(protectPDFOptions); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/protectPDFInput.pdf"); protectPDFOperation.setInput(source); // Execute the operation FileRef result = protectPDFOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/protectPDFWithOwnerPasswordOutput.pdf"); } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) { LOGGER.error("Exception encountered while executing operation", ex); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ProtectPDFWithOwnerPassword { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create new permissions instance and add the required permissions Permissions permissions = Permissions.CreateNew(); permissions.AddPermission(Permission.PRINT_LOW_QUALITY); permissions.AddPermission(Permission.EDIT_DOCUMENT_ASSEMBLY); permissions.AddPermission(Permission.COPY_CONTENT); // Build ProtectPDF options by setting an Owner/Permissions Password, Permissions, // Encryption Algorithm (used for encrypting the PDF file) and specifying the type of content to encrypt. ProtectPDFOptions protectPDFOptions = ProtectPDFOptions.PasswordProtectOptionsBuilder() .SetOwnerPassword("password") .SetPermissions(permissions) .SetEncryptionAlgorithm(EncryptionAlgorithm.AES_256) .SetContentEncryption(ContentEncryption.ALL_CONTENT_EXCEPT_METADATA) .Build(); // Create a new operation instance ProtectPDFOperation protectPDFOperation = ProtectPDFOperation.CreateNew(protectPDFOptions); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"protectPDFInput.pdf"); protectPDFOperation.SetInput(sourceFileRef); // Execute the operation. FileRef result = protectPDFOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/protectPDFWithOwnerPasswordOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Create new permissions instance and add the required permissions const protectPDF = PDFToolsSdk.ProtectPDF, protectPDFOptions = protectPDF.options, permissions = protectPDFOptions.Permissions.createNew(); permissions.addPermission(protectPDFOptions.Permission.PRINT_LOW_QUALITY); permissions.addPermission(protectPDFOptions.Permission.EDIT_DOCUMENT_ASSEMBLY); permissions.addPermission(protectPDFOptions.Permission.COPY_CONTENT); // Build ProtectPDF options by setting an Owner/Permissions Password, Permissions, // Encryption Algorithm (used for encrypting the PDF file) and specifying the type of content to encrypt. const options = new protectPDFOptions.PasswordProtectOptions.Builder() .setOwnerPassword("password") .setPermissions(permissions) .setEncryptionAlgorithm(protectPDFOptions.EncryptionAlgorithm.AES_256) .setContentEncryption(protectPDFOptions.ContentEncryption.ALL_CONTENT_EXCEPT_METADATA) .build(); // Create a new operation instance. const protectPDFOperation = protectPDF.Operation.createNew(options); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/protectPDFInput.pdf'); protectPDFOperation.setInput(input); // Execute the operation and Save the result to the specified location. protectPDFOperation.execute(executionContext) .then(result => result.saveAsFile('output/protectPDFWithOwnerPasswordOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
Use the below sample to remove security from a PDF document.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class RemoveProtection { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(RemoveProtection.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); RemoveProtectionOperation removeProtectionOperation = RemoveProtectionOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/removeProtectionInput.pdf"); removeProtectionOperation.setInput(source); // Set the password for removing security from a PDF document. removeProtectionOperation.setPassword("password"); // Execute the operation. FileRef result = removeProtectionOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/removeProtectionOutput.pdf"); } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace RemoveProtection { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance RemoveProtectionOperation removeProtectionOperation = RemoveProtectionOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"removeProtectionInput.pdf"); removeProtectionOperation.SetInput(sourceFileRef); // Set the password for removing security from a PDF document. removeProtectionOperation.SetPassword("password"); // Execute the operation. FileRef result = removeProtectionOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/removeProtectionOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Create a new operation instance. const removeProtectionOperation = PDFToolsSdk.RemoveProtection.Operation.createNew(), input = PDFToolsSdk.FileRef.createFromLocalFile( 'resources/removeProtectionInput.pdf', PDFToolsSdk.RemoveProtection.SupportedSourceFormat.pdf ); // Set operation input from a source file. removeProtectionOperation.setInput(input); // Set the password for removing security from a PDF document. removeProtectionOperation.setPassword("password"); // Execute the operation and Save the result to the specified location. removeProtectionOperation.execute(executionContext) .then(result => result.saveAsFile('output/removeProtectionOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The insert operation inserts additional pages from different PDFs into an existing PDF.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class InsertPDFPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); InsertPagesOperation insertPagesOperation = InsertPagesOperation.createNew(); // Set operation base input from a source file. FileRef baseSourceFile = FileRef.createFromLocalFile("src/main/resources/baseInput.pdf"); insertPagesOperation.setBaseInput(baseSourceFile); // Create a FileRef instance using a local file. FileRef firstFileToInsert = FileRef.createFromLocalFile("src/main/resources/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("src/main/resources/secondFileToInsertInput.pdf"); // Adds all the pages of the input PDF file to be inserted at the specified page of the // base PDF file. insertPagesOperation.addPagesToInsertAt(secondFileToInsert, 3); // Execute the operation. FileRef result = insertPagesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/insertPagesOutput.pdf"); } 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 file. PageRanges pageRanges = new PageRanges(); // Add pages 1 to 3. pageRanges.addRange(1, 3); // Add page 4. pageRanges.addSinglePage(4); return pageRanges; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace InsertPDFPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { // Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance InsertPagesOperation 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")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRangesForFirstFile = () => { // Specify which pages of the first file are to be inserted in the base file. const pageRangesForFirstFile = new PDFToolsSdk.PageRanges(); // Add pages 1 to 3. pageRangesForFirstFile.addPageRange(1, 3); // Add page 4. pageRangesForFirstFile.addSinglePage(4); return pageRangesForFirstFile; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), insertPagesOperation = PDFToolsSdk.InsertPages.Operation.createNew(); // Set operation base input from a source file. const baseInputFile = PDFToolsSdk.FileRef.createFromLocalFile('resources/baseInput.pdf'); insertPagesOperation.setBaseInput(baseInputFile); // Create a FileRef instance using a local file. const firstFileToInsert = PDFToolsSdk.FileRef.createFromLocalFile('resources/firstFileToInsertInput.pdf'), pageRanges = getPageRangesForFirstFile(); // Adds the pages (specified by the page ranges) of the input PDF file to be inserted at // the specified page of the base PDF file. insertPagesOperation.addPagesToInsertAt(2, firstFileToInsert, pageRanges); // Create a FileRef instance using a local file. const secondFileToInsert = PDFToolsSdk.FileRef.createFromLocalFile('resources/secondFileToInsertInput.pdf'); // Adds all the pages of the input PDF file to be inserted at the specified page of the // base PDF file. insertPagesOperation.addPagesToInsertAt(3, secondFileToInsert); // Execute the operation and Save the result to the specified location. insertPagesOperation.execute(executionContext) .then(result => result.saveAsFile('output/insertPagesOutput.pdf')) .catch(err => { if (err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The replace pages operation replaces pages in a PDF with pages from other PDF files.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class ReplacePDFPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ReplacePDFPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); ReplacePagesOperation replacePagesOperation = ReplacePagesOperation.createNew(); // Set operation base input from a source file. FileRef baseSourceFile = FileRef.createFromLocalFile("src/main/resources/baseInput.pdf"); replacePagesOperation.setBaseInput(baseSourceFile); // Create a FileRef instance using a local file. FileRef firstInputFile = FileRef.createFromLocalFile("src/main/resources/replacePagesInput1.pdf"); PageRanges pageRanges = getPageRangeForFirstFile(); // Adds the pages (specified by the page ranges) of the input PDF file for replacing the // page of the base PDF file. replacePagesOperation.addPagesForReplace(firstInputFile, pageRanges, 1); // Create a FileRef instance using a local file. FileRef secondInputFile = FileRef.createFromLocalFile("src/main/resources/replacePagesInput2.pdf"); // Adds all the pages of the input PDF file for replacing the page of the base PDF file. replacePagesOperation.addPagesForReplace(secondInputFile, 3); // Execute the operation FileRef result = replacePagesOperation.execute(executionContext); // Save the result at the specified location result.saveAs("output/replacePagesOutput.pdf"); } 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 file. PageRanges pageRanges = new PageRanges(); // Add pages 1 to 3. pageRanges.addRange(1, 3); // Add page 4. pageRanges.addSinglePage(4); return pageRanges; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ReplacePDFPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance ReplacePagesOperation replacePagesOperation = ReplacePagesOperation.CreateNew(); // Set operation base input from a source file. FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf"); replacePagesOperation.SetBaseInput(baseSourceFile); // Create a FileRef instance using a local file. FileRef firstInputFile = FileRef.CreateFromLocalFile(@"replacePagesInput1.pdf"); PageRanges pageRanges = GetPageRangeForFirstFile(); // Adds the pages (specified by the page ranges) of the input PDF file for replacing the // page of the base PDF file. replacePagesOperation.AddPagesForReplace(firstInputFile, pageRanges, 1); // Create a FileRef instance using a local file. FileRef secondInputFile = FileRef.CreateFromLocalFile(@"replacePagesInput2.pdf"); // Adds all the pages of the input PDF file for replacing the page of the base PDF file. replacePagesOperation.AddPagesForReplace(secondInputFile, 3); // Execute the operation. FileRef result = replacePagesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/replacePagesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); // Catch more errors here . . . } 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")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRangesForFirstFile = () => { // Specify pages of the first file for replacing the page of base PDF file. const pageRangesForFirstFile = new PDFToolsSdk.PageRanges(); // Add pages 1 to 3. pageRangesForFirstFile.addPageRange(1, 3); // Add page 4. pageRangesForFirstFile.addSinglePage(4); return pageRangesForFirstFile; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), replacePagesOperation = PDFToolsSdk.ReplacePages.Operation.createNew(); // Set operation base input from a source file. const baseInputFile = PDFToolsSdk.FileRef.createFromLocalFile('resources/baseInput.pdf'); replacePagesOperation.setBaseInput(baseInputFile); // Create a FileRef instance using a local file. const firstInputFile = PDFToolsSdk.FileRef.createFromLocalFile('resources/replacePagesInput1.pdf'), pageRanges = getPageRangesForFirstFile(); // Adds the pages (specified by the page ranges) of the input PDF file for replacing the // page of the base PDF file. replacePagesOperation.addPagesForReplace(1, firstInputFile, pageRanges); // Create a FileRef instance using a local file. const secondInputFile = PDFToolsSdk.FileRef.createFromLocalFile('resources/replacePagesInput2.pdf'); // Adds all the pages of the input PDF file for replacing the page of the base PDF file. replacePagesOperation.addPagesForReplace(3, secondInputFile); // Execute the operation and Save the result to the specified location. replacePagesOperation.execute(executionContext) .then(result => result.saveAsFile('output/replacePagesOutput.pdf')) .catch(err => { if (err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The delete pages operation selectively removes pages from a PDF file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class DeletePDFPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(DeletePDFPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); DeletePagesOperation deletePagesOperation = DeletePagesOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/deletePagesInput.pdf"); deletePagesOperation.setInput(source); // Delete pages of the document (as specified by PageRanges). PageRanges pageRangeForDeletion = getPageRangeForDeletion(); deletePagesOperation.setPageRanges(pageRangeForDeletion); // Execute the operation. FileRef result = deletePagesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/deletePagesOutput.pdf"); } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } 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; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace DeletePDFPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { // Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance DeletePagesOperation deletePagesOperation = DeletePagesOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"deletePagesInput.pdf"); deletePagesOperation.SetInput(sourceFileRef); // Delete pages of the document (as specified by PageRanges). PageRanges pageRangeForDeletion = GetPageRangeForDeletion(); deletePagesOperation.SetPageRanges(pageRangeForDeletion); // Execute the operation. FileRef result = deletePagesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/deletePagesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } 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")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRangesForDeletion = () => { // Specify pages for deletion. const pageRangesForDeletion = new PDFToolsSdk.PageRanges(); // Add page 1. pageRangesForDeletion.addSinglePage(1); // Add pages 3 to 4. pageRangesForDeletion.addPageRange(3, 4); return pageRangesForDeletion; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), deletePagesOperation = PDFToolsSdk.DeletePages.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/deletePagesInput.pdf'); deletePagesOperation.setInput(input); // Delete pages of the document (as specified by PageRanges). const pageRangesForDeletion = getPageRangesForDeletion(); deletePagesOperation.setPageRanges(pageRangesForDeletion); // Execute the operation and Save the result to the specified location. deletePagesOperation.execute(executionContext) .then(result => result.saveAsFile('output/deletePagesOutput.pdf')) .catch(err => { if (err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The reorder pages operation moves pages from one location to another in a PDF file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class ReorderPDFPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(ReorderPDFPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); ReorderPagesOperation reorderPagesOperation = ReorderPagesOperation.createNew(); // Set operation input from a source file, along with specifying the order of the pages for // rearranging the pages in a PDF file. FileRef source = FileRef.createFromLocalFile("src/main/resources/reorderPagesInput.pdf"); PageRanges pageRanges = getPageRangeForReorder(); reorderPagesOperation.setInput(source); reorderPagesOperation.setPagesOrder(pageRanges); // Execute the operation. FileRef result = reorderPagesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/reorderPagesOutput.pdf"); } 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 document. PageRanges pageRanges = new PageRanges(); // Add pages 3 to 4. pageRanges.addRange(3, 4); // Add page 1. pageRanges.addSinglePage(1); return pageRanges; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace ReorderPDFPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { // Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance ReorderPagesOperation reorderPagesOperation = ReorderPagesOperation.CreateNew(); // Set operation input from a source file, along with specifying the order of the pages for // rearranging the pages in a PDF file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"reorderPagesInput.pdf"); reorderPagesOperation.SetInput(sourceFileRef); PageRanges pageRanges = GetPageRangeForReorder(); reorderPagesOperation.SetPagesOrder(pageRanges); // Execute the operation. FileRef result = reorderPagesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/reorderPagesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } 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")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRangeForReorder = () => { // Specify order of the pages for an output document. const pageRanges = new PDFToolsSdk.PageRanges(); // Add pages 3 to 4. pageRanges.addPageRange(3, 4); // Add page 1. pageRanges.addSinglePage(1); return pageRanges; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), reorderPagesOperation = PDFToolsSdk.ReorderPages.Operation.createNew(); // Set operation input from a source file, along with specifying the order of the pages for // rearranging the pages in a PDF file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/reorderPagesInput.pdf'); const pageRanges = getPageRangeForReorder(); reorderPagesOperation.setInput(input); reorderPagesOperation.setPagesOrder(pageRanges); // Execute the operation and Save the result to the specified location. reorderPagesOperation.execute(executionContext) .then(result => result.saveAsFile('output/reorderPagesOutput.pdf')) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
The rotate pages operation selectively rotates pages in PDF file. For example, you can change portrait view to landscape view.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class RotatePDFPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(RotatePDFPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); RotatePagesOperation rotatePagesOperation = RotatePagesOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/rotatePagesInput.pdf"); rotatePagesOperation.setInput(source); // Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges firstPageRange = getFirstPageRangeForRotation(); rotatePagesOperation.setAngleToRotatePagesBy(Angle._90, firstPageRange); // Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges secondPageRange = getSecondPageRangeForRotation(); rotatePagesOperation.setAngleToRotatePagesBy(Angle._180, secondPageRange); // Execute the operation. FileRef result = rotatePagesOperation.execute(executionContext); // Save the result to the specified location. result.saveAs("output/rotatePagesOutput.pdf"); } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } 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; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace RotatePDFPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { // Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance RotatePagesOperation rotatePagesOperation = RotatePagesOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"rotatePagesInput.pdf"); rotatePagesOperation.SetInput(sourceFileRef); // Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges firstPageRange = GetFirstPageRangeForRotation(); rotatePagesOperation.SetAngleToRotatePagesBy(Angle._90, firstPageRange); // Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. PageRanges secondPageRange = GetSecondPageRangeForRotation(); rotatePagesOperation.SetAngleToRotatePagesBy(Angle._180, secondPageRange); // Execute the operation. FileRef result = rotatePagesOperation.Execute(executionContext); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + "/output/rotatePagesOutput.pdf"); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } 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; } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getFirstPageRangeForRotation = () => { // Specify pages for rotation. const firstPageRange = new PDFToolsSdk.PageRanges(); // Add page 1. firstPageRange.addSinglePage(1); // Add pages 3 to 4. firstPageRange.addPageRange(3, 4); return firstPageRange; }; const getSecondPageRangeForRotation = () => { // Specify pages for rotation. const secondPageRange = new PDFToolsSdk.PageRanges(); // Add page 2. secondPageRange.addSinglePage(2); return secondPageRange; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. const executionContext = PDFToolsSdk.ExecutionContext.create(credentials), rotatePagesOperation = PDFToolsSdk.RotatePages.Operation.createNew(); // Set operation input from a source file. const input = PDFToolsSdk.FileRef.createFromLocalFile('resources/rotatePagesInput.pdf'); rotatePagesOperation.setInput(input); // Sets angle by 90 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. const firstPageRange = getFirstPageRangeForRotation(); rotatePagesOperation.setAngleToRotatePagesBy(PDFToolsSdk.RotatePages.Angle._90, firstPageRange); // Sets angle by 180 degrees (in clockwise direction) for rotating the specified pages of // the input PDF file. const secondPageRange = getSecondPageRangeForRotation(); rotatePagesOperation.setAngleToRotatePagesBy(PDFToolsSdk.RotatePages.Angle._180,secondPageRange); // Execute the operation and Save the result to the specified location. rotatePagesOperation.execute(executionContext) .then(result => result.saveAsFile('output/rotatePagesOutput.pdf')) .catch(err => { if (err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
This operation splits a PDF into multiple smaller documents. Simply use the page count to specify the maximum number of pages of each output file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class SplitPDFByNumberOfPages { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(SplitPDFByNumberOfPages.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); SplitPDFOperation splitPDFOperation = SplitPDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/splitPDFInput.pdf"); splitPDFOperation.setInput(source); // Set the maximum number of pages each of the output files can have. splitPDFOperation.setPageCount(2); // Execute the operation. Listresult = splitPDFOperation.execute(executionContext); // Save the result to the specified location. int index = 0; for (FileRef fileRef : result) { fileRef.saveAs("output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf"); index++; } } catch (IOException| ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace SplitPDFByNumberOfPages { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance SplitPDFOperation splitPDFOperation = SplitPDFOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"splitPDFInput.pdf"); splitPDFOperation.SetInput(sourceFileRef); // Set the maximum number of pages each of the output files can have. splitPDFOperation.SetPageCount(2); // Execute the operation. Listresult = splitPDFOperation.Execute(executionContext); // Save the result to the specified location. int index = 0; foreach (FileRef fileRef in result) { fileRef.SaveAs(Directory.GetCurrentDirectory() + "/output/SplitPDFByNumberOfPagesOutput_" + index + ".pdf"); index++; } } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Create a new operation instance. const splitPDFOperation = PDFToolsSdk.SplitPDF.Operation.createNew(), input = PDFToolsSdk.FileRef.createFromLocalFile( 'resources/splitPDFInput.pdf', PDFToolsSdk.SplitPDF.SupportedSourceFormat.pdf ); // Set operation input from a source file. splitPDFOperation.setInput(input); // Set the maximum number of pages each of the output files can have. splitPDFOperation.setPageCount(2); // Execute the operation and Save the result to the specified location. splitPDFOperation.execute(executionContext) .then(result => { let saveFilesPromises = []; for(let i = 0; i < result.length; i++){ saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFByNumberOfPagesOutput_${i}.pdf`)); } return Promise.all(saveFilesPromises); }) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
As an alternative to creating smaller PDFs with a set number of pages, you can split PDFs into multiple smaller documents by specifying page ranges where each page range corresponds to a single output file.
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class SplitPDFByPageRanges { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(SplitPDFByPageRanges.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); SplitPDFOperation splitPDFOperation = SplitPDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/splitPDFInput.pdf"); splitPDFOperation.setInput(source); // Set the page ranges where each page range corresponds to a single output file. PageRanges pageRanges = getPageRanges(); splitPDFOperation.setPageRanges(pageRanges); // Execute the operation. Listresult = splitPDFOperation.execute(executionContext); // Save the result to the specified location. int index = 0; for (FileRef fileRef : result) { fileRef.saveAs("output/SplitPDFByPageRangesOutput_" + index + ".pdf"); index++; } } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } private static PageRanges getPageRanges() { // Specify page ranges. PageRanges pageRanges = new PageRanges(); // Add page 1. pageRanges.addSinglePage(1); // Add pages 3 to 4. pageRanges.addRange(3, 4); return pageRanges; } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace SplitPDFByPageRanges { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance SplitPDFOperation splitPDFOperation = SplitPDFOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"splitPDFInput.pdf"); splitPDFOperation.SetInput(sourceFileRef); // Set the page ranges where each page range corresponds to a single output file. PageRanges pageRanges = GetPageRanges(); splitPDFOperation.SetPageRanges(pageRanges); // Execute the operation. Listresult = splitPDFOperation.Execute(executionContext); // Save the result to the specified location. int index = 0; foreach (FileRef fileRef in result) { fileRef.SaveAs(Directory.GetCurrentDirectory() + "/output/SplitPDFByPageRangesOutput_" + index + ".pdf"); index++; } } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } private static PageRanges GetPageRanges() { // Specify page ranges. PageRanges pageRanges = new PageRanges(); // Add page 1. pageRanges.AddSinglePage(1); // Add pages 3 to 4. pageRanges.AddRange(3, 4); return pageRanges; } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); const getPageRanges = () => { // Specify pages ranges. const pageRanges = new PDFToolsSdk.PageRanges(); // Add page 1. pageRanges.addSinglePage(1); // Add pages 3 to 4. pageRanges.addPageRange(3, 4); return pageRanges; }; try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Create a new operation instance. const splitPDFOperation = PDFToolsSdk.SplitPDF.Operation.createNew(), input = PDFToolsSdk.FileRef.createFromLocalFile( 'resources/splitPDFInput.pdf', PDFToolsSdk.SplitPDF.SupportedSourceFormat.pdf ); // Set operation input from a source file. splitPDFOperation.setInput(input); // Set the page ranges where each page range corresponds to a single output file. const pageRanges = getPageRanges(); splitPDFOperation.setPageRanges(pageRanges); // Execute the operation and Save the result to the specified location. splitPDFOperation.execute(executionContext) .then(result => { let saveFilesPromises = []; for(let i = 0; i < result.length; i++){ saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFByPageRangesOutput_${i}.pdf`)); } return Promise.all(saveFilesPromises); }) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }
As an alternative to creating smaller PDFs by specifying a set number of pages or a page range, you can split PDFs by file count. In this case, the operation creates the specified number of files with each containing an identical number of pages (if possible).
// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples public class SplitPDFIntoNumberOfFiles { // Initialize the logger. private static final Logger LOGGER = LoggerFactory.getLogger(SplitPDFIntoNumberOfFiles.class); public static void main(String[] args) { try { // Initial setup, create credentials instance. Credentials credentials = Credentials.serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.create(credentials); SplitPDFOperation splitPDFOperation = SplitPDFOperation.createNew(); // Set operation input from a source file. FileRef source = FileRef.createFromLocalFile("src/main/resources/splitPDFInput.pdf"); splitPDFOperation.setInput(source); // Set the number of documents to split the input PDF file into. splitPDFOperation.setFileCount(2); // Execute the operation. Listresult = splitPDFOperation.execute(executionContext); // Save the result to the specified location. int index = 0; for (FileRef fileRef : result) { fileRef.saveAs("output/SplitPDFIntoNumberOfFilesOutput_" + index + ".pdf"); index++; } } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) { LOGGER.error("Exception encountered while executing operation", e); } } }
// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples namespace SplitPDFIntoNumberOfFiles { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServiceAccountCredentialsBuilder() .FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json") .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Create a new operation instance SplitPDFOperation splitPDFOperation = SplitPDFOperation.CreateNew(); // Set operation input from a source file. FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"splitPDFInput.pdf"); splitPDFOperation.SetInput(sourceFileRef); // Set the number of documents to split the input PDF file into. splitPDFOperation.SetFileCount(2); // Execute the operation. Listresult = splitPDFOperation.Execute(executionContext); // Save the result to the specified location. int index = 0; foreach (FileRef fileRef in result) { fileRef.SaveAs(Directory.GetCurrentDirectory() + "/output/SplitPDFIntoNumberOfFilesOutput_" + index + ".pdf"); index++; } } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } // Catch more errors here . . . } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } } }
// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample const PDFToolsSdk = require('@adobe/documentservices-pdftools-node-sdk'); try { // Initial setup, create credentials instance. const credentials = PDFToolsSdk.Credentials .serviceAccountCredentialsBuilder() .fromFile("pdftools-api-credentials.json") .build(); // Create an ExecutionContext using credentials const executionContext = PDFToolsSdk.ExecutionContext.create(credentials); // Create a new operation instance. const splitPDFOperation = PDFToolsSdk.SplitPDF.Operation.createNew(), input = PDFToolsSdk.FileRef.createFromLocalFile( 'resources/splitPDFInput.pdf', PDFToolsSdk.SplitPDF.SupportedSourceFormat.pdf ); // Set operation input from a source file. splitPDFOperation.setInput(input); // Set the number of documents to split the input PDF file into. splitPDFOperation.setFileCount(2); // Execute the operation and Save the result to the specified location. splitPDFOperation.execute(executionContext) .then(result => { let saveFilesPromises = []; for(let i = 0; i < result.length; i++){ saveFilesPromises.push(result[i].saveAsFile(`output/SplitPDFIntoNumberOfFilesOutput_${i}.pdf`)); } return Promise.all(saveFilesPromises); }) .catch(err => { if(err instanceof PDFToolsSdk.Error.ServiceApiError || err instanceof PDFToolsSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing operation', err); } else { console.log('Exception encountered while executing operation', err); } }); } catch (err) { console.log('Exception encountered while executing operation', err); }