Socket
Socket
Sign inDemoInstall

docximager

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

docximager - npm Package Compare versions

Comparing version 0.0.2 to 0.0.4

ahs.docx

143

index.js

@@ -6,2 +6,3 @@

const JSZip = require('jszip');
const {parseString,Builder} = require('xml2js');

@@ -14,4 +15,4 @@ const uuid = require('uuid/v4');

const IMAGE_RETRIEVAL_TYPE = {
'URL' : 'url',
'LOCAL' : 'local',
'URL' : 'url',
'LOCAL' : 'local',
'B64' : 'b64'

@@ -33,2 +34,7 @@ };

/**
* Represents a DocxImager instance
* @constructor
*/
constructor(){

@@ -38,4 +44,9 @@ this.zip = null;

async load(docx_path){
return this.__loadDocx(docx_path).catch((e)=>{
/**
* Load the DocxImager instance with the docx.
* @param {String} path_or_buffer full path of the template docx, or the buffer
* @returns {Promise}
*/
async load(path_or_buffer){
return this.__loadDocx(path_or_buffer).catch((e)=>{
console.log(e);

@@ -45,7 +56,18 @@ });

async __loadDocx(docx_path){
async __loadDocx(path_or_buffer){
let zip = new JSZip();
this.zip = await zip.loadAsync(fs.readFileSync(docx_path));
let buffer = path_or_buffer;
if(!Buffer.isBuffer(path_or_buffer)){
buffer = fs.readFileSync(path_or_buffer);
}
this.zip = await zip.loadAsync(buffer);
}
/**
* Replaces the template image with the image obtained from the web url
* @param {String} image_uri web uri of the image
* @param {String} image_id id of the image in the docx
* @param {String} type type of the template image
* @returns {Promise}
*/
replaceWithImageURL(image_uri, image_id, type, cbk){

@@ -59,3 +81,4 @@ this.__validateDocx();

res.on('end', ()=>{
fs.writeFileSync('t1.'+type, );
fs.writeFileSync('t1.'+type, Buffer.concat(buffer));
//res.headers['content-type']
this.__replaceImage(Buffer.concat(buffer), image_id, type, cbk);

@@ -71,2 +94,9 @@ });

/**
* Replaces the template image with the image obtained from the local path
* @param {String} image_path full path of the image in the local system
* @param {String} image_id id of the image in the docx
* @param {String} type type of the template image
* @returns {Promise}
*/
replaceWithLocalImage(image_path, image_id, type, cbk){

@@ -78,2 +108,9 @@ this.__validateDocx();

/**
* Replaces the template image with the image obtained from the Base64 string
* @param {String} base64_string Base64 form of the image
* @param {String} image_id id of the image in the docx
* @param {String} type type of the template image
* @returns {Promise}
*/
replaceWithB64Image(base64_string, image_id, type, cbk){

@@ -86,4 +123,11 @@ this.__validateDocx();

//1. replace the image
let path = 'word/media/image'+image_id+'.'+type;
this.zip.file(path, buffer);
return new Promise((res, rej)=>{
try{
let path = 'word/media/image'+image_id+'.'+type;
this.zip.file(path, buffer);
res(true);
}catch(e){
rej();
}
});
}

@@ -122,7 +166,2 @@

// this.zip.generateNodeStream({streamFiles : true})
// .pipe(fs.createWriteStream('./merged.docx'))
// .on('finish', function(x){
// callback();
// });
// http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/

@@ -133,2 +172,7 @@ // https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/

/**
* Saves the transformed docx.
* @param {String} op_file_name Output file name with full path.
* @returns {Promise}
*/
async save(op_file_name){

@@ -327,14 +371,23 @@ if(!op_file_name){

let matches = content.match(/(<w:r>.*?insert_image.*?<\/w:r>)/g); //match all runs in p tags containing
//TODO iterate through all matches to match more than one tag
if(matches && matches[0]){
let tag = matches[0].match(/{{(.*?)}}/g)[0];
let splits = tag.split(' ');
let var_name = splits[1];
let width = splits[2];
let height = splits[3];
let obj = final_context[var_name];
let xml = DocxImager.__getImgXMLElement(obj[REL_ID], height, width);
if(matches && matches.length > 0){
for(let i = 0; i < matches.length; i++){
let xml = matches[i];
let regex = new RegExp(/{{(.*?)}}/g);
let tag = regex.exec(xml);
while(tag){
tag = tag[0];
let splits = tag.split(' ');
let var_name = splits[1];
let width = splits[2];
let height = splits[3];
content = content.replace(matches[0], xml);
let obj = final_context[var_name];
// let xml = DocxImager.__getImgXMLElement(obj[REL_ID], height, width);
xml = xml.replace(tag, '</w:t></w:r>'+DocxImager.__getImgXMLElement(obj[REL_ID], height, width)+'<w:r><w:t>');
tag = regex.exec(xml);
}
content = content.replace(matches[i], xml);
}
this.zip.file('word/document.xml', content);

@@ -387,4 +440,5 @@ res(true);

static __getImgXMLElement(rId, height, width){
let calc_height = 951710;//9525 * height;
let calc_width = 2855130;//9525 * width;
// width and height calculated assuming resolution as 96 dpi
let calc_height = /*(9525 * height)*/2857500;
let calc_width = /*(9525 * width)*/2857500;

@@ -506,40 +560,5 @@ // from web merge

//idml functi8on
async merge(idml_path, context, merged_file_path){
return new Promise(async (res, rej)=>{
let zip = await zip.loadAsync(fs.readFileSync(idml_path));
//get all the file names that are to be merged.
let des_map = await zip.file('designmap.xml').async('nodebuffer').toString();
let regex = new RegExp(/<idPkg:Story src="(.*?)".?\/>/gm);
let m = regex.exec(des_map);
let rels = [];
while(m != null){
rels.push(m[1]);
m = regex.exec(des_map);
}
if(rels && rels.length > 0){
for(let i = 0; i < rels.length; i++){
let content = await zip.file(rels[i]).async('nodebuffer').toString();
content = Handlebars.compile(content)(context);
zip.file(rels[i], content);
}
zip.generateNodeStream({streamFiles : true})
.pipe(fs.createWriteStream(merged_file_path))
.on('finish', function(x){
res(true);
});
}else{
rej(new Error('IDML file does not contain any story file'));
}
});
}
}
module.exports = DocxImager;
module.exports = {DocxImager};
{
"name": "docximager",
"version": "0.0.2",
"version": "0.0.4",
"description": "Tool to include images in docx.",

@@ -15,3 +15,3 @@ "author": "Varun2604",

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "node test.js"
},

@@ -18,0 +18,0 @@ "repository": {

@@ -11,7 +11,17 @@ # DOCX IMAGER

## What can Docx Imager do for you ?
## What can DocxImager do for you ?
With DocxImager, you can either replace a template image in your document, or insert an image
dynamically.
## How to insert your images dynamically ?
## What is replacing a template image ?
There are certain cases where you have to insert images to your docx document dynamically. You will need to place the dynamic image with certain formatting in your document to attain perfection.
Replacing template image functionality of DocxImager will come in handy at such places.
![replace_docx_image](https://i.ibb.co/s1nD5Fk/replace-image-Google-Docs-1.png)
#### How to replace your images dynamically ?
Just follow these simple steps:

@@ -34,5 +44,5 @@

4. Insert or replace your image
4. Replace your image
```
await docxImager.replaceWithImageURL('https://path_of_inage.com/image.png')
await docxImager.replaceWithImageURL('https://path_of_image.com/image.png', 1, 'png')
```

@@ -45,12 +55,39 @@

## Built With
## What is inserting image ?
* [Dropwizard](http://www.dropwizard.io/1.0.2/docs/) - The web framework used
* [Maven](https://maven.apache.org/) - Dependency Management
* [ROME](https://rometools.github.io/rome/) - Used to generate RSS Feeds
There are certain cases where you will need to just insert an image, and formatting does not exactly matter.
Such cases can be handeled with insert image functionality of DocxImager.
## Contributing
![insert_docx_image](https://i.ibb.co/V3jyG71/insert-image-Google-Docs.png)
Please read [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) for details on our code of conduct, and the process for submitting pull requests to us.
#### How to replace your images dynamically ?
Just follow these simple steps:
1. Include the package.
```
const DocxImager = require('DocxImager');
```
2. Create a new Instance of DocxImager.
```
let docxImager = new DocxImager();
```
3. Load your docx file.
```
await docxImager.load('./my.docx')
```
4. Insert your image
```
await docxImager.insertImage({'img1' : "https://path_of_image.com/image.png"})
```
5. Save your new document in the specified path.
```
await docxImager.save('./my_new_docx.docx');
```
## Authors

@@ -57,0 +94,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc