从Node.js后端查看/下载PDF文件

4
我会尽力而为。以下是需要翻译的内容:

我正在我的节点后端生成一个pdf,就像这样:

router.post('/api/submissions/generatecontract', auth, function (req, res, next) {
  if (!req.body.stallholderId || !req.body.edition) {
    return res.json({status: 400, message: 'Please enter all fields.' });
  }

  var doc = new PDFDocument();

  doc.fontSize(25).text('Here is some text', 100, 80);
  doc.end();

  return doc.pipe(res);
});

现在当我调用后端并console.log响应时,我会得到以下输出:

_body: "%PDF-1.3↵%����↵5 0 obj↵<<↵/Type /Page↵/Parent 1 0 R↵/MediaBox [0 0 612 792]↵/Contents 3 0 R↵/Resources 4 0 R↵>>↵endobj↵4 0 obj↵<<↵/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]↵/Font <<↵/F1 6 0 R↵>>↵>>↵endobj↵7 0 obj↵<<↵/Producer (PDFKit)↵/Creator (PDFKit)↵/CreationDate (D:20160903110846Z)↵>>↵endobj↵6 0 obj↵<<↵/Type /Font↵/BaseFont /Helvetica↵/Subtype /Type1↵/Encoding /WinAnsiEncoding↵>>↵endobj↵2 0 obj↵<<↵/Type /Catalog↵/Pages 1 0 R↵>>↵endobj↵1 0 obj↵<<↵/Type /Pages↵/Count 1↵/Kids [5 0 R]↵>>↵endobj↵3 0 obj↵<<↵/Length 106↵/Filter /FlateDecode↵>>↵stream↵x�e�1↵�@�yE�sfvw�1��L�L.:13���+�IAS]�4Rdz��I�jcy�@�a9~8��~Zm����%WKʖ=({�ݶ�{�4 0z�<��LS��.J��↵endstream↵endobj↵xref↵0 8↵0000000000 65535 f ↵0000000446 00000 n ↵0000000397 00000 n ↵0000000503 00000 n ↵0000000119 00000 n ↵0000000015 00000 n ↵0000000300 00000 n ↵0000000208 00000 n ↵trailer↵<<↵/Size 8↵/Root 2 0 R↵/Info 7 0 R↵>>↵startxref↵681↵%%EOF↵"

headers: Headers _headersMap:Map size: (...) proto: Map [1] 0: {"content-type" => Array[1]} key: "content-type" value: Array[1] 0: "application/pdf" length:1 proto: Array[0] proto: Object ok: true status:200 statusText:"OK" type:2 url:"http://localhost:3000/api/submissions/generatecontract"

_body: "%PDF-1.3↵%����↵5 0 obj↵<<↵/Type /Page↵/Parent 1 0 R↵/MediaBox [0 0 612 792]↵/Contents 3 0 R↵/Resources 4 0 R↵>>↵endobj↵4 0 obj↵<<↵/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]↵/Font <<↵/F1 6 0 R↵>>↵>>↵endobj↵7 0 obj↵<<↵/Producer (PDFKit)↵/Creator (PDFKit)↵/CreationDate (D:20160903110846Z)↵>>↵endobj↵6 0 obj↵<<↵
我看到我的PDF文件在响应正文中。但是我该如何在浏览器中查看或下载它?如果有影响的话,我正在使用Angular2作为前端。
我找到的信息是针对先前的Angular 2版本。

这个链接 - Angular 2 download PDF from API and Display it in View 可能会有用。 - Mikki Kobvel
它并不实用,因为它是针对 Angular2 的先前版本。 - stijn.aerts
1个回答

0
我是这样解决的:
  generateContract(stallholder: Stallholder, submission: Submission) {
    let headers = new Headers();
    let options = new RequestOptions({ headers: headers });

    headers.append('authorization', 'Bearer ' + this.userService.getToken());

    this.http.get(this.apiUrl + `api/editions/${submission.edition}`, options)
      .map(res => res.json()).subscribe(data => {
        if (data.status === 200) {
          let total = submission.metersStreet * data.price;
          let params = `email=${stallholder.email}&firstName=${stallholder.firstName}&lastName=${stallholder.lastName}
          &name=${stallholder.name}&metersStreet=${submission.metersStreet}&metersDepth=${submission.metersDepth}
          &edition=${submission.edition}&total=${total}`;
          this.openPdfFile(params);
        }
      });
  }

  openPdfFile(params) {
    this.downloadFile(params, function (blob) {
      let win: any = window.open('_blank');
      let blobb = new Blob([blob], {type: 'application/pdf'});
      let url: any = URL.createObjectURL(blobb);
      win.location.href = url;
    });
  }

  downloadFile(params, success) {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', this.apiUrl + 'api/submissions/generatecontract', true);
    xhr.setRequestHeader('authorization', 'Bearer ' + this.userService.getToken());
    xhr.responseType = 'arraybuffer';
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (success) {
          success(xhr.response);
        }
      }
    };
    xhr.send(params);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接