Is there an npm package for converting RTF strings to PDF file in node.js?

Viewed 1477

I'm looking for an RTF to PDF converter for Node.js. I'm not finding too many packages over at the npm site.

The application is as follows: I need to pull an RTF document (created in Word and saved as .rtf) from an AWS S3 bucket. Then I need to read the file as an RTF string. Next, I need to replace certain placeholder tokens in the RTF string with values (ex. in "{host-name} would like to invite you to {address} on {date}."--I need to replace {host-name}, {address}, and {date} with actual values). Then, with actual values plugged in, I need to convert the string to a PDF that I can attach to an email.

For this reason, I cannot use any of the several Word-to-PDF packages out there (because I need to intervene in the intermediate step of plugging the placeholders with values), so I'm looking for an RTF-to-PDF converted (where the RTF starts as a string).

Is there such a thing?

Thanks.

1 Answers

LibreOffice in headless mode should provide file conversion to PDF. You can integrate it in node with LibreOffice-Convert.

However you'll need LibreOffice in your machine, as it's not installed with npm. See here for the location according to your system.

This is how it's used in the command line, so it supports RTF to PDF conversion:

soffice --headless --convert-to pdf file_name.rtf (source)

In theory it should be implemented like this (adapted from npmjs):

const libre = require('libreoffice-convert');
const path = require('path');
const fs = require('fs');
const enterPath = path.join(__dirname, '/resources/example.rtf');
const outputPath = path.join(__dirname, '/resources/example.pdf');

// Read file
const file = fs.readFileSync(enterPath);
// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
libre.convert(file, '.pdf', 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);
});
Related