0

在 netlify 上使用 supbase 作为 db 托管混音应用程序。有没有办法使用 remix 生成 pdf 文档?

4

1 回答 1

1

Remix 有一个名为Resource Routes的功能,可让您创建返回任何内容的端点。

使用它们,您可以返回带有 PDF 的响应,如何生成 PDF 将取决于您使用的库,如果您使用 React PDF 之类的东西,您可以执行以下操作:

// routes/pdf.tsx
import { renderToStream } from "@react-pdf/renderer";
// this is your PDF document component created with React PDF
import { PDFDocument } from "~/components/pdf";
import type { LoaderFunction } from "remix";

export let loader: LoaderFunction = async ({ request, params }) => {
  // you can get any data you need to generate the PDF inside the loader
  // however you want, e.g. fetch an API or query a DB or read the FS
  let data = await getDataForThePDFSomehow({ request, params });

  // render the PDF as a stream so you do it async
  let stream = await renderToStream(<PDFDocument {...data} />);

  // and transform it to a Buffer to send in the Response
  let body: Buffer = await new Promise((resolve, reject) => {
    let buffers: Uint8Array[] = [];
    stream.on("data", (data) => {
      buffers.push(data);
    });
    stream.on("end", () => {
      resolve(Buffer.concat(buffers));
    });
    stream.on("error", reject);
  });

  // finally create the Response with the correct Content-Type header for
  // a PDF
  let headers = new Headers({ "Content-Type": "application/pdf" });
  return new Response(body, { status: 200, headers });
}

现在,当用户访问它时,/pdf它会取回 PDF 文件,您还可以使用 iframe 在 HTML 上显示它。


如果您不使用 React PDF,请将渲染部分更改为使用您正在使用的库,并保留标题和响应创建部分。

于 2022-01-10T16:39:47.043 回答