python-3.x 如何下载响应作为一个pdf格式的响应来自flask API

kpbwa7wx  于 2022-12-27  发布在  Python
关注(0)|答案(2)|浏览(156)

我想下载我的flask API响应作为一个pdf在JavaScript中的响应应该看起来像这样:

%PDF-1.4%    1 0 obj<</Type /Pages/Count 2/Kids [ 3 0 R 4 0 R ]>>endobj2 0 obj<</Producer (PyPDF2)>>endobj3 0 obj<<

我想将该回复转换为PDF格式并下载

jm2pwxwz

jm2pwxwz1#

首先,向flask API发出请求,获取PDF文件作为blob,为blob创建URL,创建锚元素,设置锚元素的href和download属性

5jvtdoz2

5jvtdoz22#

调用此函数以下载您的PDF。

async function downloadPDF() {
  // Make a GET request to the Flask API
  const response = await fetch('/api/generate-pdf');

  // Get the PDF file as a blob
  const blob = await response.blob();

  // Create a URL for the blob
  const url = URL.createObjectURL(blob);

  // Create an anchor element
  const a = document.createElement('a');

  // Set the href and download attributes of the anchor element
  a.href = url;
  a.download = 'my-pdf.pdf';

  // Simulate a click on the anchor element
  a.click();

  // Revoke the object URL to release the memory
  URL.revokeObjectURL(url);
}

相关问题