Compress PDFs
Reduce the size of PDF files by compressing to smaller sizes for lower bandwidth viewing, downloading, and sharing.
Support for multiple compression levels to retain the quality of images and graphics
REST API
See our public API Reference for Compress PDF
Compress PDFs
Compress PDFs to reduce the file size prior to performing workflow operations that use bandwidth or memory.
Please refer the API usage guide to understand how to use our APIs.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.compresspdf.CompressPDF45 public class CompressPDF {6 // Initialize the logger.7 private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDF.class);89 public static void main(String[] args) {1011 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {12 // Initial setup, create credentials instance13 Credentials credentials = new ServicePrincipalCredentials(14 System.getenv("PDF_SERVICES_CLIENT_ID"),15 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1617 // Creates a PDF Services instance18 PDFServices pdfServices = new PDFServices(credentials);1920 // Creates an asset(s) from source file(s) and upload21 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());2223 // Creates a new job instance24 CompressPDFJob compressPDFJob = new CompressPDFJob(asset);2526 // Submit the job and gets the job result27 String location = pdfServices.submit(compressPDFJob);28 PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);2930 // Get content from the resulting asset(s)31 Asset resultAsset = pdfServicesResponse.getResult().getAsset();32 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3334 // Creating an output stream and copying stream asset content to it35 Files.createDirectories(Paths.get("output/"));36 OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFOutput.pdf").toPath());37 LOGGER.info("Saving asset at output/compressPDFOutput.pdf");38 IOUtils.copy(streamAsset.getInputStream(), outputStream);39 outputStream.close();40 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {41 LOGGER.error("Exception encountered while executing operation", ex);42 }43 }44 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CompressPDF/4// dotnet run CompressPDF.csproj56 namespace CompressPDF7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {17 // Initial setup, create credentials instance.18 Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder()19 .WithClientId("PDF_SERVICES_CLIENT_ID")20 .WithClientSecret("PDF_SERVICES_CLIENT_SECRET")21 .Build();2223 // Create an ExecutionContext using credentials and create a new operation instance.24 ExecutionContext executionContext = ExecutionContext.Create(credentials);25 CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew();2627 // Set operation input from a source file.28 FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"compressPDFInput.pdf");29 compressPDFOperation.SetInput(sourceFileRef);3031 // Execute the operation.32 FileRef result = compressPDFOperation.Execute(executionContext);3334 // Save the result to the specified location.35 result.SaveAs(Directory.GetCurrentDirectory() + "/output/compressPDFOutput.pdf");36 }37 catch (ServiceUsageException ex)38 {39 log.Error("Exception encountered while executing operation", ex);40 }41 // Catch more errors here . . .42 }4344 static void ConfigureLogging()45 {46 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());47 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));48 }49 }50 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/compresspdf/compress-pdf.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CompressPDFJob,10 CompressPDFResult,11 SDKError,12 ServiceUsageError,13 ServiceApiError14} = require("@adobe/pdfservices-node-sdk");15const fs = require("fs");1617(async () => {18 let readStream;19 try {20 // Initial setup, create credentials instance21 const credentials = new ServicePrincipalCredentials({22 clientId: process.env.PDF_SERVICES_CLIENT_ID,23 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET24 });2526 // Creates a PDF Services instance27 const pdfServices = new PDFServices({credentials});2829 // Creates an asset(s) from source file(s) and upload30 readStream = fs.createReadStream("./compressPDFInput.pdf");31 const inputAsset = await pdfServices.upload({32 readStream,33 mimeType: MimeType.PDF34 });3536 // Creates a new job instance37 const job = new CompressPDFJob({inputAsset});3839 // Submit the job and get the job result40 const pollingURL = await pdfServices.submit({job});41 const pdfServicesResponse = await pdfServices.getJobResult({42 pollingURL,43 resultType: CompressPDFResult44 });4546 // Get content from the resulting asset(s)47 const resultAsset = pdfServicesResponse.result.asset;48 const streamAsset = await pdfServices.getContent({asset: resultAsset});4950 // Creates an output stream and copy stream asset's content to it51 const outputFilePath = "./compressPDFOutput.pdf";52 console.log(`Saving asset at ${outputFilePath}`);5354 const outputStream = fs.createWriteStream(outputFilePath);55 streamAsset.readStream.pipe(outputStream);56 } catch (err) {57 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {58 console.log("Exception encountered while executing operation", err);59 } else {60 console.log("Exception encountered while executing operation", err);61 }62 } finally {63 readStream?.destroy();64 }65})();
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \5--header 'x-api-key: {{Placeholder for client_id}}' \6--header 'Content-Type: application/json' \7--header 'Authorization: Bearer {{Placeholder for token}}' \8--data-raw '{9 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"10}'11
Compress PDFs with Compression Level
Compress PDFs to reduce the file size on the basis of provided
compression level, prior to performing workflow operations that use
bandwidth or memory. Refer to CompressionLevel
in the API docs for a
list of supported compression levels.
Please refer the API usage guide to understand how to use our APIs.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.compresspdf.CompressPDFWithOptions45 public class CompressPDFWithOptions {6 // Initialize the logger.7 private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDFWithOptions.class);89 public static void main(String[] args) {1011 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {12 // Initial setup, create credentials instance13 Credentials credentials = new ServicePrincipalCredentials(14 System.getenv("PDF_SERVICES_CLIENT_ID"),15 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1617 // Creates a PDF Services instance18 PDFServices pdfServices = new PDFServices(credentials);1920 // Creates an asset(s) from source file(s) and upload21 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());2223 // Create parameters for the job24 CompressPDFParams compressPDFParams = CompressPDFParams.compressPDFParamsBuilder()25 .withCompressionLevel(CompressionLevel.LOW)26 .build();2728 // Creates a new job instance29 CompressPDFJob compressPDFJob = new CompressPDFJob(asset)30 .setParams(compressPDFParams);3132 // Submit the job and gets the job result33 String location = pdfServices.submit(compressPDFJob);34 PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);3536 // Get content from the resulting asset(s)37 Asset resultAsset = pdfServicesResponse.getResult().getAsset();38 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3940 // Creating an output stream and copying stream asset content to it41 Files.createDirectories(Paths.get("output/"));42 OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFWithOptionsOutput.pdf").toPath());43 LOGGER.info("Saving asset at output/compressPDFWithOptionsOutput.pdf");44 IOUtils.copy(streamAsset.getInputStream(), outputStream);45 outputStream.close();46 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {47 LOGGER.error("Exception encountered while executing operation", ex);48 }49 }50 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CompressPDF/4// dotnet run CompressPDFWithOptions.csproj56 namespace CompressPDFWithOptions7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {17 // Initial setup, create credentials instance.18 Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder()19 .WithClientId("PDF_SERVICES_CLIENT_ID")20 .WithClientSecret("PDF_SERVICES_CLIENT_SECRET")21 .Build();2223 // Create an ExecutionContext using credentials and create a new operation instance.24 ExecutionContext executionContext = ExecutionContext.Create(credentials);25 CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew();2627 // Set operation input from a source file.28 FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"compressPDFInput.pdf");29 compressPDFOperation.SetInput(sourceFileRef);3031 // Build CompressPDF options from supported compression levels and set them into the operation32 CompressPDFOptions compressPDFOptions = CompressPDFOptions.CompressPDFOptionsBuilder()33 .WithCompressionLevel(CompressionLevel.LOW)34 .Build();35 compressPDFOperation.SetOptions(compressPDFOptions);3637 // Execute the operation.38 FileRef result = compressPDFOperation.Execute(executionContext);3940 // Save the result to the specified location.41 result.SaveAs(Directory.GetCurrentDirectory() + "/output/compressPDFWithOptionsOutput.pdf");42 }43 catch (ServiceUsageException ex)44 {45 log.Error("Exception encountered while executing operation", ex);46 }47 // Catch more errors here . . .48 }4950 static void ConfigureLogging()51 {52 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());53 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));54 }55 }56 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/compresspdf/compress-pdf-with-options.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CompressPDFJob,10 CompressPDFParams,11 CompressionLevel,12 CompressPDFResult,13 SDKError,14 ServiceUsageError,15 ServiceApiError16} = require("@adobe/pdfservices-node-sdk");17const fs = require("fs");1819(async () => {20 let readStream;21 try {22 // Initial setup, create credentials instance23 const credentials = new ServicePrincipalCredentials({24 clientId: process.env.PDF_SERVICES_CLIENT_ID,25 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET26 });2728 // Creates a PDF Services instance29 const pdfServices = new PDFServices({credentials});3031 // Creates an asset(s) from source file(s) and upload32 readStream = fs.createReadStream("./compressPDFInput.pdf");33 const inputAsset = await pdfServices.upload({34 readStream,35 mimeType: MimeType.PDF36 });3738 // Set the compression level39 const params = new CompressPDFParams({40 compressionLevel: CompressionLevel.LOW,41 });4243 // Creates a new job instance44 const job = new CompressPDFJob({inputAsset, params});4546 // Submit the job and get the job result47 const pollingURL = await pdfServices.submit({job});48 const pdfServicesResponse = await pdfServices.getJobResult({49 pollingURL,50 resultType: CompressPDFResult51 });5253 // Get content from the resulting asset(s)54 const resultAsset = pdfServicesResponse.result.asset;55 const streamAsset = await pdfServices.getContent({asset: resultAsset});5657 // Creates an output stream and copy stream asset's content to it58 const outputFilePath = createOutputFilePath();59 console.log(`Saving asset at ${outputFilePath}`);6061 const outputStream = "./compressPDFWithOptionsOutput.pdf";62 streamAsset.readStream.pipe(outputStream);63 } catch (err) {64 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {65 console.log("Exception encountered while executing operation", err);66 } else {67 console.log("Exception encountered while executing operation", err);68 }69 } finally {70 readStream?.destroy();71 }72})();
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \5--header 'x-api-key: {{Placeholder for client_id}}' \6--header 'Content-Type: application/json' \7--header 'Authorization: Bearer {{Placeholder for token}}' \8--data-raw '{9 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",10 "compressionLevel": "MEDIUM"11}'