Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

officegen

Ziv-Barber84.5kMIT0.6.5

Office Open XML Generator using Node.js streams. Supporting Microsoft Office 2007 and later Word (docx), PowerPoint (pptx,ppsx) and Excell (xlsx). This module is for all frameworks and environments. No need for any commandline tool - this module is doing

officegen, office, microsoft, 2007, word, powerpoint, excel, docx, pptx, ppsx, xlsx, charts, Office Open XML, stream, generate, create, maker, generator, creator

readme

officegen

Creating Office Open XML files (Word, Excel and Powerpoint) for Microsoft Office 2007 and later without external tools, just pure Javascript. officegen should work on any environment that supports Node.js including Linux, OSX and Windows. officegen also supporting PowerPoint native charts objects with embedded data.

npm version dependencies devDependencies Build Status Join the chat at https://gitter.im/officegen/Lobby Backers on Open Collective Sponsors on Open Collective

Officegen logo Microsoft Office logo

Contributors:

This project exists thanks to all the people who contribute.

Getting Started:

Microsoft Powerpoint logo Microsoft Word logo Microsoft Excel logo

Officegen features overview:

  • Generating Microsoft PowerPoint document (.pptx file):
    • Create PowerPoint document with one or more slides.
    • Support both PPT and PPS.
    • Can create native charts.
    • Add text blocks.
    • Add images.
    • Can declare fonts, alignment, colors and background.
    • You can rotate objects.
    • Support shapes: Ellipse, Rectangle, Line, Arrows, etc.
    • Support hidden slides.
    • Support automatic fields like date, time and current slide number.
    • Support speaker notes.
    • Support slide layouts.
  • Generating Microsoft Word document (.docx file):
    • Create Word document.
    • You can add one or more paragraphs to the document and you can set the fonts, colors, alignment, etc.
    • You can add images.
    • Support header and footer.
    • Support bookmarks and hyperlinks.
  • Generating Microsoft Excel document (.xlsx file):
    • Create Excel document with one or more sheets. Supporting cells with either numbers or strings.

Installation:

$ npm install officegen

Microsoft PowerPoint basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty PowerPoint object:
let pptx = officegen('pptx')

// Let's add a title slide:

let slide = pptx.makeTitleSlide('Officegen', 'Example to a PowerPoint document')

// Pie chart slide example:

slide = pptx.makeNewSlide()
slide.name = 'Pie Chart slide'
slide.back = 'ffff00'
slide.addChart(
  {
    title: 'My production',
    renderType: 'pie',
    data:
    [
      {
        name: 'Oil',
        labels: ['Czech Republic', 'Ireland', 'Germany', 'Australia', 'Austria', 'UK', 'Belgium'],
        values: [301, 201, 165, 139, 128,  99, 60],
        colors: ['ff0000', '00ff00', '0000ff', 'ffff00', 'ff00ff', '00ffff', '000000']
      }
    ]
  }
)

// Let's generate the PowerPoint document into a file:

return new Promise((resolve, reject) => {
  let out = fs.createWriteStream('example.pptx')

  // This one catch only the officegen errors:
  pptx.on('error', function(err) {
    reject(err)
  })

  // Catch fs errors:
  out.on('error', function(err) {
    reject(err)
  })

  // End event after creating the PowerPoint file:
  out.on('close', function() {
    resolve()
  })

  // This async method is working like a pipe - it'll generate the pptx data and put it into the output stream:
  pptx.generate(out)
})

Since that officegen is using node.js events you can also create a document directly into a http respons stream:

const officegen = require('officegen')
const http = require('http')

/**
 * This is a simple web server that response with a PowerPoint document.
 */
http.createServer(function(req, res) {
  // We'll send a generated on the fly PowerPoint document without using files:
  if (req.url == '/') {
    // Create an empty PowerPoint object:
    let pptx = officegen('pptx')

    // Let's create a new slide:
    var slide = pptx.makeNewSlide()

    slide.name = 'Hello World'

    // Change the background color:
    slide.back = '000000'

    // Declare the default color to use on this slide:
    slide.color = 'ffffff'

    // Basic way to add text string:
    slide.addText('Created on the fly using a http server!')

    //
    // Let's generate the PowerPoint document directly into the response stream:
    //

    response.writeHead(200, {
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'Content-disposition': 'attachment filename=out.pptx'
    })

    // Content types related to Office documents:
    // .xlsx   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    // .xltx   application/vnd.openxmlformats-officedocument.spreadsheetml.template
    // .potx   application/vnd.openxmlformats-officedocument.presentationml.template
    // .ppsx   application/vnd.openxmlformats-officedocument.presentationml.slideshow
    // .pptx   application/vnd.openxmlformats-officedocument.presentationml.presentation
    // .sldx   application/vnd.openxmlformats-officedocument.presentationml.slide
    // .docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
    // .dotx   application/vnd.openxmlformats-officedocument.wordprocessingml.template
    // .xlam   application/vnd.ms-excel.addin.macroEnabled.12
    // .xlsb   application/vnd.ms-excel.sheet.binary.macroEnabled.12

    // This one catch only the officegen errors:
    pptx.on('error', function(err) {
      res.end(err)
    })

    // Catch response errors:
    res.on('error', function(err) {
      res.end(err)
    })

    // End event after sending the PowerPoint data:
    res.on('finish', function() {
      res.end()
    })

    // This async method is working like a pipe - it'll generate the pptx data and pass it directly into the output stream:
    pptx.generate(res)
  } else {
    res.end('Invalid Request!')
  } // Endif.
}).listen(3000)

Where to go from here?

Microsoft Word basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty Word object:
let docx = officegen('docx')

// Officegen calling this function after finishing to generate the docx document:
docx.on('finalize', function(written) {
  console.log(
    'Finish to create a Microsoft Word document.'
  )
})

// Officegen calling this function to report errors:
docx.on('error', function(err) {
  console.log(err)
})

// Create a new paragraph:
let pObj = docx.createP()

pObj.addText('Simple')
pObj.addText(' with color', { color: '000088' })
pObj.addText(' and back color.', { color: '00ffff', back: '000088' })

pObj = docx.createP()

pObj.addText('Since ')
pObj.addText('officegen 0.2.12', {
  back: '00ffff',
  shdType: 'pct12',
  shdColor: 'ff0000'
}) // Use pattern in the background.
pObj.addText(' you can do ')
pObj.addText('more cool ', { highlight: true }) // Highlight!
pObj.addText('stuff!', { highlight: 'darkGreen' }) // Different highlight color.

pObj = docx.createP()

pObj.addText('Even add ')
pObj.addText('external link', { link: 'https://github.com' })
pObj.addText('!')

pObj = docx.createP()

pObj.addText('Bold + underline', { bold: true, underline: true })

pObj = docx.createP({ align: 'center' })

pObj.addText('Center this text', {
  border: 'dotted',
  borderSize: 12,
  borderColor: '88CCFF'
})

pObj = docx.createP()
pObj.options.align = 'right'

pObj.addText('Align this text to the right.')

pObj = docx.createP()

pObj.addText('Those two lines are in the same paragraph,')
pObj.addLineBreak()
pObj.addText('but they are separated by a line break.')

docx.putPageBreak()

pObj = docx.createP()

pObj.addText('Fonts face only.', { font_face: 'Arial' })
pObj.addText(' Fonts face and size.', { font_face: 'Arial', font_size: 40 })

docx.putPageBreak()

pObj = docx.createP()

// We can even add images:
pObj.addImage('some-image.png')

// Let's generate the Word document into a file:

let out = fs.createWriteStream('example.docx')

out.on('error', function(err) {
  console.log(err)
})

// Async call to generate the output file:
docx.generate(out)

Where to go from here?

Microsoft Excel basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty Excel object:
let xlsx = officegen('xlsx')

// Officegen calling this function after finishing to generate the xlsx document:
xlsx.on('finalize', function(written) {
  console.log(
    'Finish to create a Microsoft Excel document.'
  )
})

// Officegen calling this function to report errors:
xlsx.on('error', function(err) {
  console.log(err)
})

let sheet = xlsx.makeNewSheet()
sheet.name = 'Officegen Excel'

// Add data using setCell:

sheet.setCell('E7', 42)
sheet.setCell('I1', -3)
sheet.setCell('I2', 3.141592653589)
sheet.setCell('G102', 'Hello World!')

// The direct option - two-dimensional array:

sheet.data[0] = []
sheet.data[0][0] = 1
sheet.data[1] = []
sheet.data[1][3] = 'some'
sheet.data[1][4] = 'data'
sheet.data[1][5] = 'goes'
sheet.data[1][6] = 'here'
sheet.data[2] = []
sheet.data[2][5] = 'more text'
sheet.data[2][6] = 900
sheet.data[6] = []
sheet.data[6][2] = 1972

// Let's generate the Excel document into a file:

let out = fs.createWriteStream('example.xlsx')

out.on('error', function(err) {
  console.log(err)
})

// Async call to generate the output file:
xlsx.generate(out)

Where to go from here?

Support:

Examples:

  • make_pptx.js - Example how to create PowerPoint 2007 presentation and save it into file.
  • make_xlsx.js - Example how to create Excel 2007 sheet and save it into file.
  • make_docx.js - Example how to create Word 2007 document and save it into file.
  • pptx_server.js - Example HTTP server that generating a PowerPoint file with your name without using files on the server side.

The official officegen Google Group:

officegen Google Group

The officegen Slack team:

Slack

Plans for the next release:

Trello

:coffee: The source code:

The project structure:

  • office/index.js - The main file.
  • office/lib/ - All the sources should be here.
    • basicgen.js - The generic engine to build many type of document files. This module providing the basicgen plugins interface for all the document generator. Any document generator MUST use this plugins API.
    • docplug.js - The document generator plugins interface - optional engine to create plugins API for each document generator.
    • msofficegen.js - A template basicgen plugin to extend the default basicgen module with the common Microsoft Office stuff. All the Microsoft Office based document generators in this project are using this template plugin.
    • genpptx.js - A document generator (basicgen plugin) to create a PPTX/PPSX document.
    • genxlsx.js - A document generator (basicgen plugin) to create a XLSX document.
    • gendocx.js - A document generator (basicgen plugin) to create a DOCX document.
    • pptxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Powerpoint based features.
    • docxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Word based features.
    • xlsxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Excel based features.
  • officegen/test/ - All the unit tests.
  • Gruntfile.js - Grunt scripts.

Code documentations:

To create the jsdoc documentation:

grunt jsdoc

External dependencies:

This project is using the following awesome libraries/utilities/services:

  • archiver
  • jszip
  • lodash
  • xmlbuilder

How to add new features:

The easiest way to add new features is by using the officegen internal plugins system.

Credit:

  • Created by Ziv Barber in 2013.
  • For creating zip streams i'm using 'archiver' by cmilhench, dbrockman, paulj originally inspired by Antoine van Wel's zipstream.

Contributors:

This project exists thanks to all the people who contribute.

Backers:

Thank you to all our backers! 🙏 [Become a backer]

Sponsors:

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

changelog

  • Version 0.6.5:
    • PPTX: Better fonts support in pptx: new options parameter for addText: pitch_family and charset.
  • Version 0.6.4:
    • Apple Pages compatibility and more options (thanks apsavin!).
    • Merge pull request #349 from isdh/patch-1.
    • More options for tables.
    • Extend encoding of text to also remove invalid XML characters.
    • Round cx and cy values for images in a:ext tag.
    • Packages updates.
    • DOCX: Feature request: ability to specify list level/depth.
    • Documentation: Fixed the addImage example for DOCX.
  • Version 0.6.3:
    • DOCX: addText() now supporting newline.
    • DOCX: Add paragraph spacing option.
    • DOCX: Fix image relationships for header/footer.
    • DOCX: columns support.
    • DOCX: Better units support for image size: '1in', '1em', '1cm', '1mm', '1pt', '1pc'.
    • Fixed the jpeg support.
  • Version 0.6.2:
    • PPTX workaround for using placeholders + custom sizes + custom fills: the disableFillSettings setting.
  • Version 0.6.1:
    • PPTX paragraph: more auto-fit options and more dots options.
    • PPTX shapes more options: you can now change y,x,cx and cy for ph shapes, title, desc, hidden, nvPrAttrCode and nvPrCode.
    • Better units support in pptx shapes: '1in', '1em', '1cm', '1mm', '1pt', '1pc'.
    • An option to change the view of a pptx document.
    • Fix: borderStyle does not work because of a typo.
    • More fonts support.
    • Some packages updates.
  • Version 0.6.0:
    • Option to change the pptx master slide layout (right now only one master slides supported).
    • Add 'indentFirstLine' attribute for paragraph, 'indent' attribute for tables (Merge pull request #302).
    • Add some docx features (Merge pull request #301).
    • Some packages updates.
  • Version 0.5.2:
    • Added a missing configuration option to the layout controls support in PowerPoint slides.
  • Version 0.5.1:
    • Allow using layout controls in PowerPoint slides using the ph option of addText.
  • Version 0.5.0:
    • Microsoft Word Document new features:
      • addText now have 2 new options: superscript and subscript (fixed issue #299).
    • Microsoft PowerPoint Document new features:
      • Custom layouts support.
      • Allow to insert direct xml code to a slide.
      • Allow using theme's colors in a slide object.
      • Documented how to change the theme.
      • More customizations to the slide's size (see the documentation).
    • Redesign the lib directory structure.
    • Some packages updates.
  • Version 0.4.8:
    • Upgraded jszip to the last version.
    • Some packages updates.
    • xmlbuilder 11.0.1 migration.
    • Start cleaning the documentation.
    • Remove missing sourcemap url (Merge pull request #295 from pdesantis/master).
    • Update docxtable.js.
  • Version 0.4.7:
    • Merge pull request #278 from aug2uag/master.
    • Merge pull request #255 from OmniCyberSecurity/master.
    • Merge pull request #262 from bkylerussell/indent.
    • Small fixed for the README.md.
    • Updated the supported node.js versions.
    • Merge pull request #270 from markau/markau-docxJSON-fixes.
    • Fix to example JSON key name, Fix to lib to ensure createListOfNumber.
    • Merge pull request #266 from pdesantis/master.
    • Merge pull request #259 from textioHQ/custom-style-support.
    • Add strikethrough option to docx addText function.
    • Account for paragraphs without specified options.
    • Round cx and cy values for images.
    • Merge pull request #249 from flaviolacer/patch-1.
    • Working Grid Width.
    • Merge pull request #238 from danishcake/missing_require_path.
    • Fix missing require('path').
    • Merge pull request #228 from msenevir/docs-set-slide-size-option.
    • update docs.
    • Merge pull request #227 from bainweb/master.
    • Remove unnecessary margin above tables.
    • Merge pull request #225 from salzhrani/rtl (RTL support).
  • Version 0.4.6:
    • Fixed issue with createByJson - Merge pull request #209 from goyney/master
  • Version 0.4.5:
    • Added dot bullets.
    • Option to append text to the content object of a slide based on the "text and content" layout.
    • Bug: Fix creating invalid pptx files when using styles.
    • Bug: Create invalid empty <cols> in excel files.
    • Bug: pptx addText ( null ) crashing officegen.
    • Bug: The title and content layout was the same as section header.
    • Bug: Selecting a layout not effecting the slide.
    • Add support for baseline font property (peakon).
    • Enable cell specific formatting in PowerPoint tables (jmetric).
  • Version 0.4.4:
    • Fix to support pptx speaker notes in Office 2013.
  • Version 0.4.3:
    • PowerPoint:
      • Improved speaker notes support.
      • Improved title layout API.
    • Excel:
      • New API to change the width of every cell instead of changing it directly. Warning! the internal format of sheet.width been changed!!!
  • Version 0.4.2:
    • PowerPoint:
      • Support for speaker notes.
      • Advanced way to set the side of the slides.
      • Allow you to make a slide from the title slide layout.
      • Now adding all the original Office layouts to the generated pptx document.
      • Table support fixes (japneet121).
    • Word:
      • Support for header and footer.
      • Support for bookmarks and hyperlinks.
    • Design and development:
      • Document type plugins system to easy adding new features.
  • Version 0.4.1:
    • Ability to make text hyperlinks in docx - Merge pull request #154 from embrialabs/master
    • Added support for bullets (they weren't working, and were just showing numbers) - Merge pull request #151 from njcaruso/master.
    • Fixed issue with _scaling private method - Merge pull request #150 from andrewBalekha/bugfix/chart-scaling-issue
    • pptx/bug: Multiline text using \n for splitting paragraphs would style properly only first paragraph - Merge pull request #140 from tomasztunik/master
    • Merge pull request #145 from arrowing/grid-span - Merge pull request #145 from arrowing/grid-span
  • Version 0.4.0:
    • For all Microsoft Office based documents:
      • Bug fix: Changing the document's properties from the document's settings didn't work.
      • You can now change also the 'categories' and 'status' in the document's properties.
      • 'creator' now changed to 'aurthor' (but you can still use also 'creator').
    • PowerPoint:
      • Charts now working again, using jszip so no need for any external tool.
    • Word:
      • Paragraph's text new options:
        • 'shdType' and 'shdColor' (used with 'back').
        • 'border', 'borderColor' and 'borderSize'.
        • 'highlight'.
      • All inside table borders (by cgarethc).
  • Version 0.2.11:
    • Allow user to set options in addImage when they use createByJson to generate docx (peizhuang) and also to change the image type (Ziv Barber).
    • Provide varying column sizes in Word tables (cgarethc).
    • Tables in Word can have differing column widths (cgarethc).
    • The cellColWidth option that is copied to the w:w on a w:tcW only works if the w:gridCol is a non-zero value. It is now possible to set table columns to different widths by using the cellColWidth on the columns for the first row, rather than having to set a constant column with in the table options.
    • PPTX Widescreen Centering Fix (funnelwise).
    • Uses pptWidth for obj cx and x calculations instead of hard coded numbers (EricR-FW).
    • Cleaned the code and more documentations and unit tests.
  • Version 0.2.10:
    • All the community patches since 0.2.9.
  • Version 0.2.9:
    • Italic support to docx files by Vlampreia.
    • Floating point support by Van Dyvk (pptx files).
  • Version 0.2.8:
    • Drop the support for node 0.8.x for now ("startpoint" not supporting node 0.8.x).
    • New generate engine.
    • Support 16:9 presentations (thanks redders6600).
    • Fix the required archiver version to 0.4.10.
  • Version 0.2.7:
    • PowerPoint:
      • Automatic updated fields support: date and time, slide number.
      • Bug fix: The text parameter of addText now supporting also numbers.
      • addText: simple array support then before (just pass list of strings to add as a text paragraph).
    • Word:
      • putPageBreak changed to addPageBreak but you can still use the old name.
      • Patch by Antoine Proulx: fix the font size converting.
      • Patch by Antoine Proulx: Proposition for the addition of a line break inside a paragraph.
  • Version 0.2.6:
    • PowerPoint:
      • Automatically support line breaks.
      • Fixed a bug when using effects (shadows).
    • Excell:
      • Patch by arnesten: Automatically support line breaks if used in cell and also set appropriate row height depending on the number of line breaks.
  • Version 0.2.5:
    • Internal design changes that should not effect current implementations. To support future features.
    • Bugs:
      • Small typo which makes it crash. oobjOptions should be objOptions on line 464 in genpptx.js (thanks Stefan Van Dyck!).
  • Version 0.2.4:
    • PowerPoint:
      • Body properties like autoFit and margin now supported for text objects (thanks Stefan Van Dyck!).
      • You can pass now 0 to either cx or cy (good when drawing either horizontal or vertical lines).
    • Plugins developers:
      • You can now generate also tar and gzip based documents (or archive files).
      • You can generate your document resources using template engines (like jade, ejs, haml*, CoffeeKup, etc).
  • Version 0.2.3:
    • PowerPoint:
      • You can now either read or change the options of a parahraph object after creating it.
      • You can add shadow effects (both outher and inner).
  • Version 0.2.2:
    • Word:
      • You can now put images inside your document.
    • General features:
      • You can now pass callbacks to generate() instead of using node events.
    • Bugs / Optimization:
      • If you add the same image only one copy of it will be saved.
      • Missing requirement after the split of the code in version 0.2.x (thanks Seth Pollack!)
      • Fix the bug when you put number as a string for properties like y, x, cy and cx.
      • Generating invalid strings for MS-Office document properties.
      • Better shared string support in Excel (thanks vivocha!).
  • Version 0.2.0:
    • Huge design change from 'quick patch' based code to real design with much better API while still supporting also the old API.
    • Bugs:
      • You can now listen on error events.
      • Missing files in the relationships list made the Excel files unreadable to the Numbers application on the Mac (lmalheiro).
      • Minor bug fixes on the examples and the documentation.
  • Version 0.1.11:
    • PowerPoint:
      • Transparent level for solid color.
      • Rotate any object.
      • Flip vertical now working for any kind of object.
      • Line width.
    • Bugs:
      • Invalid PPTX file when adding more then one image of the same type.
  • Version 0.1.10:
    • PowerPoint:
      • Supporting more image types.
      • Supporting hidden slides.
      • Allow changing the indent for text.
    • Bug: All the text messages for all type of documents can now have '<', '>', etc.
  • Version 0.1.9:
    • Bug: Fix the invalid package.json main file.
    • PowerPoint: Allow adding shapes.
  • Version 0.1.8:
    • PowerPoint: Allow adding images (png only).
  • Version 0.1.7:
    • Excel 2007: addCell.
    • Many internal changes that are not effecting the user API.
  • Version 0.1.6:
    • Excel 2007: finished supporting shared strings.
    • Excel 2007: The interface been changed.
    • A lot of changes in the design of this module.
  • Version 0.1.5:
    • Word 2007 basic API now working.
  • Version 0.1.4:
    • WARNING: The addText function for PowerPoint been changed since version 0.1.3.
    • Many new features for PowerPoint.
    • Minor bug fixes.
  • Version 0.1.3:
    • Can generate also ppsx files.
    • Minor bug fixes.
  • Version 0.1.2:
    • HTTP server demo.
    • Can generate very limited Excel file.
    • You can change the background color of slides.
    • Minor bug fixes.