Create PDF
Create PDFs from a variety of formats, including static and dynamic HTML; Microsoft Word, PowerPoint, and Excel; as well as text, image, Zip, and URL. Support for HTML to PDF, DOC to PDF, DOCX to PDF, PPT to PDF, PPTX to PDF, XLS to PDF, XLSX to PDF, TXT to PDF, RTF to PDF, BMP to PDF, JPEG to PDF, GIF to PDF, TIFF to PDF, PNG to PDF
REST API
See our public API Reference for :
Create a PDF
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)
If a Microsoft Word/PowerPoint input file has an embedded TrueType font, the output pdf will also contain the same embedded TrueType font. For more information, refer Benefits of embedding custom fonts.
We do not support HTML to PDF conversion for requests containing urls where:
1. The URL Scheme is not HTTPS.
2. The hostname resolves to a non-routable IP address. This encompasses scenarios where redirects lead to non-routable IP addresses as well.
Please refer the API usage guide to understand how to use our APIs.
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.createpdf.CreatePDFFromDOCX45public class CreatePDFFromDOCX {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDOCX.class);910 public static void main(String[] args) {1112 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFInput.docx").toPath())) {13 // Initial setup, create credentials instance14 Credentials credentials = new ServicePrincipalCredentials(15 System.getenv("PDF_SERVICES_CLIENT_ID"),16 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1718 // Creates a PDF Services instance19 PDFServices pdfServices = new PDFServices(credentials);2021 // Creates an asset(s) from source file(s) and upload22 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());2324 // Creates a new job instance25 CreatePDFJob createPDFJob = new CreatePDFJob(asset);2627 // Submit the job and gets the job result28 String location = pdfServices.submit(createPDFJob);29 PDFServicesResponse<CreatePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CreatePDFResult.class);3031 // Get content from the resulting asset(s)32 Asset resultAsset = pdfServicesResponse.getResult().getAsset();33 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3435 // Creates an output stream and copy stream asset's content to it36 File.createDirectories(Paths.get("output/"));37 OutputStream outputStream = Files.newOutputStream(new File("output/createPDFFromDOCX.pdf").toPath());38 LOGGER.info("Saving asset at output/createPDFFromDOCX.pdf");39 IOUtils.copy(streamAsset.getInputStream(), outputStream);40 outputStream.close();41 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {42 LOGGER.error("Exception encountered while executing the operation", ex);43 }44 }45}
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CreatePDFFromDocx/4// dotnet run CreatePDFFromDocx.csproj56namespace CreatePDFFromDocx7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 // Creates an asset(s) from source file(s) and upload27 using Stream inputStream = File.OpenRead(@"createPdfInput.docx");28 IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());2930 // Creates a new job instance31 CreatePDFJob createPDFJob = new CreatePDFJob(asset);3233 // Submits the job and gets the job result34 String location = pdfServices.Submit(createPDFJob);35 PDFServicesResponse<CreatePDFResult> pdfServicesResponse =36 pdfServices.GetJobResult<CreatePDFResult>(location, typeof(CreatePDFResult));3738 // Get content from the resulting asset(s)39 IAsset resultAsset = pdfServicesResponse.Result.Asset;40 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4142 // Creating output streams and copying stream asset's content to it43 String outputFilePath = "/output/createPdfOutput.pdf";44 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();45 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);46 streamAsset.Stream.CopyTo(outputStream);47 outputStream.Close();48 }49 catch (ServiceUsageException ex)50 {51 log.Error("Exception encountered while executing operation", ex);52 }53 catch (ServiceApiException ex)54 {55 log.Error("Exception encountered while executing operation", ex);56 }57 catch (SDKException ex)58 {59 log.Error("Exception encountered while executing operation", ex);60 }61 catch (IOException ex)62 {63 log.Error("Exception encountered while executing operation", ex);64 }65 catch (Exception ex)66 {67 log.Error("Exception encountered while executing operation", ex);68 }69 }7071 static void ConfigureLogging()72 {73 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());74 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));75 }76 }77}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/createpdf/create-pdf-from-docx.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CreatePDFJob,10 CreatePDFResult,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("./createPDFInput.docx");31 const inputAsset = await pdfServices.upload({32 readStream,33 mimeType: MimeType.DOCX34 });3536 // Creates a new job instance37 const job = new CreatePDFJob({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: CreatePDFResult44 });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 result asset's content to it51 const outputFilePath = "./createPDFFromDOCX.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# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/createpdf/create_pdf_from_docx.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class CreatePDFFromDOCX:9 def __init__(self):10 try:11 file = open('./createPDFInput.docx', 'rb')12 input_stream = file.read()13 file.close()1415 # Initial setup, create credentials instance16 credentials = ServicePrincipalCredentials(17 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),18 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')19 )2021 # Creates a PDF Services instance22 pdf_services = PDFServices(credentials=credentials)2324 # Creates an asset(s) from source file(s) and upload25 input_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)2627 # Creates a new job instance28 create_pdf_job = CreatePDFJob(input_asset)2930 # Submit the job and gets the job result31 location = pdf_services.submit(create_pdf_job)32 pdf_services_response = pdf_services.get_job_result(location, CreatePDFResult)3334 # Get content from the resulting asset(s)35 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()36 stream_asset: StreamAsset = pdf_services.get_content(result_asset)3738 # Creates an output stream and copy stream asset's content to it39 output_file_path = 'output/CreatePDFFromDOCX.pdf'40 with open(output_file_path, "wb") as file:41 file.write(stream_asset.get_input_stream())4243 except (ServiceApiException, ServiceUsageException, SdkException) as e:44 logging.exception(f'Exception encountered while executing operation: {e}')4546if __name__ == "__main__":47 CreatePDFFromDOCX()
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \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}'
Create PDF with DocumentLanguage
Use the sample below to create PDFs with supported documentLanguage from Microsoft Office documents (Word, Excel and PowerPoint). The example shows .docx file conversion with english as the language of the input file, the SDK supports the following formats:
- Microsoft Word (DOC, DOCX)
- Microsoft PowerPoint (PPT, PPTX)
- Microsoft Excel (XLS, XLSX)
- Text (TXT, RTF)
Please refer the API usage guide to understand how to use our APIs.
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.createpdf.CreatePDFFromDOCXWithOptions45public class CreatePDFFromDOCXWithOptions {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(CreatePDFFromDOCXWithOptions.class);910 public static void main(String[] args) {1112 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFInput.docx").toPath())) {13 // Initial setup, create credentials instance14 Credentials credentials = new ServicePrincipalCredentials(15 System.getenv("PDF_SERVICES_CLIENT_ID"),16 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1718 // Creates a PDF Services instance19 PDFServices pdfServices = new PDFServices(credentials);2021 // Creates an asset(s) from source file(s) and upload22 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());2324 // Create parameters for the job25 CreatePDFParams createPDFWordParams = CreatePDFParams.wordParamsBuilder().26 withDocumentLanguage(DocumentLanguage.EN_US).27 build();2829 // Creates a new job instance30 CreatePDFJob createPDFJob = new CreatePDFJob(asset)31 .setParams(createPDFWordParams);3233 // Submit the job and gets the job result34 String location = pdfServices.submit(createPDFJob);35 PDFServicesResponse<CreatePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CreatePDFResult.class);3637 // Get content from the resulting asset(s)38 Asset resultAsset = pdfServicesResponse.getResult().getAsset();39 StreamAsset streamAsset = pdfServices.getContent(resultAsset);4041 // Creates an output stream and copy stream asset's content to it42 File.createDirectories(Paths.get("output/"));43 OutputStream outputStream = Files.newOutputStream(new File("output/createPDFFromDOCXWithOptionsOutput.pdf").toPath());44 LOGGER.info("Saving asset at output/createPDFFromDOCXWithOptionsOutput.pdf");45 IOUtils.copy(streamAsset.getInputStream(), outputStream);46 outputStream.close();47 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {48 LOGGER.error("Exception encountered while executing operation", ex);49 }50 }51 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CreatePDFFromDocxWithOptions/4// dotnet run CreatePDFFromDocxWithOptions.csproj56namespace CreatePDFFromDocxWithOptions7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 // Creates an asset(s) from source file(s) and upload27 using Stream inputStream = File.OpenRead(@"createPdfInput.docx");28 IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.DOCX.GetMIMETypeValue());2930 // Create parameters for the job31 CreatePDFParams createPDFParams = CreatePDFParams.WordParamsBuilder()32 .WithDocumentLanguage(DocumentLanguage.EN_US)33 .Build();3435 // Creates a new job instance36 CreatePDFJob createPDFJob = new CreatePDFJob(asset).SetParams(createPDFParams);3738 // Submits the job and gets the job result39 String location = pdfServices.Submit(createPDFJob);40 PDFServicesResponse<CreatePDFResult> pdfServicesResponse =41 pdfServices.GetJobResult<CreatePDFResult>(location, typeof(CreatePDFResult));4243 // Get content from the resulting asset(s)44 IAsset resultAsset = pdfServicesResponse.Result.Asset;45 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4647 // Creating output streams and copying stream asset's content to it48 String outputFilePath = "/output/createPDFFromDOCXWithOptionsOutput.pdf";49 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();50 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);51 streamAsset.Stream.CopyTo(outputStream);52 outputStream.Close();53 }54 catch (ServiceUsageException ex)55 {56 log.Error("Exception encountered while executing operation", ex);57 }58 catch (ServiceApiException ex)59 {60 log.Error("Exception encountered while executing operation", ex);61 }62 catch (SDKException ex)63 {64 log.Error("Exception encountered while executing operation", ex);65 }66 catch (IOException ex)67 {68 log.Error("Exception encountered while executing operation", ex);69 }70 catch (Exception ex)71 {72 log.Error("Exception encountered while executing operation", ex);73 }74 }7576 static void ConfigureLogging()77 {78 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());79 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));80 }81 }82}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/createpdf/create-pdf-from-docx-with-options.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CreatePDFJob,10 CreatePDFParams,11 CreatePDFResult,12 DocumentLanguage,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("./createPDFInput.docx");33 const inputAsset = await pdfServices.upload({34 readStream,35 mimeType: MimeType.DOCX36 });3738 // Create parameters for the job39 const params = new CreatePDFParams({40 documentLanguage: DocumentLanguage.EN_US41 });4243 // Creates a new job instance44 const job = new CreatePDFJob({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: CreatePDFResult51 });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 result asset's content to it58 const outputFilePath = "./createPDFFromDOCXWithOptionsOutput.pdf";59 console.log(`Saving asset at ${outputFilePath}`);6061 const outputStream = fs.createWriteStream(outputFilePath);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# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/createpdf/create_pdf_from_docx_with_options.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class CreatePDFFromDOCXWithOptions:9 def __init__(self):1011 try:12 file = open('./createPDFInput.docx', 'rb')13 input_stream = file.read()14 file.close()1516 # Initial setup, create credentials instance17 credentials = ServicePrincipalCredentials(18 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),19 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')20 )2122 # Creates a PDF Services instance23 pdf_services = PDFServices(credentials=credentials)2425 # Creates an asset(s) from source file(s) and upload26 input_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.DOCX)2728 # Create parameters for the job29 create_pdf_params = CreatePDFFromWordParams(document_language=DocumentLanguage.EN_US)3031 # Creates a new job instance32 create_pdf_job = CreatePDFJob(input_asset=input_asset, create_pdf_params=create_pdf_params)3334 # Submit the job and gets the job result35 location = pdf_services.submit(create_pdf_job)36 pdf_services_response = pdf_services.get_job_result(location, CreatePDFResult)3738 # Get content from the resulting asset(s)39 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()40 stream_asset: StreamAsset = pdf_services.get_content(result_asset)4142 # Creates an output stream and copy stream asset's content to it43 output_file_path = 'output/CreatePDFFromDOCXWithOptions.pdf'44 with open(output_file_path, "wb") as file:45 file.write(stream_asset.get_input_stream())4647 except (ServiceApiException, ServiceUsageException, SdkException) as e:48 logging.exception(f'Exception encountered while executing operation: {e}')4950if __name__ == "__main__":51 CreatePDFFromDOCXWithOptions()
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Create-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/createpdf' \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 "documentLanguage": "en-US"11}'
Create a PDF from static HTML
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.
Please refer the API usage guide to understand how to use our APIs.
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.htmltopdf.StaticHTMLToPDF45public class StaticHTMLToPDF {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(StaticHTMLToPDF.class);910 public static void main(String[] args) {1112 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFFromStaticHtmlInput.zip").toPath())) {13 // Initial setup, create credentials instance14 Credentials credentials = new ServicePrincipalCredentials(15 System.getenv("PDF_SERVICES_CLIENT_ID"),16 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1718 // Creates a PDF Services instance19 PDFServices pdfServices = new PDFServices(credentials);2021 // Creates an asset(s) from source file(s) and upload22 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.ZIP.getMediaType());2324 // Create parameters for the job25 HTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();2627 // Creates a new job instance28 HTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(asset)29 .setParams(htmlToPDFParams);3031 // Submit the job and gets the job result32 String location = pdfServices.submit(htmLtoPDFJob);33 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);3435 // Get content from the resulting asset(s)36 Asset resultAsset = pdfServicesResponse.getResult().getAsset();37 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3839 // Creates an output stream and copy stream asset's content to it40 File.createDirectories(Paths.get("output/"));41 OutputStream outputStream = Files.newOutputStream(new File("output/staticHTMLToPDFOutput.pdf").toPath());42 LOGGER.info("Saving asset at output/staticHTMLToPDFOutput.pdf");43 IOUtils.copy(streamAsset.getInputStream(), outputStream);44 outputStream.close();45 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {46 LOGGER.error("Exception encountered while executing operation", ex);47 }48 }49 private static HTMLToPDFParams getHTMLToPDFParams() {50 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)51 PageLayout pageLayout = new PageLayout();52 pageLayout.setPageSize(8, 11.5);5354 return new HTMLToPDFParams.Builder()55 .includeHeaderFooter(true).withPageLayout(pageLayout)56 .build();57 }58}
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd StaticHTMLToPDF/4// dotnet run StaticHTMLToPDF.csproj56namespace StaticHTMLToPDF7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 // Creates an asset(s) from source file(s) and upload27 using Stream inputStream = File.OpenRead(@"createPDFFromStaticHtmlInput.zip");28 IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.ZIP.GetMIMETypeValue());2930 // Create parameters for the job31 HTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();3233 // Creates a new job instance34 HTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(asset).SetParams(htmlToPDFParams);3536 // Submits the job and gets the job result37 String location = pdfServices.Submit(htmlToPDFJob);38 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =39 pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));4041 // Get content from the resulting asset(s)42 IAsset resultAsset = pdfServicesResponse.Result.Asset;43 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4445 // Creating output streams and copying stream asset's content to it46 String outputFilePath = "/output/createPdfFromStaticHtmlOutput.pdf";47 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();48 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);49 streamAsset.Stream.CopyTo(outputStream);50 outputStream.Close();51 }52 catch (ServiceUsageException ex)53 {54 log.Error("Exception encountered while executing operation", ex);55 }56 catch (ServiceApiException ex)57 {58 log.Error("Exception encountered while executing operation", ex);59 }60 catch (SDKException ex)61 {62 log.Error("Exception encountered while executing operation", ex);63 }64 catch (IOException ex)65 {66 log.Error("Exception encountered while executing operation", ex);67 }68 catch (Exception ex)69 {70 log.Error("Exception encountered while executing operation", ex);71 }72 }7374 private static HTMLToPDFParams GetHTMLToPDFParams()75 {76 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).77 PageLayout pageLayout = new PageLayout();78 pageLayout.SetPageSize(8, 11.5);7980 // Set the desired HTML-to-PDF conversion options.81 HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder()82 .IncludeHeaderFooter(true)83 .WithPageLayout(pageLayout)84 .Build();85 return htmlToPDFParams;86 }878889 static void ConfigureLogging()90 {91 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());92 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));93 }94 }95}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/htmltopdf/static-html-to-pdf.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 PageLayout,10 HTMLToPDFParams,11 HTMLToPDFResult,12 HTMLToPDFJob,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("./createPDFFromStaticHtmlInput.zip");33 const inputAsset = await pdfServices.upload({34 readStream,35 mimeType: MimeType.ZIP36 });3738 // Create parameters for the job39 const params = getHTMLToPDFParams();4041 // Creates a new job instance42 const job = new HTMLToPDFJob({inputAsset, params});4344 // Submit the job and get the job result45 const pollingURL = await pdfServices.submit({job});46 const pdfServicesResponse = await pdfServices.getJobResult({47 pollingURL,48 resultType: HTMLToPDFResult49 });5051 // Get content from the resulting asset(s)52 const resultAsset = pdfServicesResponse.result.asset;53 const streamAsset = await pdfServices.getContent({asset: resultAsset});5455 // Creates an output stream and copy result asset's content to it56 const outputFilePath = "createPdfFromStaticHtmlOutput.pdf";57 console.log(`Saving asset at ${outputFilePath}`);5859 const outputStream = fs.createWriteStream(outputFilePath);60 streamAsset.readStream.pipe(outputStream);61 } catch (err) {62 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {63 console.log("Exception encountered while executing operation", err);64 } else {65 console.log("Exception encountered while executing operation", err);66 }67 } finally {68 readStream?.destroy();69 }70})();7172function getHTMLToPDFParams() {73 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)74 const pageLayout = new PageLayout({75 pageHeight: 11.5,76 pageWidth: 877 });7879 return new HTMLToPDFParams({80 pageLayout,81 includeHeaderFooter: true,82 });83}
Copied to your clipboard1# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/htmltopdf/static_html_to_pdf.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class StaticHTMLtoPDF:9 def __init__(self):10 try:11 file = open('./createPDFFromStaticHtmlInput.zip', 'rb')12 input_stream = file.read()13 file.close()1415 # Initial setup, create credentials instance16 credentials = ServicePrincipalCredentials(17 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),18 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')19 )2021 # Creates a PDF Services instance22 pdf_services = PDFServices(credentials=credentials)2324 # Creates an asset(s) from source file(s) and upload25 input_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.ZIP)2627 # Create parameters for the job28 html_to_pdf_params = self.get_html_to_pdf_params()2930 # Creates a new job instance31 html_to_pdf_job = HTMLtoPDFJob(input_asset=input_asset, html_to_pdf_params=html_to_pdf_params)3233 # Submit the job and gets the job result34 location = pdf_services.submit(html_to_pdf_job)35 pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)3637 # Get content from the resulting asset(s)38 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()39 stream_asset: StreamAsset = pdf_services.get_content(result_asset)4041 # Creates an output stream and copy stream asset's content to it42 output_file_path = 'output/StaticHTMLToPDF.pdf'43 with open(output_file_path, "wb") as file:44 file.write(stream_asset.get_input_stream())4546 except (ServiceApiException, ServiceUsageException, SdkException) as e:47 logging.exception(f'Exception encountered while executing operation: {e}')4849 @staticmethod50 def get_html_to_pdf_params() -> HTMLtoPDFParams:51 # Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)52 page_layout = PageLayout(page_height=11.5, page_width=8)53 return HTMLtoPDFParams(page_layout=page_layout, include_header_footer=True)5455if __name__ == "__main__":56 StaticHTMLtoPDF()57
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \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 "json": "{}",11 "includeHeaderFooter": true,12 "pageLayout": {13 "pageWidth": 11,14 "pageHeight": 8.515 }16}'
Create a PDF from static HTML with inline CSS
The sample below creates a PDF file from a static HTML file with inline CSS. The file must be local.
Please refer the API usage guide to understand how to use our APIs.
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.htmltopdf.HTMLWithInlineCSSToPDF45 public class HTMLWithInlineCSSToPDF {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(HTMLWithInlineCSSToPDF.class);910 public static void main(String[] args) {11 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFFromHTMLWithInlineCSSInput.html").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.HTML.getMediaType());2223 // Create parameters for the job24 HTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();2526 // Creates a new job instance27 HTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(asset)28 .setParams(htmlToPDFParams);2930 // Submit the job and gets the job result31 String location = pdfServices.submit(htmLtoPDFJob);32 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);3334 // Get content from the resulting asset(s)35 Asset resultAsset = pdfServicesResponse.getResult().getAsset();36 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3738 // Creates an output stream and copy stream asset's content to it39 File.createDirectories(Paths.get("output/"));40 OutputStream outputStream = Files.newOutputStream(new File("output/htmlWithInlineCSSToPDFOutput.pdf").toPath());41 LOGGER.info("Saving asset at output/htmlWithInlineCSSToPDFOutput.pdf");42 IOUtils.copy(streamAsset.getInputStream(), outputStream);43 outputStream.close();44 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {45 LOGGER.error("Exception encountered while executing operation", ex);46 }47 }4849 private static HTMLToPDFParams getHTMLToPDFParams() {50 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)51 PageLayout pageLayout = new PageLayout();52 pageLayout.setPageSize(20, 25);5354 return new HTMLToPDFParams.Builder()55 .includeHeaderFooter(true).withPageLayout(pageLayout)56 .build();57 }58}
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd HTMLWithInlineCSSToPDF/4// dotnet run HTMLWithInlineCSSToPDF.csproj56namespace HTMLWithInlineCSSToPDF7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 // Creates an asset(s) from source file(s) and upload27 using Stream inputStream = File.OpenRead(@"createPDFFromHTMLWithInlineCSSInput.html");28 IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.HTML.GetMIMETypeValue());2930 // Create parameters for the job31 HTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();3233 // Creates a new job instance34 HTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(asset).SetParams(htmlToPDFParams);3536 // Submits the job and gets the job result37 String location = pdfServices.Submit(htmlToPDFJob);38 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =39 pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));4041 // Get content from the resulting asset(s)42 IAsset resultAsset = pdfServicesResponse.Result.Asset;43 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4445 // Creating output streams and copying stream asset's content to it46 String outputFilePath = "/output/createPDFFromHTMLWithInlineCSSOutput.pdf";47 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();48 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);49 streamAsset.Stream.CopyTo(outputStream);50 outputStream.Close();51 }52 catch (ServiceUsageException ex)53 {54 log.Error("Exception encountered while executing operation", ex);55 }56 catch (ServiceApiException ex)57 {58 log.Error("Exception encountered while executing operation", ex);59 }60 catch (SDKException ex)61 {62 log.Error("Exception encountered while executing operation", ex);63 }64 catch (IOException ex)65 {66 log.Error("Exception encountered while executing operation", ex);67 }68 catch (Exception ex)69 {70 log.Error("Exception encountered while executing operation", ex);71 }72 }7374 private static HTMLToPDFParams GetHTMLToPDFParams()75 {76 // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation).77 PageLayout pageLayout = new PageLayout();78 pageLayout.SetPageSize(20, 25);7980 // Set the desired HTML-to-PDF conversion options.81 HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder()82 .IncludeHeaderFooter(true)83 .WithPageLayout(pageLayout)84 .Build();85 return htmlToPDFParams;86 }8788 static void ConfigureLogging()89 {90 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());91 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));92 }93 }94}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/htmltopdf/html-with-inline-css-to-pdf.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 HTMLToPDFJob,10 HTMLToPDFResult,11 PageLayout,12 HTMLToPDFParams,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("./createPDFFromHTMLWithInlineCSSInput.html");33 const inputAsset = await pdfServices.upload({34 readStream,35 mimeType: MimeType.HTML36 });3738 // Create parameters for the job39 const params = getHTMLToPDFParams();4041 // Creates a new job instance42 const job = new HTMLToPDFJob({inputAsset, params});4344 // Submit the job and get the job result45 const pollingURL = await pdfServices.submit({job});46 const pdfServicesResponse = await pdfServices.getJobResult({47 pollingURL,48 resultType: HTMLToPDFResult49 });5051 // Get content from the resulting asset(s)52 const resultAsset = pdfServicesResponse.result.asset;53 const streamAsset = await pdfServices.getContent({asset: resultAsset});5455 // Creates an output stream and copy result asset's content to it56 const outputFilePath = "./createPDFFromHTMLWithInlineCSSOutput.pdf";57 console.log(`Saving asset at ${outputFilePath}`);5859 const outputStream = fs.createWriteStream(outputFilePath);60 streamAsset.readStream.pipe(outputStream);61 } catch (err) {62 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {63 console.log("Exception encountered while executing operation", err);64 } else {65 console.log("Exception encountered while executing operation", err);66 }67 } finally {68 readStream?.destroy();69 }70})();7172function getHTMLToPDFParams() {73 // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation)74 const pageLayout = new PageLayout({75 pageHeight: 25,76 pageWidth: 2077 });7879 return new HTMLToPDFParams({80 pageLayout,81 includeHeaderFooter: true,82 });83}
Copied to your clipboard1# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/htmltopdf/html_with_inline_css_to_pdf.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class HTMLWithInlineCSSToPDF:9 def __init__(self):10 try:11 file = open('./createPDFFromHTMLWithInlineCSSInput.html', 'rb')12 input_stream = file.read()13 file.close()1415 # Initial setup, create credentials instance16 credentials = ServicePrincipalCredentials(17 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),18 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')19 )2021 # Creates a PDF Services instance22 pdf_services = PDFServices(credentials=credentials)2324 # Creates an asset(s) from source file(s) and upload25 input_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.HTML)2627 # Create parameters for the job28 html_to_pdf_params = self.get_html_to_pdf_params()2930 # Creates a new job instance31 html_to_pdf_job = HTMLtoPDFJob(input_asset=input_asset, html_to_pdf_params=html_to_pdf_params)3233 # Submit the job and gets the job result34 location = pdf_services.submit(html_to_pdf_job)35 pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)3637 # Get content from the resulting asset(s)38 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()39 stream_asset: StreamAsset = pdf_services.get_content(result_asset)4041 # Creates an output stream and copy stream asset's content to it42 output_file_path = 'output/HTMLWithInlineCSSToPDF.pdf'43 with open(output_file_path, "wb") as file:44 file.write(stream_asset.get_input_stream())4546 except (ServiceApiException, ServiceUsageException, SdkException) as e:47 logging.exception(f'Exception encountered while executing operation: {e}')4849 @staticmethod50 def get_html_to_pdf_params() -> HTMLtoPDFParams:51 # Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation)52 page_layout = PageLayout(page_height=25, page_width=20)53 return HTMLtoPDFParams(page_layout=page_layout, include_header_footer=True)545556if __name__ == "__main__":57 HTMLWithInlineCSSToPDF()58
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \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 "json": "{}",11 "includeHeaderFooter": true,12 "pageLayout": {13 "pageWidth": 11,14 "pageHeight": 8.515 }16}'
Create a PDF File From HTML specified via URL
The sample below creates a PDF file from a HTML file specified via URL.
Please refer the API usage guide to understand how to use our APIs.
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.htmltopdf.HTMLToPDFFromURL45 public class HTMLToPDFFromURL {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(HTMLToPDFFromURL.class);910 public static void main(String[] args) {1112 try {13 // Initial setup, create credentials instance14 Credentials credentials = new ServicePrincipalCredentials(15 System.getenv("PDF_SERVICES_CLIENT_ID"),16 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1718 // Creates a PDF Services instance19 PDFServices pdfServices = new PDFServices(credentials);2021 String htmlURL = "<HTML URL>";2223 // Create parameters for the job24 HTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();2526 // Creates a new job instance27 HTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(htmlURL)28 .setParams(htmlToPDFParams);2930 // Submit the job and gets the job result31 String location = pdfServices.submit(htmLtoPDFJob);32 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);3334 // Get content from the resulting asset(s)35 Asset resultAsset = pdfServicesResponse.getResult().getAsset();36 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3738 // Creates an output stream and copy stream asset's content to it39 File.createDirectories(Paths.get("output/"));40 OutputStream outputStream = Files.newOutputStream(new File("output/htmlToPDFFromURLOutput.pdf").toPath());41 LOGGER.info("Saving asset at output/htmlToPDFFromURLOutput.pdf");42 IOUtils.copy(streamAsset.getInputStream(), outputStream);43 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {44 LOGGER.error("Exception encountered while executing operation", ex);45 }46 }4748 private static HTMLToPDFParams getHTMLToPDFParams() {49 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)50 PageLayout pageLayout = new PageLayout();51 pageLayout.setPageSize(20, 25);5253 return new HTMLToPDFParams.Builder()54 .includeHeaderFooter(true).withPageLayout(pageLayout)55 .build();56 }57}
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd HTMLToPDFFromURL/4// dotnet run HTMLToPDFFromURL.csproj56namespace HTMLToPDFFromURL7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 String htmlURL = "https://www.adobe.io";2728 // Create parameters for the job29 HTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();3031 // Creates a new job instance32 HTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(htmlURL).SetParams(htmlToPDFParams);3334 // Submits the job and gets the job result35 String location = pdfServices.Submit(htmlToPDFJob);36 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =37 pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));3839 // Get content from the resulting asset(s)40 IAsset resultAsset = pdfServicesResponse.Result.Asset;41 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4243 // Creating output streams and copying stream asset's content to it44 String outputFilePath = "/output/createPdfFromURLOutput.pdf";45 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();46 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);47 streamAsset.Stream.CopyTo(outputStream);48 outputStream.Close();49 }50 catch (ServiceUsageException ex)51 {52 log.Error("Exception encountered while executing operation", ex);53 }54 catch (ServiceApiException ex)55 {56 log.Error("Exception encountered while executing operation", ex);57 }58 catch (SDKException ex)59 {60 log.Error("Exception encountered while executing operation", ex);61 }62 catch (IOException ex)63 {64 log.Error("Exception encountered while executing operation", ex);65 }66 catch (Exception ex)67 {68 log.Error("Exception encountered while executing operation", ex);69 }70 }7172 private static HTMLToPDFParams GetHTMLToPDFParams()73 {74 // Define the page layout, in this case an 20 x 25 inch page (effectively portrait orientation).75 PageLayout pageLayout = new PageLayout();76 pageLayout.SetPageSize(20, 25);7778 // Set the desired HTML-to-PDF conversion options.79 HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder()80 .IncludeHeaderFooter(true)81 .WithPageLayout(pageLayout)82 .Build();83 return htmlToPDFParams;84 }8586 static void ConfigureLogging()87 {88 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());89 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));90 }91 }92}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/htmltopdf/html-to-pdf-from-url.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 PageLayout,9 HTMLToPDFParams,10 HTMLToPDFResult,11 HTMLToPDFJob,12 SDKError,13 ServiceUsageError,14 ServiceApiError15} = require("@adobe/pdfservices-node-sdk");16const fs = require("fs");1718(async () => {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 const inputURL = "<HTML_URL>";3031 // Create parameters for the job32 const params = getHTMLToPDFParams();3334 // Creates a new job instance35 const job = new HTMLToPDFJob({inputURL, params});3637 // Submit the job and get the job result38 const pollingURL = await pdfServices.submit({job});39 const pdfServicesResponse = await pdfServices.getJobResult({40 pollingURL,41 resultType: HTMLToPDFResult42 });4344 // Get content from the resulting asset(s)45 const resultAsset = pdfServicesResponse.result.asset;46 const streamAsset = await pdfServices.getContent({asset: resultAsset});4748 // Creates an output stream and copy result asset's content to it49 const outputFilePath = "./createPDFFromHTMLURL.pdf";50 console.log(`Saving asset at ${outputFilePath}`);5152 const outputStream = fs.createWriteStream(outputFilePath);53 streamAsset.readStream.pipe(outputStream);54 } catch (err) {55 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {56 console.log("Exception encountered while executing operation", err);57 } else {58 console.log("Exception encountered while executing operation", err);59 }60 }61})();6263function getHTMLToPDFParams() {64 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)65 const pageLayout = new PageLayout({66 pageHeight: 11.5,67 pageWidth: 868 });6970 return new HTMLToPDFParams({71 includeHeaderFooter: true,72 pageLayout73 });74}
Copied to your clipboard1# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/htmltopdf/html_to_pdf_from_url.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class HTMLtoPDFFromURL:9 def __init__(self):10 try:11 # Initial setup, create credentials instance12 credentials = ServicePrincipalCredentials(13 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),14 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')15 )1617 # Creates a PDF Services instance18 pdf_services = PDFServices(credentials=credentials)1920 html_url = "<HTML URL>"2122 # Create parameters for the job23 html_to_pdf_params = self.get_html_to_pdf_params()2425 # Creates a new job instance26 html_to_pdf_job = HTMLtoPDFJob(input_url=html_url, html_to_pdf_params=html_to_pdf_params)2728 # Submit the job and gets the job result29 location = pdf_services.submit(html_to_pdf_job)30 pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)3132 # Get content from the resulting asset(s)33 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()34 stream_asset: StreamAsset = pdf_services.get_content(result_asset)3536 # Creates an output stream and copy stream asset's content to it37 output_file_path = 'output/HTMLToPDFFromURL.pdf'38 with open(output_file_path, "wb") as file:39 file.write(stream_asset.get_input_stream())4041 except (ServiceApiException, ServiceUsageException, SdkException) as e:42 logging.exception(f'Exception encountered while executing operation: {e}')4344 @staticmethod45 def get_html_to_pdf_params() -> HTMLtoPDFParams:46 # Define the page layout47 page_layout = PageLayout(page_height=25, page_width=20)48 return HTMLtoPDFParams(page_layout=page_layout, include_header_footer=True)495051if __name__ == "__main__":52 HTMLtoPDFFromURL()53
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \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 "inputUrl": "https://developer.adobe.com/document-services/homepage",10 "json": "{}",11 "includeHeaderFooter": true,12 "pageLayout": {13 "pageWidth": 11,14 "pageHeight": 8.515 }16}'
Create a PDF from dynamic HTML
To support workflows with dynamic data, DynamicHTMLToPDF
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 DynamicHTMLToPDF
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.
Please refer the API usage guide to understand how to use our APIs.
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.htmltopdf.DynamicHTMLToPDF4 public class DynamicHTMLToPDF {56 // Initialize the logger.7 private static final Logger LOGGER = LoggerFactory.getLogger(DynamicHTMLToPDF.class);89 public static void main(String[] args) {1011 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/createPDFFromDynamicHtmlInput.zip").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.ZIP.getMediaType());2223 // Create parameters for the job24 HTMLToPDFParams htmlToPDFParams = getHTMLToPDFParams();2526 // Creates a new job instance27 HTMLToPDFJob htmLtoPDFJob = new HTMLToPDFJob(asset)28 .setParams(htmlToPDFParams);2930 // Submit the job and gets the job result31 String location = pdfServices.submit(htmLtoPDFJob);32 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse = pdfServices.getJobResult(location, HTMLToPDFResult.class);3334 // Get content from the resulting asset(s)35 Asset resultAsset = pdfServicesResponse.getResult().getAsset();36 StreamAsset streamAsset = pdfServices.getContent(resultAsset);3738 // Creates an output stream and copy stream asset's content to it39 File.createDirectories(Paths.get("output/"));40 OutputStream outputStream = Files.newOutputStream(new File("output/dynamicHTMLToPDFOutput.pdf").toPath());41 LOGGER.info("Saving asset at output/dynamicHTMLToPDFOutput.pdf");42 IOUtils.copy(streamAsset.getInputStream(), outputStream);43 outputStream.close();44 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {45 LOGGER.error("Exception encountered while executing operation", ex);46 }47 }4849 private static HTMLToPDFParams getHTMLToPDFParams() {50 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)51 PageLayout pageLayout = new PageLayout();52 pageLayout.setPageSize(8, 11.5);5354 // Sets the dataToMerge field that needs to be populated in the HTML before its conversion55 JSONObject dataToMerge = new JSONObject();56 dataToMerge.put("title","Create, Convert PDFs and More!");57 dataToMerge.put("sub_title","Easily integrate PDF actions within your document workflows.");5859 return new HTMLToPDFParams.Builder()60 .includeHeaderFooter(true).withPageLayout(pageLayout).withDataToMerge(dataToMerge)61 .build();62 }63}
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd DynamicHTMLToPDF/4// dotnet run DynamicHTMLToPDF.csproj56namespace DynamicHTMLToPDF7{8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));1112 static void Main()13 {14 //Configure the logging15 ConfigureLogging();16 try17 {18 // Initial setup, create credentials instance19 ICredentials credentials = new ServicePrincipalCredentials(20 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID"),21 Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET"));2223 // Creates a PDF Services instance24 PDFServices pdfServices = new PDFServices(credentials);2526 // Creates an asset(s) from source file(s) and upload27 using Stream inputStream = File.OpenRead(@"createPDFFromDynamicHtmlInput.zip");28 IAsset asset = pdfServices.Upload(inputStream, PDFServicesMediaType.ZIP.GetMIMETypeValue());2930 // Create parameters for the job31 HTMLToPDFParams htmlToPDFParams = GetHTMLToPDFParams();3233 // Creates a new job instance34 HTMLToPDFJob htmlToPDFJob = new HTMLToPDFJob(asset).SetParams(htmlToPDFParams);3536 // Submits the job and gets the job result37 String location = pdfServices.Submit(htmlToPDFJob);38 PDFServicesResponse<HTMLToPDFResult> pdfServicesResponse =39 pdfServices.GetJobResult<HTMLToPDFResult>(location, typeof(HTMLToPDFResult));4041 // Get content from the resulting asset(s)42 IAsset resultAsset = pdfServicesResponse.Result.Asset;43 StreamAsset streamAsset = pdfServices.GetContent(resultAsset);4445 // Creating output streams and copying stream asset's content to it46 String outputFilePath = "/output/createPdfFromDynamicHtmlOutput.pdf";47 new FileInfo(Directory.GetCurrentDirectory() + outputFilePath).Directory.Create();48 Stream outputStream = File.OpenWrite(Directory.GetCurrentDirectory() + outputFilePath);49 streamAsset.Stream.CopyTo(outputStream);50 outputStream.Close();51 }52 catch (ServiceUsageException ex)53 {54 log.Error("Exception encountered while executing operation", ex);55 }56 catch (ServiceApiException ex)57 {58 log.Error("Exception encountered while executing operation", ex);59 }60 catch (SDKException ex)61 {62 log.Error("Exception encountered while executing operation", ex);63 }64 catch (IOException ex)65 {66 log.Error("Exception encountered while executing operation", ex);67 }68 catch (Exception ex)69 {70 log.Error("Exception encountered while executing operation", ex);71 }72 }7374 private static HTMLToPDFParams GetHTMLToPDFParams()75 {76 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation).77 PageLayout pageLayout = new PageLayout();78 pageLayout.SetPageSize(8, 11.5);7980 //Set the dataToMerge field that needs to be populated in the HTML before its conversion81 JObject dataToMerge = new JObject82 {83 { "title", "Create, Convert PDFs and More!" },84 { "sub_title", "Easily integrate PDF actions within your document workflows." }85 };8687 // Set the desired HTML-to-PDF conversion options.88 HTMLToPDFParams htmlToPDFParams = HTMLToPDFParams.HTMLToPDFParamsBuilder()89 .IncludeHeaderFooter(true)90 .WithPageLayout(pageLayout)91 .WithDataToMerge(dataToMerge)92 .Build();93 return htmlToPDFParams;94 }959697 static void ConfigureLogging()98 {99 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());100 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));101 }102 }103}
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/htmltopdf/dynamic-html-to-pdf.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 PageLayout,10 HTMLToPDFParams,11 HTMLToPDFResult,12 HTMLToPDFJob,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("./createPDFFromDynamicHtmlInput.zip");33 const inputAsset = await pdfServices.upload({34 readStream,35 mimeType: MimeType.ZIP36 });3738 // Create parameters for the job39 const params = getHTMLToPDFParams();4041 // Creates a new job instance42 const job = new HTMLToPDFJob({inputAsset, params});4344 // Submit the job and get the job result45 const pollingURL = await pdfServices.submit({job});46 const pdfServicesResponse = await pdfServices.getJobResult({47 pollingURL,48 resultType: HTMLToPDFResult49 });5051 // Get content from the resulting asset(s)52 const resultAsset = pdfServicesResponse.result.asset;53 const streamAsset = await pdfServices.getContent({asset: resultAsset});5455 // Creates an output stream and copy result asset's content to it56 const outputFilePath = "./createPDFFromDynamicHtmlOutput.pdf";57 console.log(`Saving asset at ${outputFilePath}`);5859 const outputStream = fs.createWriteStream(outputFilePath);60 streamAsset.readStream.pipe(outputStream);61 } catch (err) {62 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {63 console.log("Exception encountered while executing operation", err);64 } else {65 console.log("Exception encountered while executing operation", err);66 }67 } finally {68 readStream?.destroy();69 }70})();7172function getHTMLToPDFParams() {73 // Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)74 const pageLayout = new PageLayout({75 pageHeight: 11.5,76 pageWidth: 877 });7879 // Set the dataToMerge field that needs to be populated in the HTML before its conversion80 const dataToMerge = {81 "title": "Create, Convert PDFs and More!",82 "sub_title": "Easily integrate PDF actions within your document workflows."83 };8485 return new HTMLToPDFParams({86 pageLayout,87 dataToMerge,88 includeHeaderFooter: true,89 });90}
Copied to your clipboard1# Get the samples https://github.com/adobe/pdfservices-python-sdk-samples2# Run the sample:3# python src/htmltopdf/dynamic_html_to_pdf.py45# Initialize the logger6logging.basicConfig(level=logging.INFO)78class DynamicHTMLToPDF:9 def __init__(self):10 try:11 file = open('./createPDFFromDynamicHtmlInput.zip', 'rb')12 input_stream = file.read()13 file.close()1415 # Initial setup, create credentials instance16 credentials = ServicePrincipalCredentials(17 client_id=os.getenv('PDF_SERVICES_CLIENT_ID'),18 client_secret=os.getenv('PDF_SERVICES_CLIENT_SECRET')19 )2021 # Creates a PDF Services instance22 pdf_services = PDFServices(credentials=credentials)2324 # Creates an asset(s) from source file(s) and upload25 input_asset = pdf_services.upload(input_stream=input_stream, mime_type=PDFServicesMediaType.ZIP)2627 # Create parameters for the job28 html_to_pdf_params = self.get_html_to_pdf_params()2930 # Creates a new job instance31 html_to_pdf_job = HTMLtoPDFJob(input_asset=input_asset, html_to_pdf_params=html_to_pdf_params)3233 # Submit the job and gets the job result34 location = pdf_services.submit(html_to_pdf_job)35 pdf_services_response = pdf_services.get_job_result(location, HTMLtoPDFResult)3637 # Get content from the resulting asset(s)38 result_asset: CloudAsset = pdf_services_response.get_result().get_asset()39 stream_asset: StreamAsset = pdf_services.get_content(result_asset)4041 # Creates an output stream and copy stream asset's content to it42 output_file_path = 'output/DynamicHTMLToPDF.pdf'43 with open(output_file_path, "wb") as file:44 file.write(stream_asset.get_input_stream())4546 except (ServiceApiException, ServiceUsageException, SdkException) as e:47 logging.exception(f'Exception encountered while executing operation: {e}')4849 @staticmethod50 def get_html_to_pdf_params() -> HTMLtoPDFParams:51 # Define the page layout, in this case an 8 x 11.5 inch page (effectively portrait orientation)52 page_layout = PageLayout(page_height=11.5, page_width=8)53 # Sets the dataToMerge field that needs to be populated in the HTML before its conversion54 data_to_merge = {55 "title": "Create, Convert PDFs and More!",56 "sub_title": "Easily integrate PDF actions within your document workflows."57 }58 return HTMLtoPDFParams(page_layout=page_layout, json=json.dumps(data_to_merge))596061if __name__ == "__main__":62 DynamicHTMLToPDF()
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Html-To-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/htmltopdf' \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 "json": "{}",11 "includeHeaderFooter": true,12 "pageLayout": {13 "pageWidth": 11,14 "pageHeight": 8.515 }16}'