Nodejs word to pdf

I have method on Node js Return Word document , i want pass parameter called file type to convert this word document
to PDF.

the output from buf var it file like below
PK
! ߤ�l [Content_Types].xml<?xml version="1.0" encoding="UTF-8" standalone="yes"?>...

How can convert this word document to pdf ?

router.get("/hello", function(request, response, next,fileType) {

  var zip = new JSZip(
    "UEsDBBQABgAIAAAAIQDfpNJsWgEAACAFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0lMtuwjAQRfeV+g+Rt1Vi6KKqKgKLPpYtUukHGHsCVv2Sx7z+vhMCUVUBkQpsIiUz994zVsaD0dqabAkRtXcl6xc9loGTXmk3K9nX5C1/ZBkm4ZQ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hAsAAHdvcmQvdGhlbWUvdGhlbWUxLnhtbFBLAQItABQABgAIAAAAIQAylTWVzwMAAAMKAAARAAAAAAAAAAAAAAAAANoRAAB3b3JkL3NldHRpbmdzLnhtbFBLAQItABQABgAIAAAAIQDtVkksZAIAAFMIAAASAAAAAAAAAAAAAAAAANgVAAB3b3JkL2ZvbnRUYWJsZS54bWxQSwECLQAUAAYACAAAACEAW239kwkBAADxAQAAFAAAAAAAAAAAAAAAAABsGAAAd29yZC93ZWJTZXR0aW5ncy54bWxQSwECLQAUAAYACAAAACEAAR0f33EBAADHAgAAEAAAAAAAAAAAAAAAAACnGQAAZG9jUHJvcHMvYXBwLnhtbFBLAQItABQABgAIAAAAIQDWVAxaegEAAAMDAAARAAAAAAAAAAAAAAAAAE4cAABkb2NQcm9wcy9jb3JlLnhtbFBLAQItABQABgAIAAAAIQALRmoQGwsAAARwAAAPAAAAAAAAAAAAAAAAAP8eAAB3b3JkL3N0eWxlcy54bWxQSwUGAAAAAAsACwDBAgAARyoAAAAA",
    { base64: true }
  );
  var doc = new Docxtemplater();

  doc.loadZip(zip);
  //set the templateVariables
  doc.setData({});

  try {
    // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
    doc.render();
    var buf = doc.getZip().generate({ type: "nodebuffer" });


    if(fileType=='docx'){
    response.writeHead(200, {
      "Content-Disposition": "attachment;filename=" + "template.docx",
      "Content-Type":
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    });
    }else if(fileType=='pdf'){

        //here should convert 
    }

    response.end(buf);
  } catch (error) {
    var e = {
      message: error.message,
      name: error.name,
      stack: error.stack,
      properties: error.properties
    };
    console.log(JSON.stringify({ error: e }));
    // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
    throw error;
  }
});

Express or Express.js is described as a flexible framework for building web apps and APIs, as well as the de facto standard server framework for Node.js. Leveraging Express and Node.js enables devs to add powerful back-end functionalities to their web and mobile applications, and create feature-rich user experiences. Check out the following video for more info on building a PDF app with Express and Node.js.

In this blog, we show you how to create your very own file server using Node.js, Express, and the Apryse SDK Node.js PDF Library. Our sample project not only serves static files; it will also perform advanced document processing operations like file conversion from DOCX, PPTX, or XLSX to PDF (MS Office software or licenses not required), thumbnail generation, and more.

Check out this ready-to-go project sample on our Github. And if you do not have Node.js installed yet, download and install it from here.

Set Up Your Node.js Project

To get started, create a new folder, open it inside your terminal, and type the following:

$ npm init

The above command will walk you through the creation of a new project. The entry point, the file from which execution starts, is index.js by default.

Next, let’s install some project dependencies. The first one is Express.js, a lightweight web framework for Node.js.

$ npm install express --save

The second one is the Apryse SDK. This will facilitate file conversion, splitting of documents, thumbnail generation, optimization of PDFs, OCR, and many other document processing actions.

$ npm install @pdftron/pdfnet-node --save

The third one is nodemon, which enables hot reloading of the server while we develop and make changes to our code.

$ npm install nodemon --save

Once we are done with dependencies, we will get our package.json in order. Add the following under scripts.

"scripts": {
    "start": "nodemon index.js"
  },
  

The next step is to establish our entry point. Create a new file called index.js on the same level as package.json.

Afterwards, run npm start.

Create a Simple Express.js Server

Now we will create a simple Express server inside of index.js.

const express = require('express');
const port = 9000;

const app = express();

app.listen(port, () =>
  console.log(
    `nodejs-convert-file-server listening at http://localhost:${port}`,
  ),
);

Next, navigate to http://localhost:9000 and you should see your server running. No endpoints are created just yet, so you will be met with Cannot GET/. If you run into any other errors, check the terminal, since it might require a manual restart.

Serve Static Files From Node.js

We will create a new folder directory called files within your project. Let’s add an API to our index.js to return a list of files inside of it in JSON format.

app.get('/files', (req, res) => {
  const inputPath = path.resolve(__dirname, filesPath);
  fs.readdir(inputPath, function (err, files) {
    if (err) {
      return console.log('Unable to scan directory: ' + err);
    }
    res.setHeader('Content-type', mimeType['.json']);
    res.end(JSON.stringify(files));
  });
});

Mime data types are just a way of communicating what type of content the browser should expect. Therefore, I’ve prepared a handy module you can use:

// maps file extension to MIME types
// full list can be found here: https://www.freeformatter.com/mime-types-list.html
module.exports = mimeType = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.zip': 'application/zip',
    '.doc': 'application/msword',
    '.eot': 'application/vnd.ms-fontobject',
    '.ttf': 'application/x-font-ttf',
  };

To use this module inside of index.js, make sure you import it:

const mimeType = require('./mimeType');

Now, let’s create another endpoint that returns the requested file:

app.get('/files/:filename', (req, res) => {
  const inputPath = path.resolve(__dirname, filesPath, req.params.filename);
  fs.readFile(inputPath, function (err, data) {
    if (err) {
      res.statusCode = 500;
      res.end(`Error getting the file: ${err}.`);
    } else {
      const ext = path.parse(inputPath).ext;
      res.setHeader('Content-type', mimeType[ext] || 'text/plain');
      res.end(data);
    }
  });
});

Over at http://localhost:9000, if you append a path and a filename, you should get that file back in your response. For example, http://localhost:9000/files/test.pdf will return test.pdf if that file is present in the files folder.

Create a Thumbnail by Converting PDF to Image

Let’s add another API to create a thumbnail of a PDF, a functionality that will pair nicely with the ability to list files in the directory and get a quick preview for each of them.

For this new API, we will use the Apryse library we installed earlier.

app.get('/thumbnail/:filename', (req, res) => {
  const filename = req.params.filename;
  let ext = path.parse(filename).ext;

  const inputPath = path.resolve(__dirname, filesPath, filename);
  const outputPath = path.resolve(__dirname, filesPath, `${filename}.png`);

  if (ext !== '.pdf') {
    throw `Only PDFs can return a thumbnail. Cannot return a thumb for a file with extension: ${ext}.`;
  }

  const main = async () => {
    const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath);
    await doc.initSecurityHandler();
    const pdfdraw = await PDFNet.PDFDraw.create(92);
    const currPage = await doc.getPage(1);
    await pdfdraw.export(currPage, outputPath, 'PNG');
  };

  PDFNetEndpoint(main, outputPath, res);
})

The above code snippet will parse out the requested parameters, ensure the file is a PDF, and generate a PNG thumbnail for the first page, before calling a function we created called PDFNetEndpoint. PDFNetEndpoint definition is below:

const PDFNetEndpoint = (main, pathname, res) => {
    PDFNet.runWithCleanup(main)
    .then(() => {
      PDFNet.shutdown();
      fs.readFile(pathname, (err, data) => {
        if (err) {
          res.statusCode = 500;
          res.end(`Error getting the file: ${err}.`);
        } else {
          const ext = path.parse(pathname).ext;
          res.setHeader('Content-type', mimeType[ext] || 'text/plain');
          res.end(data);
        }
      });
    })
    .catch((error) => {
      res.statusCode = 500;
      res.end(error);
    });
};

This Apryse endpoint ensures that we can execute the thumbnail-generating function without any errors and return an image representation of the first page of a PDF.

To test the endpoint out, enter the following into the browser: http://localhost:9000/thumbnail/test.pdf

Convert to PDF from DOCX, PPTX, or XLSX

Here is an example for how to convert an MS Office document into a PDF without needing MS Office software or licenses.

app.get('/convert/:filename', (req, res) => {
  const filename = req.params.filename;
  let ext = path.parse(filename).ext;

  const inputPath = path.resolve(__dirname, filesPath, filename);
  const outputPath = path.resolve(__dirname, filesPath, `${filename}.pdf`);

  if (ext === '.pdf') {
    res.statusCode = 500;
    res.end(`File is already PDF.`);
  }

  const main = async () => {
    const pdfdoc = await PDFNet.PDFDoc.create();
    await pdfdoc.initSecurityHandler();
    await PDFNet.Convert.toPdf(pdfdoc, inputPath);
    pdfdoc.save(
      `${pathname}${filename}.pdf`,
      PDFNet.SDFDoc.SaveOptions.e_linearized,
    );
    ext = '.pdf';
  };

  PDFNetEndpoint(main, outputPath, res);
});

To test it out, enter the following in the browser: http://localhost:9000/convert/test.docx.

Generate PDFs From a Template

Typically, generating PDFs happens from a source format, like a Word file or HTML markup, which you then convert to PDF using a solution like the Apryse SDK. For example, we have a letter template below, called template_letter.pdf in which we will replace names, dates, and addresses programmatically.

Empty letter template used for PDF generation

app.get('/replaceContent/:name', (req, res) => {
  const name = req.params.name.replace('_', ' ');
  const filename = 'template_letter.pdf'

  const inputPath = path.resolve(__dirname, filesPath, filename);
  const outputPath = path.resolve(__dirname, filesPath, `${filename}_replaced.pdf`);

  const main = async () => {
    const pdfdoc = await PDFNet.PDFDoc.createFromFilePath(inputPath);
    await pdfdoc.initSecurityHandler();
    const replacer = await PDFNet.ContentReplacer.create();
    const page = await pdfdoc.getPage(1);

    await replacer.addString('NAME', name);
    await replacer.addString('Address', '123 Main St, Vancouver, BC CANADA');
    await replacer.addString('DATE', new Date(Date.now()).toLocaleString());
    await replacer.process(page);

    pdfdoc.save(
      outputPath,
      PDFNet.SDFDoc.SaveOptions.e_linearized,
    );
  };

  PDFNetEndpoint(main, outputPath, res);
});

To test it, in browser, call the endpoint http://localhost:9000/replaceContent/John_Smith. After replacing name, address, and date, our letter is ready to be sent. As you can see, we preserve fonts and styles.

Filled letter template as part of PDF generation

Using Apryse, however, you can also generate PDFs from scratch. In the following sample, we generate a new PDF from nothing and add a blank page.

app.get('/generate/:filename', (req, res) => {
  const filename = req.params.filename;
  const outputPath = path.resolve(__dirname, filesPath, `${filename}.pdf`);
  const main = async () => {
    const pdfdoc = await PDFNet.PDFDoc.create();
    await pdfdoc.initSecurityHandler();
    const page1 = await pdfdoc.pageCreate();
    pdfdoc.pagePushBack(page1);
    pdfdoc.save(
      outputPath,
      PDFNet.SDFDoc.SaveOptions.e_linearized,
    );
  };

  PDFNetEndpoint(main, outputPath, res);
});

After generating a PDF, you can call other APIs to add text elements, images, and so on⁠—either through adding annotations and then flattening them, or element building at a low-level.

Watermark a PDF

Sometimes, we want to protect the content of a PDF and prevent screenshotting or screen capture of a document. Many organizations choose to watermark content in order to protect it, which can be achieved with the following:

app.get('/watermark/:filename-:watermark', (req, res) => {
  const filename = req.params.filename;
  const watermark = req.params.watermark;
  let ext = path.parse(filename).ext;

  if (ext !== '.pdf') {
    res.statusCode = 500;
    res.end(`File is not a PDF. Please convert it first.`);
  }

  const inputPath = path.resolve(__dirname, filesPath, filename);
  const outputPath = path.resolve(__dirname, filesPath, `${filename}_watermarked.pdf`);

  const main = async () => {
    const pdfdoc = await PDFNet.PDFDoc.createFromFilePath(inputPath);
    await pdfdoc.initSecurityHandler();

    const stamper = await PDFNet.Stamper.create(
      PDFNet.Stamper.SizeType.e_relative_scale,
      0.5,
      0.5,
    ); // Stamp size is relative to the size of the crop box of the destination page
    stamper.setAlignment(
      PDFNet.Stamper.HorizontalAlignment.e_horizontal_center,
      PDFNet.Stamper.VerticalAlignment.e_vertical_center,
    );
    const redColorPt = await PDFNet.ColorPt.init(1, 0, 0);
    stamper.setFontColor(redColorPt);
    const pgSet = await PDFNet.PageSet.createRange(1, await pdfdoc.getPageCount());
    stamper.stampText(pdfdoc, watermark, pgSet);

    pdfdoc.save(
      outputPath,
      PDFNet.SDFDoc.SaveOptions.e_linearized,
    );
  };

  PDFNetEndpoint(main, outputPath, res);
});

To test, in the browser, call http://localhost:9000/watermark/webviewer.pdf-awesome. This will watermark every page of the document with awesome.

Add More APIs and Endpoints

You can also add a number of other document manipulation APIs. In fact, we have put together several Node.js samples for you to try out, including:

  • Parse & extract PDF content
  • Convert HTML to PDF
  • Encrypt and decrypt PDF files
  • Compress & optimize PDF files
  • Redact PDF content
  • Much more… (see Node.js samples)

Conclusion

This article was intended to help you build a simple document processing file server using Node.js and Express using our sample project on Github.

Ultimately, however, we’re just scratching the surface of what functionalities you can add with the powerful Apryse SDK, including dozens of other unique document processing capabilities.

Stay tuned for more APIs and demos, which I’ll be adding. And feel free to reach out with any questions.

Convert word document to pdf in Nodejs Example

In this post, You will learn how to convert Docx files to pdf documents in JavaScript and nodejs.

Docx/doc are document file formats from Microsoft, that contains images, text, tables, and styles
PDF files are from Adobe company, which is a separate format for representing the content of images, texts, and styles

There are a lot of online tools to do the conversion from doc to pdf. Sometimes, As a programmer, you need to have a conversion of different formats in the JavaScript/NodeJS applications.

JavaScript/NodeJS offers multiple ways to convert using npm packages

  • docx-to-pdf
  • libreoffice-convert

You can also check other posts on npm command deprecate option is deprecated

How to Convert word document to pdf in Nodejs application

First, Create a Nodejs application from scratch.

Let’s create a nodejs application from scratch using the npm init -y command in a new folder

B:blogjsworknodeworkdoctopdf>npm init -y
Wrote to B:blogjsworknodeworkdoctopdfpackage.json:

{
  "name": "doctopdf",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

This creates a package.json as follows

{
  "name": "doctopdf",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

convert docx to pdf using docx-pdf library

docx-pdf is a simple library to convert Docx to a pdf document.

First, Install Docx-pdf npm library

npm install Docx-pdf --save

This will add a dependency in package.json as follows

{
 "dependencies": {
    "docx-pdf": "0.0.1"
  }
}

In javascript, import docx-pdf using the required for ES5 modules

var converter = require('docx-pdf');

convert objects accepts

  • input file which is a word document
  • output file is the name of a pdf document
  • callback which has err for error messages for conversion failed
    and result in successful conversion
  • a result is an object containing a filename attribute and the value is the pdf document name and path
var converter = require('docx-pdf');

converter('test.docx', 'output.pdf', function(err, result) {
    if (err) {
        console.log("Converting Doc to PDF  failed", err);
    }
    console.log("Converting Doc to PDF succesfull", result);
});

And same code was written with async and await keywords for the asynchronous process.

convert docx to pdf with async/await

This will be useful for bigger files of sizes

The declared function which accepts input and output filename
It returns the promise object with reject for failed conversions and resolve for successful conversions.
And, docxConverter logic calls inside the async keyword with an anonymous function for asynchronous processing.

    async function ConvertDocToPdf(inputfile, outputfile) {
            return new Promise((resolve, reject) =>{
                        const inputPath = path.join(__dirname, "test.docx");
        const outputPath = path.join(__dirname, `/test.pdf`);
        let docData = await fs.readFile(inputPath)
                docxConverter(inputfile, outputfile, (err, result) => {
                    return err ?
                        reject(err) :
                        resolve(result)
                })
            })
        }

You need to call the same function with the await keyword

    await ConvertDocToPdf("test.docx", "test.pdf")

It is a simple library, the only disadvantage is not able to convert formatting styles.

libreoffice-convert npm package

libreoffice is an open-source office package for managing office documents.

libreoffice-convert is an npm package in nodejs that provides manipulation of word documents.

First, install libreoffice-convert npm package using the npm install command

npm install libreoffice-convert --save

Example code to convert docx to pdf using the libreoffice-convert package:

const libre = require('libreoffice-convert');
const path = require('path');
const fs = require('fs');
async function ConvertDocToPdf() {
    try {
        const inputPath = path.join(__dirname, "test.docx");
        const outputPath = path.join(__dirname, `/test.pdf`);
        let docData = await fs.readFile(inputPath)
        return new Promise((resolve, reject) => {
            libre.convert(docData, '.pdf', undefined, (err, done) => {
                if (err) {
                    reject('Conversion Failed')
                }
                fs.writeFileSync(outputPath, done);
                resolve("Convertion successfull")
            });
        })
    } catch (err) {
        console.log("Error in input reading", err);
    }
}

a sequence of steps for the above code

  • Defined function with async keyword for asynchronous processing
  • import libreoffice-convert, fs, and path modules into code
  • read the input file using readFile method of fs module in NodeJS
  • libre.convert the docx to pdf file
  • conversion code is wrapped in a promise object
  • for conversion failed cases, the reject promise is returned
  • the promise is resolved for a successful conversion,
  • Finally written output pdf file using the writeFileSync method

Conclusion

To Sum up, Learned how to Convert word to pdf in nodejs in multiple ways.

nodejs-convert-file-server

Screenshot

Convert from MS Office, images to PDF, get thumbnails for file previews, optimize files for quick rendering.

Built with:

  • Node.js
  • Express.js
  • PDFTron Node.js SDK

I put together a get started blog to walk through this project.

And you can follow this step-by-step video to recreate it yourself.

Installation

Clone the repo and run:

npm start

The server will be listening on port 9000. http://localhost:9000

Test

To test the proper functionality of the file server, you can run:

npm test

API Calls

List file directory

The endpoint returns all files present in the files directory in JSON format.

HTTP Request

GET http://localhost:9000/files

Get file

The endpoint returns the requested file.

HTTP Request

GET http://localhost:9000/files/:filename

Get thumbnail

The endpoint returns the thumbnail for the specified file. Uses PDFTron Node.js API.

HTTP Request

GET http://localhost:9000/thumbnail/:filename

Convert to PDF

The endpoint converts the file to a PDF. Conversion is possible for the following file formats: DOC, DOCX, PPTX, PPT, XLSX, PNG, JPEG, JPG, TIFF, TXT. Uses PDFTron Node.js API.

HTTP Request

GET http://localhost:9000/convert/:filename

Convert to PDF from HTML

The endpoint converts the HTML to a PDF. There are several settings available to get the best results. Uses PDFTron Node.js API for HTML2PDF.

HTTP Request

GET http://localhost:9000/convertHTML/:filename-:pathToHTML

Example

Converts an HTML form to a PDF
http://localhost:9000/convertHTML/myhtml-index.html

Optimize PDF

The endpoint converts the PDF to an optimized PDF to be used with PDFTron WebViewer. Uses PDFTron Node.js API.

HTTP Request

GET http://localhost:9000/optimize/:filename

Extract Text from a PDF

Returns text from a PDF at a specified page number.

HTTP Request

GET http://localhost:9000/textextract/:filename-:pagenumber

Generate PDF

Creates a blank PDF with a single page.

HTTP Request

GET http://localhost:9000/generate/:filename

Replace Content in PDF

Replaces a placeholder string in a PDF.

HTTP Request

GET http://localhost:9000/replaceContent/:name

Example

Replaces placeholder strings in the template PDF letter with provided name and returns a ready to be sent file. The _ replaced with spaces.
http://localhost:9000/replaceContent/John_Smith

Watermark PDF

Watermarks a PDF document with the provided watermark.

HTTP Request

GET http://localhost:9000/watermark/:filename-:watermark

Example

Places a watermark on every page in red.
http://localhost:9000/watermark/webviewer.pdf-awesome

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

Reading time: 10 minutes | Coding time: 15 minutes

In this article you will learn how how to create PDF files out of your word document.Well up until recently, creating complex or elegant PDFs in Javascript has been challenging.Here I’m going to show you step-by-step the path of to create beautiful PDFs.

unnamed

Before we dive further into the process why don’t we learn what is word document or what is PDFs or what is the need to convert word document to PDFs.
Word Document is a popular word-processing program used primarily for creating documents such as letters, brochures, learning activities, tests, quizzes and students’ homework assignments.DOC stands for DOCument file. A DOC file can contain formatted text, images, tables, graphs, charts, page formatting, and print settings.

The Portable Document Format (PDF)is a file format developed by Adobe in the 1990s to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems
Yes, PDFs were created to avoid any changes that might occur due change in hardware or software which might have occurred to you if you had ever used Word document.Let’s take a example,Whenever a make a word document and to a printing shop for the print the shop owner may have different OS,hardware or even software and when you get your printed document it is not what you saved at your computer maybe there is a large gap between line format is distorted or something else.So,that’s where PDF come’s to rescue.

Word to PDF approaches

There are three methods that I am going to discuss today which are very easy to use and produce excellent results. These are using:

  • awesome-unoconv
  • libreoffice-convert
  • docx-pdf

1. awesome-unoconv

awesome-unoconv is nodeJS wrapper for converting Office files to PDF or HTML

REQUIREMENT

Unoconv is required, which requires LibreOffice (or OpenOffice)
You can install unoconv in linux operating system by using following command

sudo apt-get install unoconv

INSTALLATION

npm install awesome-unoconv

CODE

const path = require('path');
const unoconv = require('awesome-unoconv');
//Place your word file in source
const sourceFilePath = path.resolve('./word_file.docx');
const outputFilePath = path.resolve('./myDoc.pdf');
 
unoconv
  .convert(sourceFilePath, outputFilePath)
  .then(result => {
    console.log(result); // return outputFilePath
  })
  .catch(err => {
    console.log(err);
  });

Now go to the terminal and run your command pdf will be created in current working directory with name «myDoc.pdf» (you choose any name you like).
This is one of the method to convert word document to pdf let’s keep going.

2. libreoffice-convert

A simple and fast node.js module for converting office documents to different formats.

DEPENDENCY

Since,I am using linux please Install libreoffice in /Applications (Mac), with your favorite package manager (Linux), or with the msi (Windows).

INSTALLATION

npm install libreoffice-convert

CODE

const libre = require('libreoffice-convert');
 
const path = require('path');
const fs = require('fs');
 
const extend = '.pdf'
const FilePath = path.join(__dirname, './word_file.docx');
const outputPath = path.join(__dirname, `./example${extend}`);
 
// Read file
const enterPath = fs.readFileSync(FilePath);
// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
libre.convert(enterPath, extend, undefined, (err, done) => {
    if (err) {
      console.log(`Error converting file: ${err}`);
    }
    
    // Here in done you have pdf file which you can save or transfer in another stream
    fs.writeFileSync(outputPath, done);
});

Since,This is only for libre-office you might not find it very usefull if you are using windows but for for linux/Mac operating system it is very popular.

Let’s look at the last and third method to convert word document to PDFs

3. docx-pdf

It is a library that converts docx file to pdf and it is one of most optimal and quality wise best among the three and most easiest one also.

INSTALLATION

npm install docx-pdf

CODE

var docxConverter = require('docx-pdf');

docxConverter('./word_file.docx','./output.pdf',function(err,result){
  if(err){
    console.log(err);
  }
  console.log('result'+result);
});

Output should be output.pdf which will be produced on the output path your provided.

Question

Which one of the following is the correct command to install any module/package in your project?

npm install package-name

node install package-name

install package-name

nodejs install package-name

npm install

is the correct syntax,Example:
If you want to install express module you can do it by writing the command
> npm install express

If you want to see the project you can use this link to my github page.

udiko

udiko

Posted on Apr 28, 2022



 



 



 



 



 

 

Most of the npms didnt works for me but this one do the job:

npm i convert-multiple-files

convert.ts:

import { convertWordFiles } from 'convert-multiple-files';

const docToPdf = async (filePath: string, outputDir: string): Promise<string> => await convertWordFiles(filePath, 'pdf', outputDir);

export {
    docToPdf
};

Enter fullscreen mode

Exit fullscreen mode

const outputFile = await docToPdf('file.docx', './outFolder');

Top comments (0)

Like this post? Please share to your friends:
  • Node js работа с файлами excel
  • Node js выгрузка в excel
  • Node js word template
  • Node js import syntaxerror unexpected reserved word
  • Node js excel parser