【问题标题】:Is there a way to generate pdf with remix.run有没有办法用 remix.run 生成 pdf
【发布时间】:2022-01-09 14:39:33
【问题描述】:

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

【问题讨论】:

    标签: pdf pdf-generation supabase remix.run


    【解决方案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,请将渲染部分更改为使用您正在使用的库,并保留标题和响应创建部分。

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 2017-08-30
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 2010-09-07
      相关资源
      最近更新 更多