axios post请求和节点pdfkit显示空白pdf

问题描述 投票:0回答:1

我正在使用

react
axios
express
服务器发送发布请求,以使用
pdfkit
创建 pdf。发回后,文件会自动下载。它似乎发回 pdf 信息,但打开文件时 pdf 是空白的。

import axios from 'axios';
import download from 'downloadjs';

const url = baseUrl + /invoice-generator/create-pdf;

export const downloadInvoiceApi = async (values) => {
  await axios.post(`${baseUrl}/invoice-generator/create-pdf`, {
    responseType: "arraybuffer",
    headers: {
      "Content-Type": "application/pdf"
    }
  })
  .then((response) => {
    download(response.data, "file.pdf", response.headers['content-type']);
  });

};


这是快递代码

import { Request, Response } from "express"
import PDFDocument from 'pdfkit';

export const createPDF = async (
    req: invoiceGeneratorRequest,
    res: Response
) => {

    try {
      res.writeHead( 200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename=test.pdf'
      } );

      let doc = new PDFDocument( {
          size: 'A4',
          margin: 50
      } );


      doc.fontSize( 12 );

      doc.text( 'PDFKit is simple', 10, 30, {
          align: 'center',
          width: 200
      } );

      doc.end();
      doc.pipe( res );

    } catch (error) {
        console.error("Error creating PDF", error)
        res.status(500).send("Error creating PDF")
    }
}

返回的pdf数据

%PDF-1.3
%����
7 0 obj
<<
/Type /Page
/Parent 1 0 R
/MediaBox [0 0 595.28 841.89]
/Contents 5 0 R
/Resources 6 0 R
>>
endobj
6 0 obj
<<
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
/Font <<
/F1 8 0 R
>>
>>
endobj
5 0 obj
<<
/Length 108
/Filter /FlateDecode
>>
stream
x�m�1
�0F�]��/PG�eقҡ��
�B��d���/���<��'��E]%u�vЗ�߾��V���sI�)�iHF�^+���ۼi�a�܊�}�f�~!4=��Kq
endstream
endobj
10 0 obj
(PDFKit)
endobj
11 0 obj
(PDFKit)
endobj
12 0 obj
(D:20240307162326Z)
endobj
9 0 obj
<<
/Producer 10 0 R
/Creator 11 0 R
/CreationDate 12 0 R
>>
endobj
8 0 obj
<<
/Type /Font
/BaseFont /Helvetica
/Subtype /Type1
/Encoding /WinAnsiEncoding
>>
endobj
4 0 obj
<<
>>
endobj
3 0 obj
<<
/Type /Catalog
/Pages 1 0 R
/Names 2 0 R
>>
endobj
1 0 obj
<<
/Type /Pages
/Count 1
/Kids [7 0 R]
>>
endobj
2 0 obj
<<
/Dests <<
  /Names [
]
>>
>>
endobj
xref
0 13
0000000000 65535 f 
0000000735 00000 n 
0000000792 00000 n 
0000000673 00000 n 
0000000652 00000 n 
0000000214 00000 n 
0000000125 00000 n 
0000000015 00000 n 
0000000555 00000 n 
0000000480 00000 n 
0000000394 00000 n 
0000000419 00000 n 
0000000444 00000 n 
trailer
<<
/Size 13
/Root 3 0 R
/Info 9 0 R
/ID [<c38b249f82e129b82db4804f21d40825> <c38b249f82e129b82db4804f21d40825>]
>>
startxref
839
%%EOF

pdf 下载正确,但当我打开 PDF 时,它是空白的

reactjs node.js express axios pdfkit
1个回答
0
投票

根据文档,在浏览器

responseType
上,只能使用
blob
作为值:

  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  //   browser only: 'blob'
  responseType: 'json', // default https://axios-http.com/docs/req_config

因此,相应地更改它:

  await axios.post(`${baseUrl}/invoice-generator/create-pdf`, {
    responseType: "blob",
    headers: {
      "Content-Type": "application/pdf"
    }
  })
  .then((response) => {
    download(response.data, "file.pdf", response.headers['content-type']);
  });

然后下载应该是这样的:

const url = window.URL.createObjectURL(response.data);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.pdf');
document.body.appendChild(link);
link.click();

document.body.removeChild(link);
URL.revokeObjectURL(href);
© www.soinside.com 2019 - 2024. All rights reserved.