REST API
Node js
.NET
Java
Python
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Document-Generationcurl --location --request POST 'https://pdf-services.adobe.io/operation/documentgeneration' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","outputFormat": "pdf","jsonDataForMerge": {"customerName": "Kane Miller","customerVisits": 100,"itemsBought": [{"name": "Sprays","quantity": 50,"amount": 100},{"name": "Chemicals","quantity": 100,"amount": 200}],"totalAmount": 300,"previousBalance": 50,"lastThreeBillings": [100,200,300],"photograph": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP88h8AAu0B9XNPCQQAAAAASUVORK5CYII="}}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-documentGeneration
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/documentmerge/merge-document-to-pdf.jsconst {ServicePrincipalCredentials,PDFServices,MimeType,DocumentMergeParams,OutputFormat,DocumentMergeJob,DocumentMergeResult,SDKError,ServiceUsageError,ServiceApiError} = require("@adobe/pdfservices-node-sdk");const fs = require("fs");(async () => {let readStream;try {// Initial setup, create credentials instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Setup input data for the document merge processconst jsonDataForMerge = {customerName: "Kane Miller",customerVisits: 100}// Creates an asset(s) from source file(s) and uploadreadStream = fs.createReadStream("./documentMergeTemplate.docx");const inputAsset = await pdfServices.upload({readStream,mimeType: MimeType.DOCX});// Create parameters for the jobconst params = new DocumentMergeParams({jsonDataForMerge,outputFormat: OutputFormat.PDF});// Creates a new job instanceconst job = new DocumentMergeJob({inputAsset,params});// Submit the job and get the job resultconst pollingURL = await pdfServices.submit({job});const pdfServicesResponse = await pdfServices.getJobResult({pollingURL,resultType: DocumentMergeResult});// Get content from the resulting asset(s)const resultAsset = pdfServicesResponse.result.asset;const streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates a write stream and copy stream asset's content to itconst outputFilePath = "./documentMergeOutput.pdf";console.log(`Saving asset at ${outputFilePath}`);const writeStream = fs.createWriteStream(outputFilePath);streamAsset.readStream.pipe(writeStream);} catch (err) {if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {console.log("Exception encountered while executing operation", err);} else {console.log("Exception encountered while executing operation", err);}} finally {readStream?.destroy();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd MergeDocumentToPDF/// dotnet run MergeDocumentToPDF.csprojnamespace MergeDocumentToPDF{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){//Configure the loggingConfigureLogging();try{// Initial setup, create credentials instanceICredentials credentials = new ServicePrincipalCredentials(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset from source file and uploadusing Stream inputStream = File.OpenRead(@"documentMergeTemplate.docx");IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());// Setup input data for the document merge processJObject jsonDataForMerge = JObject.Parse("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.DocumentMergeParamsBuilder().WithJsonDataForMerge(jsonDataForMerge).WithOutputFormat(OutputFormat.PDF).Build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submits the job and gets the job resultString location = pdfServices.Submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse =pdfServices.GetJobResult<DocumentMergeResult>(location, typeof(DocumentMergeResult));// Get content from the resulting asset(s)IAsset resultAsset = pdfServicesResponse.Result.Asset;StreamAsset streamAsset = pdfServices.GetContent(resultAsset);// Creating output streams and copying stream asset's content to itString outputFilePath = "/output/documentMergeOutput.pdf";new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);streamAsset.Stream.CopyTo(outputStream);outputStream.Close();}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);}catch (ServiceApiException ex){log.Error("Exception encountered while executing operation", ex);}catch (SDKException ex){log.Error("Exception encountered while executing operation", ex);}catch (IOException ex){log.Error("Exception encountered while executing operation", ex);}catch (Exception ex){log.Error("Exception encountered while executing operation", ex);}}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.documentmerge.MergeDocumentToPDFpackage com.adobe.pdfservices.operation.samples.documentmerge;public class MergeDocumentToPDF {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(MergeDocumentToPDF.class);public static void main(String[] args) {try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/documentMergeTemplate.docx").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Setup input data for the document merge process.JSONObject jsonDataForMerge = new JSONObject("{\"customerName\": \"Kane Miller\",\"customerVisits\": 100}");// Creates an asset(s) from source file(s) and uploadAsset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());// Create parameters for the jobDocumentMergeParams documentMergeParams = DocumentMergeParams.documentMergeParamsBuilder().withJsonDataForMerge(jsonDataForMerge).withOutputFormat(OutputFormat.PDF).build();// Creates a new job instanceDocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);// Submit the job and gets the job resultString location = pdfServices.submit(documentMergeJob);PDFServicesResponse<DocumentMergeResult> pdfServicesResponse = pdfServices.getJobResult(location, DocumentMergeResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itOutputStream outputStream = Files.newOutputStream(new File("output/documentMergeOutput.pdf").toPath());IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {LOGGER.error("Exception encountered while executing operation", ex);}}}
Copied to your clipboard# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/documentmerge/merge_document_to_pdf.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class MergeDocumentToPDF:def __init__(self):try:file = open("./salesOrderTemplate.docx", "rb")input_stream = file.read()file.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadinput_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)# Setup input data for the document merge processwith open("./salesOrder.json", "r") as file:content_string = file.read()json_data_for_merge = json.loads(content_string)# Create parameters for the jobdocument_merge_params = DocumentMergeParams(json_data_for_merge=json_data_for_merge, output_format=OutputFormat.PDF)# Creates a new job instancedocument_merge_job = DocumentMergeJob(input_asset=input_asset, document_merge_params=document_merge_params)# Submit the job and gets the job resultlocation = pdf_services.submit(document_merge_job)pdf_services_response = pdf_services.get_job_result(location, DocumentMergePDFResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "output/MergeDocumentToPDF.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")if __name__ == "__main__":MergeDocumentToPDF()