这是我的文件:

.
├── 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);
 }

希望这可以帮助。

关于javascript - 如何使用pdflatex子进程在Node.js中将PDF作为流获取?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41560344/

10-09 20:12
查看更多