Gathering detailed insights and metrics for docxtemplater-image-hyperlink-module-free
Gathering detailed insights and metrics for docxtemplater-image-hyperlink-module-free
Gathering detailed insights and metrics for docxtemplater-image-hyperlink-module-free
Gathering detailed insights and metrics for docxtemplater-image-hyperlink-module-free
Open Source Image Module for docxtemplater with Hyperlink support
npm install docxtemplater-image-hyperlink-module-free
Typescript
Module System
Node Version
NPM Version
71.6
Supply Chain
98.4
Quality
75.2
Maintenance
25
Vulnerability
80.9
License
JavaScript (100%)
Total Downloads
1,019
Last Day
1
Last Week
7
Last Month
9
Last Year
298
1 Stars
177 Commits
1 Forks
1 Branches
1 Contributors
Latest Version
1.0.2
Package Id
docxtemplater-image-hyperlink-module-free@1.0.2
Unpacked Size
81.02 kB
Size
24.26 kB
File Count
13
NPM Version
8.19.3
Node Version
16.19.0
Publised On
08 Feb 2023
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
0%
7
Compared to previous week
Last month
50%
9
Compared to previous month
Last year
-58.7%
298
Compared to previous year
This repository holds a maintained version of docxtemplater image module.
This package is open source. There is also a paid version maintained by docxtemplater author.
Note this version is compatible with docxtemplater 3.x.
You first need to install docxtemplater by following its installation guide.
For Node.js install this package:
1npm i docxtemplater-image-hyperlink-module-free
Builds are located in build/node
directory.
To build your own just run
1npm run compile
Builds are located in build/browser
directory.
Alternatively, you can create your own build from the sources:
1npm run compile 2npm run browserify 3npm run uglify
Assuming your docx or pptx template contains only the text {%image}
:
1// Node.js example 2const PizZip = require("pizzip"); 3const Docxtemplater = require("docxtemplater"); 4const ImageModule = require('docxtemplater-image-hyperlink-module-free'); 5 6const fs = require("fs"); 7const path = require("path"); 8 9// Below the options that will be passed to ImageModule instance 10const imageOpts = { 11 centered: false, // Set to true to always center images 12 fileType: "docx", // Or pptx 13 // Pass your image loader 14 getImage: function (tagValue, tagName) { 15 return fs.readFileSync(tagValue); 16 }, 17 // Pass the function that returns image size 18 getSize: function (img, tagValue, tagName) { 19 // It also is possible to return a size in centimeters, like this : return [ "2cm", "3cm" ]; 20 return [150, 150]; 21 }, 22 // Pass the function that returns image properties 23 getProps: function(tagValue, tagName) { 24 // Filter by tagName, replace with yours 25 // For instance, tagName is 'image' 26 if (tagName === 'image') { 27 return { 28 link: 'https://domain.example', 29 }; 30 } 31 /* 32 * If you don't want to change the props 33 * for a given tagName, just return null 34 */ 35 return null; 36 } 37}; 38 39// Load the docx file as binary content 40const content = fs.readFileSync( 41 path.resolve(__dirname, "input.docx"), 42 "binary" 43); 44 45const zip = new PizZip(content); 46const doc = new Docxtemplater(zip, { 47 modules: [new ImageModule(imageOpts)], 48}); 49doc.render({ image: "examples/image.png" }); 50 51const buffer = doc.getZip().generate({ 52 type: "nodebuffer", 53 compression: "DEFLATE", 54}); 55 56fs.writeFile("test.docx", buffer);
Some notes regarding templates:
{%image}
must be in a dedicated paragraph.{%image}
must be in a dedicated text cell.In the browser, this shows how to get the image asynchronously :
1<html> 2 <script src="node_modules/docxtemplater/build/docxtemplater.js"></script> 3 <script src="node_modules/pizzip/dist/pizzip.js"></script> 4 <script src="node_modules/pizzip/vendor/FileSaver.js"></script> 5 <script src="node_modules/pizzip/dist/pizzip-utils.js"></script> 6 <script src="build/browser/imagemodule.js"></script> 7 <script> 8 docxType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 9 PizZipUtils.getBinaryContent( 10 "examples/image-example.docx", 11 function (error, content) { 12 if (error) { 13 console.error(error); 14 return; 15 } 16 const imageOpts = { 17 centered: false, 18 getImage: function (tagValue, tagName) { 19 return new Promise(function ( 20 resolve, 21 reject 22 ) { 23 PizZipUtils.getBinaryContent( 24 tagValue, 25 function (error, content) { 26 if (error) { 27 return reject(error); 28 } 29 return resolve(content); 30 } 31 ); 32 }); 33 }, 34 getSize: function (img, tagValue, tagName) { 35 // FOR FIXED SIZE IMAGE : 36 return [150, 150]; 37 38 // FOR IMAGE COMING FROM A URL (IF TAGVALUE IS AN ADDRESS) : 39 // To use this feature, you have to be using docxtemplater async 40 // (if you are calling render(), you are not using async). 41 return new Promise(function ( 42 resolve, 43 reject 44 ) { 45 const image = new Image(); 46 image.src = url; 47 image.onload = function () { 48 resolve([ 49 image.width, 50 image.height, 51 ]); 52 }; 53 image.onerror = function (e) { 54 console.log( 55 "img, tagValue, tagName : ", 56 img, 57 tagValue, 58 tagName 59 ); 60 alert( 61 "An error occured while loading " + 62 tagValue 63 ); 64 reject(e); 65 }; 66 }); 67 }, 68 getProps: function(tagValue, tagName) { 69 // Filter by tagName, replace with yours 70 // For instance, tagName is 'image' 71 if (tagName === 'image') { 72 return { 73 link: 'https://domain.example', 74 }; 75 } 76 /* 77 * If you don't want to change the props 78 * for a given tagName, just return null 79 */ 80 return null; 81 } 82 }; 83 84 const zip = new PizZip(content); 85 const doc = new docxtemplater(zip, { 86 modules: [new ImageModule(imageOpts)], 87 }); 88 89 doc.renderAsync({ 90 image: "examples/image.png", 91 }).then(function () { 92 const out = doc.getZip().generate({ 93 type: "blob", 94 mimeType: docxType, 95 }); 96 saveAs(out, "generated.docx"); 97 }); 98 } 99 ); 100 </script> 101 102</html>
You can center all images by setting the global switch to true imageOpts.centered = true
.
If you would like to choose which images should be centered one by one:
imageOpts.centered = false
.{%image}
for images that shouldn't be centered.{%%image}
for images that you would like to see centered.In pptx generated documents, images are centered vertically and horizontally relative to the parent cell.
It is possible to get images asynchronously by returning a Promise in the getImage
function and use the docxtemplater async api : http://docxtemplater.readthedocs.io/en/latest/async.html
Here is an example in node that allows you to retrieve values from an URL and use a fixed width, and keep the aspect ratio.
1const fs = require("fs"); 2const Docxtemplater = require("docxtemplater"); 3const https = require("https"); 4const http = require("http"); 5const Stream = require("stream").Transform; 6const ImageModule = require("docxtemplater-image-module"); 7const PizZip = require("pizzip"); 8 9const content = fs.readFileSync("demo_template.docx"); 10 11const data = { image: "https://docxtemplater.com/xt-pro.png" }; 12 13const imageOpts = { 14 getImage: function (tagValue, tagName) { 15 console.log(tagValue, tagName); 16 const base64Value = base64Parser(tagValue); 17 if (base64Value) { 18 return base64Value; 19 } 20 // tagValue is "https://docxtemplater.com/xt-pro-white.png" 21 // tagName is "image" 22 return new Promise(function (resolve, reject) { 23 getHttpData(tagValue, function (err, data) { 24 if (err) { 25 return reject(err); 26 } 27 resolve(data); 28 }); 29 }); 30 }, 31 getSize: function (img, tagValue, tagName) { 32 console.log(tagValue, tagName); 33 // img is the value that was returned by getImage 34 // This is to force the width to 600px, but keep the same aspect ratio 35 const sizeOf = require("image-size"); 36 const sizeObj = sizeOf(img); 37 console.log(sizeObj); 38 const forceWidth = 600; 39 const ratio = forceWidth / sizeObj.width; 40 return [ 41 forceWidth, 42 // calculate height taking into account aspect ratio 43 Math.round(sizeObj.height * ratio), 44 ]; 45 }, 46 getProps: function(tagValue, tagName) { 47 // Filter by tagName, replace with yours 48 // For instance, tagName is 'image' 49 if (tagName === 'image') { 50 return { 51 link: 'https://domain.example', 52 }; 53 } 54 /* 55 * If you don't want to change the props 56 * for a given tagName, just return null 57 */ 58 return null; 59 } 60}; 61 62const zip = new PizZip(content); 63const doc = new Docxtemplater(zip, { 64 modules: [new ImageModule(imageOpts)], 65}); 66 67doc.renderAsync(data) 68 .then(function () { 69 const buffer = doc.getZip().generate({ 70 type: "nodebuffer", 71 compression: "DEFLATE", 72 }); 73 74 fs.writeFileSync("test.docx", buffer); 75 console.log("rendered"); 76 }) 77 .catch(function (error) { 78 console.log("An error occured", error); 79 }); 80 81// Returns a Promise<Buffer> of the image 82function getHttpData(url, callback) { 83 (url.substr(0, 5) === "https" ? https : http) 84 .request(url, function (response) { 85 if (response.statusCode !== 200) { 86 return callback( 87 new Error( 88 `Request to ${url} failed, status code: ${response.statusCode}` 89 ) 90 ); 91 } 92 93 const data = new Stream(); 94 response.on("data", function (chunk) { 95 data.push(chunk); 96 }); 97 response.on("end", function () { 98 callback(null, data.read()); 99 }); 100 response.on("error", function (e) { 101 callback(e); 102 }); 103 }) 104 .end(); 105}
You can have customizable image loader using the template's placeholder name.
1const imageOpts = {
2 getImage: function (tagValue, tagName) {
3 if (tagName === "logo")
4 return fs.readFileSync(
5 __dirname + "/logos/" + tagValue
6 );
7
8 return fs.readFileSync(
9 __dirname + "/images/" + tagValue
10 );
11 },
12};
The same thing can be used to customize image size.
1const imageOpts = { 2 getSize: function (img, tagValue, tagName) { 3 if (tagName === "logo") return [100, 100]; 4 5 return [300, 300]; 6 }, 7};
And image properties.
1const imageOpts = { 2 getProps: function (img, tagValue, tagName) { 3 if (tagName === "logo") return { 4 link: "https://mycompany.com"; 5 }; 6 7 return { 8 link: "https://defaultlink.com"; 9 } 10 }, 11};
You can use base64 images with the following code:
1function base64DataURLToArrayBuffer(dataURL) { 2 const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/; 3 if (!base64Regex.test(dataURL)) { 4 return false; 5 } 6 const stringBase64 = dataURL.replace(base64Regex, ""); 7 let binaryString; 8 if (typeof window !== "undefined") { 9 binaryString = window.atob(stringBase64); 10 } else { 11 binaryString = new Buffer(stringBase64, "base64").toString("binary"); 12 } 13 const len = binaryString.length; 14 const bytes = new Uint8Array(len); 15 for (let i = 0; i < len; i++) { 16 const ascii = binaryString.charCodeAt(i); 17 bytes[i] = ascii; 18 } 19 return bytes.buffer; 20} 21const imageOpts = { 22 getImage(tag) { 23 return base64DataURLToArrayBuffer(tag); 24 }, 25 getSize() { 26 return [100, 100]; 27 }, 28 getProps() { 29 return { 30 link: "https://domain.example" 31 }; 32 } 33}; 34doc.attachModule(new ImageModule(imageOpts));
No vulnerabilities found.
No security vulnerabilities found.