在netlify上托管混合应用程序,并将supabase作为db。有没有一种方法可以使用混合方式生成pdf文档?
发布于 2022-01-10 16:39:47
Remix有一个名为资源路线的特性,它允许您创建返回任何内容的端点。
使用它们,您可以用PDF返回响应,如何生成PDF将取决于您使用的库是什么,如果您使用的是React,您可以这样做:
// 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,请将呈现部分更改为使用正在使用的库,并保留标头和响应创建部分。
https://stackoverflow.com/questions/70642314
复制相似问题