如何使用 pdflatex 子进程在 Node.js 中获取 PDF 作为流?

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

这是我的文件:

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

这里是我的app.js文件的相关内容:

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

运行 此代码成功地在同一目录中创建了一个 res.pdf 文件。但是,我不想创建文件,而是希望将 PDF 作为流获取并将其作为对浏览器的响应发送。 我试图避免在服务器中创建任何 PDF 文件,我只想立即发送生成的 PDF 作为响应。是否可以更改此代码来执行此操作?

node-pdflatex有以下方法。

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;
        });
    }
};

解决方案

一旦文件生成,我们就可以读取文件,取消文件与目录的链接,并将响应发送到浏览器。

 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);
 }

希望对您有所帮助。

基于 pdflatex documentation 它不能处理流,只能处理文件。

这有点晚了,但我最终只是围绕 latex 编写了自己的包装器。它允许您使用字体和 .cls,以及其他输入。它创建一个 temp 目录,将生成的 PDF 放在那里,然后将 PDF 流式传输回给您。 temp 目录随后被清理。

您可以在此处查看模块:node-latex