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
Python
REST API
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.compresspdf.CompressPDFpublic class CompressPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submit the job and gets the job resultString location = pdfServices.submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creating an output stream and copying stream asset content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFOutput.pdf").toPath());LOGGER.info("Saving asset at output/compressPDFOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CompressPDF/// dotnet run CompressPDF.csprojnamespace CompressPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"compressPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset);// Submits the job and gets the job resultString location = pdfServices.Submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse =pdfServices.GetJobResult<CompressPDFResult>(location, typeof(CompressPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/compressPDFOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/compresspdf/compress-pdf.jsconst {ServicePrincipalCredentials,PDFServices,MimeType,CompressPDFJob,CompressPDFResult,SDKError,ServiceUsageError,ServiceApiError} = require("@adobe/pdfservices-node-sdk");const fs = require("fs");(async () => {let readStream;try {// Initial setup, create credentials instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./compressPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Creates a new job instanceconst job = new CompressPDFJob({inputAsset});// Submit the job and get the job resultconst pollingURL = await pdfServices.submit({job});const pdfServicesResponse = await pdfServices.getJobResult({pollingURL,resultType: CompressPDFResult});// Get content from the resulting asset(s)const resultAsset = pdfServicesResponse.result.asset;const streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates an output stream and copy stream asset's content to itconst outputFilePath = "./compressPDFOutput.pdf";console.log(`Saving asset at ${outputFilePath}`);const outputStream = fs.createWriteStream(outputFilePath);streamAsset.readStream.pipe(outputStream);} catch (err) {if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {console.log("Exception encountered while executing operation", err);} else {console.log("Exception encountered while executing operation", err);}} finally {readStream?.destroy();}})();
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/compresspdf/compress_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class CompressPDF:def __init__(self):try:file = open('./compressPDFInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream,mime_type=PDFServicesMediaType.PDF)# Creates a new job instancecompress_pdf_job = CompressPDFJob(input_asset=input_asset)# Submit the job and gets the job resultlocation = pdf_services.submit(compress_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CompressPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'output/CompressPDF.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":CompressPDF()
Copied to your clipboard// Please refer our REST API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"}'
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
Python
REST API
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.compresspdf.CompressPDFWithOptionspublic class CompressPDFWithOptions {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(CompressPDFWithOptions.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/compressPDFInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.PDF.getMediaType());// Create parameters for the jobCompressPDFParams compressPDFParams = CompressPDFParams.compressPDFParamsBuilder().withCompressionLevel(CompressionLevel.LOW).build();// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset).setParams(compressPDFParams);// Submit the job and gets the job resultString location = pdfServices.submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CompressPDFResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creating an output stream and copying stream asset content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/compressPDFWithOptionsOutput.pdf").toPath());LOGGER.info("Saving asset at output/compressPDFWithOptionsOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd CompressPDF/// dotnet run CompressPDFWithOptions.csprojnamespace CompressPDFWithOptions{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadusing Stream inputStream = File.OpenRead(@"compressPDFInput.pdf");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.PDF.GetMIMETypeValue());// Create parameters for the jobCompressPDFParams compressPDFParams = CompressPDFParams.CompressPDFParamsBuilder().WithCompressionLevel(CompressionLevel.MEDIUM).Build();// Creates a new job instanceCompressPDFJob compressPDFJob = new CompressPDFJob(asset).SetParams(compressPDFParams);// Submits the job and gets the job resultString location = pdfServices.Submit(compressPDFJob);PDFServicesResponse<CompressPDFResult> pdfServicesResponse =pdfServices.GetJobResult<CompressPDFResult>(location, typeof(CompressPDFResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/compressPDFWithOptionsOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/compresspdf/compress-pdf-with-options.jsconst {ServicePrincipalCredentials,PDFServices,MimeType,CompressPDFJob,CompressPDFParams,CompressionLevel,CompressPDFResult,SDKError,ServiceUsageError,ServiceApiError} = require("@adobe/pdfservices-node-sdk");const fs = require("fs");(async () => {let readStream;try {// Initial setup, create credentials instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./compressPDFInput.pdf");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.PDF});// Set the compression levelconst params = new CompressPDFParams({compressionLevel: CompressionLevel.LOW,});// Creates a new job instanceconst job = new CompressPDFJob({inputAsset, params});// Submit the job and get the job resultconst pollingURL = await pdfServices.submit({job});const pdfServicesResponse = await pdfServices.getJobResult({pollingURL,resultType: CompressPDFResult});// Get content from the resulting asset(s)const resultAsset = pdfServicesResponse.result.asset;const streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates an output stream and copy stream asset's content to itconst outputFilePath = createOutputFilePath();console.log(`Saving asset at ${outputFilePath}`);const outputStream = "./compressPDFWithOptionsOutput.pdf";streamAsset.readStream.pipe(outputStream);} catch (err) {if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {console.log("Exception encountered while executing operation", err);} else {console.log("Exception encountered while executing operation", err);}} finally {readStream?.destroy();}})();
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python python src/compresspdf/compress_pdf_with_options.pyclass CompressPDFWithOptions:def __init__(self):try:file = open('./compressPDFInput.pdf', 'rb')input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET'))# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream,mime_type=PDFServicesMediaType.PDF)# Create parameters for the jobcompress_pdf_params = CompressPDFParams(compression_level=CompressionLevel.LOW)# Creates a new job instancecompress_pdf_job = CompressPDFJob(input_asset=input_asset,compress_pdf_params=compress_pdf_params)# Submit the job and gets the job resultlocation = pdf_services.submit(compress_pdf_job)pdf_services_response = pdf_services.get_job_result(location, CompressPDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = 'output/CompressPDFWithOptions.pdf'with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f'Exception encountered while executing operation: {e}')if __name__ == "__main__":CompressPDFWithOptions()
Copied to your clipboard// Please refer our REST API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Compress-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/compresspdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","compressionLevel": "MEDIUM"}'