Using Microsoft Word to create templates
jsreport supports the creation of templates from Microsoft Word files. Templates created using Word are able to generate reports in .docx format from the Template scripts.
-
To create a Microsoft Word template, open Word and paste the following contents to the document, using the handlebars syntax
{{<variable name>}}
to refer to your data fields:{{companyName}} Total raised amount: {{raisedAmount}} $
Format the text as desired, for example:
-
Save the document and drag it to the jsreport sidebar:
-
Create a new template named
sample-word
and set the recipe field todocx
: -
Click Next and select the existing
sample/sample
as the sample data: -
Click Next and select the
docx
file previously uploaded as the Office template: -
Click Run to output a
docx
file that contains the sample data:
Obtaining a template identifier
-
From the jsreport sidebar, click the sample-word template.
-
Click the Link button and then copy the last part of the link containing the identifier:
Calling jsreport from a template script "binary" perspective
-
Open the script created earlier.
-
Create a function that returns a binary object representation with a
templateId
property set to the identifier of the template and adata
property with the data to pass to the template:function buildDocxDownload({ computedData }) { // The identifier of the docx template const templateId = '1-pEMybJG'; const filename = `${computedData.companyName}.docx`; return { filename, templateId, data: computedData }; }
-
Add the function to a perspective with a name that identifies it:
context.registerPerspectives({ binary: { 'Docx report': { initialData: getInitialData, enrich: enrichRecordData, render: buildDocxDownload } } });
-
In the record preview, from Download as… , click the download docx button to download a
docx
with the contents from the template created previously in jsreport.
Calling jsreport using the Reporting API
To create reports outside of binary perspectives, you can use the Reporting API. For example, you can create a view
perspective with a custom button that creates a report:
function download() {
// The identifier of the docx template
const docxTemplateId = '1-pEMybJG';
sirenapi.Reporting.download(docxTemplateId, { value: 123 }, `report.docx`);
}
context.registerPerspectives({
view: {
'Create report button': {
render() {
return <button onClick={download}>Download report</button>
}
}
}
});
Next steps
For more information about template scripts, see template scripts.
For more information about scripting, see Scripting API documentation.