Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use dynamic Image to generate document by javascript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you the "javascript how to achieve the use of dynamic images to generate documents", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "javascript how to achieve the use of dynamic images to generate documents" this article.

One of the most attractive aspects of Adobe Document Generation is that it is very flexible. One aspect that API can really enhance the end result is the ability to include images in the template. In a typical use case, you will provide a still image defined in the data used with API. In this blog post, I will show a more advanced example-dynamic generation of images, in our case, dynamic generation of charts.

Basic knowledge

Before we move on to a more advanced demonstration, let's quickly introduce the basics. My colleagues have studied document generation and images very deeply, and you should check them, too. As described in our documentation, using dynamic images in Word templates requires several steps.

First, you add the image to the document. It doesn't matter which image you choose, it's just a placeholder, but you need to place it in the document as needed and make sure it's resized as expected. When you are finished, right-click the image and select the Edit alternate text option. In this alternative text, you provide JSON:

JSON:

{"location-path": "logo", "image-props": {"alt-text": "This is an alt-text for the image placeholder"}}

The location-path property must point to the key value used in the data containing the image data. For example, given the above location-path value, the data I use with API might look like this:

JSON:

{"name": "Some Random Name"

"age": 48, "logo": "

}

As shown in the example, the image data must be the Base64-encoded version of the image. If you've never seen it before, it looks a bit like this:

Data: image / png;base64, a very long list of characters

You can also use Word Add On to insert images for you. If the sample data you add contains a Base64 value, you can select it in the Images section of the Advanced tab.

So at this point, you can dynamically change the image in the final PDF or Word document. To do this, you need to swap out the value. Imagine that you have two options for the images in the document, a picture of a cat or a picture of a dog. In the Word template, you embed a placeholder image and link it to a value pet. Exe. Before sending your template and data to Document Generation API, you will use the correct values:

/ / data is the object you will pass to the API, it's got stuff alreadyif (thisPersonIsVeryCool) {data.pet = catBase64ImageData;} else {data.pet = dogBase64ImageData;} / / now call our API and pass the template and data

As you can see, depending on certain Boolean values, the data will have an encoded version of the cat or dog picture. Obviously one is better than the other, and of course I'm talking about cats. )

Although this is dynamic, we can go further.

Use dynamic Ima

For our scenario, we will create a document describing the number of cats in the shelter over the past six months. This data is returned from the internal reporting system and can be expressed as follows:

JSON:

{{"numberOfCats": [{"date": "11date", "amount": 210}, {"date": "12date", "amount": 354}, {"date": "1date 2021", "amount": 321}, {"date": "2x2021", "amount": 337}, {"date": "3x2021", "amount": 298}) {"date": "4amp 2021", "amount": 274}]}

The data consists of an array of values sorted from the oldest to the latest. Each item in the array has a date stamp and a numeric amount. Let's start with a template that contains a data table.

As far as it is concerned, it is beautiful and simple, and the output is clean. This is what the PDF looks like when it is generated:

It is "effective", but charts can make it easier to read. You can see trends more clearly over time and make better judgments based on the data provided. But how do we get dynamic charts in the Word template?

First, we need to find a service that can create charts at the same time, which is a critical part so that we can access the original image data of the chart. You see, there are about a thousand chart services for web developers. However, many of these chart libraries will render their libraries in a browser environment and when viewing the JavaScript of a particular web page. What we need is a service to create an actual image that can be requested and converted to Base64 through our server-side code.

For our demonstration, we will use QuickChart. QuickChart is a "service wrapper" around open source Chart.js packages. It basically takes the functionality of Chart.js and allows you to get a still image of the chart by making URL. For example, consider this URL:

Https://quickchart.io/chart?c={type:'bar',data:{labels:['Q1','Q2','Q3','Q4'], datasets: [{label:'Users', data: [50Jing 60je 70180]}, {label:'Revenue',data: [100200300400]}

You can see the URL parameters that define all aspects of the chart, including types (bar), labels, and actual data. You can see the results here:

Although URL is a bit complex (and maybe even more complex), it provides a solution to our problem. Given that we have data from the internal API, all we have to do is "rewrite" it in the URL for QuickChart.

I built that first. It takes my ordered data and uses it to create a URL on QuickChart that uses the line chart format and specifies a specific height and width. This is the function:

Function generateQuickChartURL (arr) {let labels = arr.map (d = > d.date); let data = arr.map (d = > d.amount); let url = `https://quickchart.io/chart?c={type:'line',data:{labels:${JSON.stringify(labels)},datasets:[{label:'Cats',data:${JSON.stringify(data)}}]}}&width=500&height=300`; return url;}

If I want to add more chart features, such as custom colors, I will modify them here. When I'm done, I added a placeholder image to the Word document and specified the size. Ben introduces this as Tip 6 in his wonderful article, Adobe document Generation API: working with Images.

One of the things I want to add to this suggestion is to switch Word to use pixel height and width for images instead of inches. Under Advanced in the Word settings, go to display and enable "Show pixels of the HTML feature":

When this feature is enabled, we can set a specific height and width (500 x 300) for the image and center it below the table.

The alternative text for the picture is as follows:

{"location-path": "image"}

As a reminder, this means that when we pass the data to the document to generate API, it expects the image key to contain the Base64 data of our image. What do we do? There is one more function!

JSON:

Async function urlToBase64 (url) {let resp = await fetch (url); let header = resp.headers.get ('content-type'); let body = await resp.arrayBuffer (); data = _' data:' + resp.headers.get ('content-type') +'; base64,' + Buffer.from (body) .toString ('base64'); return data;}

The urlToBase64 function fits exactly what it requires-to access the remote URL, get the data, and then convert it. Now that we have all the parts we need, let's look at a complete example:

Const PDFToolsSdk = require ('@ adobe/documentservices-pdftools-node-sdk'); const fs = require ('fs'); const fetch = require (' node-fetch'); (async () = > {let input ='. / catreport.docx'; let data = JSON.parse (fs.readFileSync ('. / cats.json')); let output ='. / catreport.pdf'; if (fs.existsSync (output) fs.unlinkSync (output); let url = generateQuickChartURL (data.numberOfCats)) / / get my image data.image = await urlToBase64 (url); await generateFromTemplate (input, data, output,'. / pdftools-api-credentials.json');}) (); / * I'm specifically designed to return a url for a line item chart based on my cat array-must include 'date' and' amount'*/function generateQuickChartURL (arr) {let labels = arr.map (d = > d.date); let data = arr.map (d = > d.amount) Let url = `https://quickchart.io/chart?c={type:'line',data:{labels:${JSON.stringify(labels)},datasets:[{label:'Cats',data:${JSON.stringify(data)}}]}}&width=500&height=300`; return url;} async function urlToBase64 (url) {let resp = await fetch (url); let header = resp.headers.get ('content-type'); let body = await resp.arrayBuffer () Data = _ 'data:' + resp.headers.get (' content-type') +'; base64,' + Buffer.from (body) .toString ('base64'); return data;} async function generateFromTemplate (template, data, dest, creds) {return new Promise ((resolve, reject) = > {/ / Initial setup, create credentials instance. Const credentials = PDFToolsSdk.Credentials. ServiceAccountCredentialsBuilder (). FromFile (creds). Build (); / / Create an ExecutionContext using credentials. Const executionContext = PDFToolsSdk.ExecutionContext.create (credentials); const documentMerge = PDFToolsSdk.DocumentMerge, documentMergeOptions = documentMerge.options; / / dest determines if Word or PDF let format; let destExt = dest.split ('.'). Pop (). ToLowerCase (); if (destExt = 'docx') format = documentMergeOptions.OutputFormat.DOCX; else if (destExt =' pdf') format = documentMergeOptions.OutputFormat.PDF Else throw ('Invalid destination extension') / / Create a new DocumentMerge options instance. Options = new documentMergeOptions.DocumentMergeOptions (data, format); / / Create a new operation instance using the options instance. Const documentMergeOperation = documentMerge.Operation.createNew (options); / / Set operation input document template from a source file. Const input = PDFToolsSdk.FileRef.createFromLocalFile (template); documentMergeOperation.setInput (input); / / Execute the operation and Save the result to the specified location. DocumentMergeOperation.execute (executionContext) .then (result = > result.saveAsFile (dest)) .then (() = > resolve (true)) .catch (err = > {if (err instanceof PDFToolsSdk.Error.ServiceApiError | | err instanceof PDFToolsSdk.Error.ServiceUsageError) {console.log ('Exception encountered while executing operation', err); reject (err)) } else {console.log ('Exception encountered while executing operation', err); reject (err);}

Starting at the top, I first specify variables for my input, data, and output. In this case, my cat data is a hard-coded JSON file, as shown above. Then I call generateQuickChatURL my data and assign the result to the image value. Finally, this will be passed to generateFromTemplate's utility function () to create PDF using our SDK.

The above is all the contents of the article "how to use javascript to generate documents with dynamic images". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report