下载PDF文件而不将其保存在服务器nodejs上

时间:2017-08-10 12:32:57

标签: node.js

我正在使用html-pdf从HTML创建PDF文件。现在我想按下HTML按钮下载文件。我知道如何强制下载文件。现在我想知道如何强制下载生成的PDF文件。

PDF生成代码:

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('PDF.html', 'utf8');
var options = { "height": "9in",        // allowed units: mm, cm, in, px
  "width": "8in" ,orientation : "portrait","header": {
    "height": "5mm",border: {
    "top": "2in",            // default is 0, units: mm, cm, in, px
    "right": "1in",
    "bottom": "2in",
    "left": "1.5in"
  },
    "base": "",
  },};


pdf.create(html).toStream(function(err, stream){
  stream.pipe(fs.createWriteStream('foo.pdf'));
});

文件下载代码:

var http = require('http');


http.createServer(function (req, res) {
var text_ready = "This is a content of a txt file."


res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'});

res.end( text_ready );
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

有没有办法可以将这两种方法结合起来?或者更好的方法来下载生成的PDF文件而不保存它?我让他们两个分开工作。我对Node.js很新。

1 个答案:

答案 0 :(得分:2)

您可以将pdf传输到响应,因为响应实现了Writable Stream

int numberOfWordsInDict(char **dict)
{
    int i, cnt = 0;
    for(i = 0; i < 10; i++)
    {
        if(dict[i] != NULL)
        {
            cnt++;
        }
    }
    return cnt;
}

void printDict(char **dict)
{
    int i = 0;
    printf("Dictionary:\n");
    if(numberOfWordsInDict(dict) == 0)
    {
        printf("The dictionary is empty.\n");
    } else
    {
        for(i = 0; i < 10; i++)
        {
            printf("- %s\n", dict[i]);
        }
    }
}

int main()
{
    char *dict[10] = {
            "aap", "bro ", "jojo", "koe", "kip", 
            "haha", "hond", "    drop", NULL,NULL};

    char *newWord1 = "hoi";
    printDict(dict);
    strcpy(dict[1], newWord1);
    printDict(dict);

    return 0;
}