首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法用remix.run生成pdf?

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

Stack Overflow用户
提问于 2022-01-09 14:39:33
回答 1查看 795关注 0票数 0

在netlify上托管混合应用程序,并将supabase作为db。有没有一种方法可以使用混合方式生成pdf文档?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-10 16:39:47

Remix有一个名为资源路线的特性,它允许您创建返回任何内容的端点。

使用它们,您可以用PDF返回响应,如何生成PDF将取决于您使用的库是什么,如果您使用的是React,您可以这样做:

代码语言:javascript
复制
// 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,请将呈现部分更改为使用正在使用的库,并保留标头和响应创建部分。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70642314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档