Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
docx
Advanced tools
Package description
The docx npm package is a powerful library for creating and manipulating Microsoft Word documents programmatically. It allows developers to generate .docx files with various elements such as text, images, tables, and more, directly from their JavaScript or TypeScript code.
Creating a Simple Document
This feature allows you to create a simple Word document with text. The code sample demonstrates how to create a document with a single paragraph containing both regular and formatted text.
const { Document, Packer, Paragraph, TextRun } = require('docx');
const fs = require('fs');
const doc = new Document({
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new TextRun('Hello World!'),
new TextRun({
text: ' This is bold and underlined text.',
bold: true,
underline: {}
})
]
})
]
}
]
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync('MyDocument.docx', buffer);
});
Adding Images
This feature allows you to add images to your Word document. The code sample demonstrates how to insert an image with specified dimensions into a document.
const { Document, Packer, Paragraph, ImageRun } = require('docx');
const fs = require('fs');
const doc = new Document({
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync('path/to/image.png'),
transformation: {
width: 100,
height: 100
}
})
]
})
]
}
]
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync('DocumentWithImage.docx', buffer);
});
Creating Tables
This feature allows you to create tables within your Word document. The code sample demonstrates how to create a table with two rows and two columns.
const { Document, Packer, Table, TableRow, TableCell, Paragraph } = require('docx');
const fs = require('fs');
const doc = new Document({
sections: [
{
properties: {},
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph('Cell 1')]
}),
new TableCell({
children: [new Paragraph('Cell 2')]
})
]
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph('Cell 3')]
}),
new TableCell({
children: [new Paragraph('Cell 4')]
})
]
})
]
})
]
}
]
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync('DocumentWithTable.docx', buffer);
});
officegen is another npm package that allows you to generate Microsoft Office documents, including Word, Excel, and PowerPoint files. Compared to docx, officegen offers a broader range of document types but may not have as many advanced features specifically for Word documents.
mammoth is a library focused on converting .docx documents to HTML and plain text. While it doesn't offer the same document creation capabilities as docx, it is useful for extracting content from existing Word documents.
pizzip is a low-level library for manipulating ZIP files, which can be used in conjunction with other libraries like docxtemplater to create and modify .docx files. It provides more control over the ZIP structure but requires more effort to use for document creation.
Readme
A tool to create Word Documents (.docx) with JS
$ npm install --save docx
var officeClippy = require('office-clippy');
// Used to create docx files
var docx = require('docx');
// Used to export the file into a .docx file
// var exporter = officeClippy.exporter;
var doc = new docx.Document();
var paragraph = new docx.Paragraph(),
var text = new docx.TextRun('Hello World');
paragraph.addText(text);
doc.addParagraph(paragraph);
You can add properties to the Word document by specifying options, for example:
var doc = new docx.Document({
creator: 'Dolan Miu',
description: 'My extremely interesting document',
title: 'My Document'
});
creator
description
title
subject
keywords
lastModifiedBy
revision
You can mix and match whatever properties you want, or provide no properties.
Every text block in OpenXML is organised in paragraphs. You can add more text to the paragraph by doing this:
var paragraph = new docx.Paragraph(),
var text = new docx.TextRun('Lorem Ipsum Foo Bar');
var paragraph = new docx.Paragraph();
paragraph.addText(text);
var paragraph = new docx.Paragraph("Short hand notation for adding text.");
After you create the paragraph, you must add the paragraph into the document
:
doc.addParagraph(paragraph);
Styles is a very important part of the look of a word document. At the moment, only headings and title is supported, but son the rest will be supported along with custom styles!
paragraph.heading1();
paragraph.heading2();
paragraph.heading3();
paragraph.heading4();
paragraph.heading5();
paragraph.title();
To change the text alignment of a paragraph, for center, left, right or justified:
paragraph.center();
paragraph.left();
paragraph.right();
paragraph.justified();
paragraph.heading1().center();
The above will create a heading 1
which is centered
.
To add a break in the page, simply add .thematicBreak()
on a paragraph:
var paragraph = new docx.Paragraph("Amazing Heading").heading1().thematicBreak();
The above example will create a heading with a page break directly under it.
To move to a new page (insert a page break), simply add .pageBreak()
on a paragraph:
var paragraph = new docx.Paragraph("Amazing Heading").heading1().pageBreak();
The above example will create a heading and start a new page immediately afterwards.
Paragraphs need text run
objects. To create text:
var text = new docx.TextRun("My awesome text here for my university dissertation");
paragraph.addText(text);
Text objects have methods inside which changes the way the text is displayed.
More info here
text.bold();
text.italic();
text.underline();
text.strike();
text.doubleStrike();
text.superScript();
text.subScript();
text.allCaps();
text.smallCaps();
Sometimes you would want to put text underneath another line of text but inside the same paragraph.
text.break();
What if you want to create a paragraph which is bold and italic?
paragraph.bold().italic();
To make a bullet point, simply make a paragraph into a bullet point:
var text = new docx.TextRun("Bullet points");
var paragraph = new docx.Paragraph(text).bullet();
var text2 = new docx.TextRun("Are awesome");
var paragraph2 = new docx.Paragraph(text2).bullet();
doc.addParagraph(paragraph);
doc.addParagraph(paragraph2);
This will produce:
If you do not know why tab stops are useful, then I recommend you do a bit of research. It enables side by side text which is nicely laid out without the need for tables, or constantly pressing space bar.
Note: At the moment, the unit of measurement for a tab stop is counter intuitive for a human. It is using OpenXMLs own measuring system. For example, 2268 roughly translates to 3cm. Therefore in the future, I may consider changing it to percentages or even cm.
Simply call the relevant methods on the paragraph listed below. Then just add a tab()
method call to a text object. Adding multiple tabStops
will mean you would have to chain tab()
until the desired tabStop
is selected. Example is shown below.
paragraph.leftTabStop(2268);
2268 is the distance from the left side.
paragraph.centerTabStp(2268);
2268 is the distance from the left side.
paragraph.rightTabStop(2268);
2268 is the distance from the left side.
paragraph.maxRightTabStop();
This will create a tab stop on the very edge of the right hand side. Handy for right aligning and left aligning text on the same line.
var paragraph = new docx.Paragraph().maxRightTabStop();
var leftText = new docx.TextRun("Hey everyone").bold();
var rightText = new docx.TextRun("11th November 2015").tab();
paragraph.addText(leftText);
paragraph.addText(rightText);
The example above will create a left aligned text, and a right aligned text on the same line. The laymans approach to this problem would be to either use text boxes or tables. YUK!
var paragraph = new docx.Paragraph();
paragraph.maxRightTabStop();
paragraph.leftTabStop(1000);
var text = new docx.TextRun("Second tab stop here I come!").tab().tab();
paragraph.addText(text);
The above shows the use of two tab stops, and how to select/use it.
I used the express exporter in my website. It's very useful, and is the preferred way if you want to make a downloadable file for a visitor. it is much better than generating a physical file on the server, and then passing a download link to that file.
Simply use the exporter, and pass in the necessary parameters:
var docx = require('docx');
var doc = new docx.Document();
var exporter = new docx.ExpressPacker(doc, res);
exporter.pack('My Document');
where res
is the response object obtained through the Express router. It is that simple. The file will begin downloading in the browser.
var docx = require('docx');
var doc = new docx.Document();
var exporter = new docx.LocalPacker(doc);
exporter.pack('My Document');
I used this library in my personal portfolio/CV website. Click generate CV for a demonstration. http://www.dolan.bio
var doc = new docx.Document();
var paragraph = new docx.Paragraph("Hello World");
var institutionText = new docx.TextRun("University College London").bold(),
var dateText = new docx.TextRun("5th Dec 2015").tab().bold();
paragraph.addText(institutionText);
paragraph.addText(dateText);
doc.addParagraph(paragraph);
var exporter = new docx.LocalPacker(doc);
exporter.pack('My Document');
Or:
var doc = new docx.Document();
var paragraph = new docx.Paragraph("Hello World");
var institutionText = new docx.TextRun("University College London").bold(),
var dateText = new docx.TextRun("5th Dec 2015").tab().bold();
paragraph.addText(institutionText);
paragraph.addText(dateText);
var exporter = new docx.ExpressPacker(doc, res);
exporter.pack('My Document');
Would produce:
University College London
5th Dec 2015
MIT © Dolan Miu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Easily generate .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
The npm package docx receives a total of 136,998 weekly downloads. As such, docx popularity was classified as popular.
We found that docx demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.