有没有办法用 remix.run 生成 pdf

Jak*_*nár 1 pdf pdf-generation supabase remix.run

在 netlify 上托管 remix 应用程序,使用 supabase 作为数据库。有没有办法使用 remix 生成 pdf 文档?

小智 7

Remix 有一个名为“资源路由”的功能,可让您创建返回任何内容的端点。

使用它们,您可以返回带有 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 });
}
Run Code Online (Sandbox Code Playgroud)

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


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