How to use a pdflatex child process to get a PDF as a stream in Node.js?

1.3k views Asked by At

Here are my files:

.
├── app.js
├── res.cls
└── res.tex

And here is the relevant contents of my app.js file:

const { spawn } = require('child_process')
const latex = spawn('pdflatex', ['res.tex'])

Running this code successfully creates a res.pdf file in the same directory. However, rather than creating a file, I would like to get the PDF as a stream and send it as a response to the browser instead. I'm trying to avoid creating any PDF files in the server, I just want to send the generated PDF as a response immediately. Is it possible to alter this code to do this?

3

There are 3 answers

0
Saad On BEST ANSWER

This is a bit late, but I ended up just writing my own wrapper around latex. It lets you use fonts and .cls, and other inputs. It creates a temp directory, puts the generated PDF in there and then streams the PDF back to you. The temp directory is cleaned up afterwards.

You can check out the module here: node-latex.

1
SUNDARRAJAN K On

The node-pdflatex has the following methods.

var util = require('util');
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;

/*
 PDFLatex class
*/
// constructor
function PDFLatex(inputPath) {
    // default settings
    this.outputDirectory = process.cwd() + "/";
    this.inputPath = inputPath;
};

PDFLatex.prototype.outputDir = function(path) {
    this.outputDirectory = path;
    return this;
};

PDFLatex.prototype.process = function() {
    if (this.inputPath && this.inputPath.length > 0) {
        var command = "pdflatex -output-directory " + this.outputDirectory + " '" + this.inputPath + "'";
        util.puts(command);
        exec(command, function(err) {
            if (err) throw err;
        });
    }
};

Solution

Once the file is generated, we can read the file, unlink the file from the directory and send the response to the browser.

 var outputDir = '/dir/pdf/a.pdf'.
 if(fs.existsSync(outputDir)) {

    var check = fs.readFileSync(outputDir);
    fs.unlinkSync(outputDir);
    res.attachment(name+'.pdf');
    res.end(check);
 }

Hope this helps.

0
Gergo On

Based on the pdflatex documentation it's not able to handle streams, only files.