如何将 Nextjs 页面导出为 pdf?

2024-03-30

我在页面上有以下结构:

export default function FichaTecnica(props) {
  const data = props.data;
  return (
    <>
      <Container>
        <TopData info={data} />
        <DataSheet datasheet={data} />
        <GraphBox history={data} />
        <MapButton hasMap={data.mapa} />
      </Container>
    </>
  );
}

export async function getServerSideProps(context) {
  const idIndicador = context.params.idIndicador;
  const res = await fetch(
    `${process.env.INDICADORES_BASE_URL}/indicadores/${idIndicador}`
  );

  const data = await res.json();
  if (res.status === 200) {
    return {
      props: { ...data },
    };
  } else {
    return {
      props: {
        data: [],
      },
    };
  }
}

在自定义组件“”内,我有一个按钮列表,用于将页面信息导出为 Excel、Json、CSV 和 PDF。我已经完成了前三个按钮,但我不知道从哪里开始将我的页面导出为 PDF。

The idea is to export it as it is, meaning that I want to have it with the same style it has with CSS and the Material UI components, for example, if the website looks like this: Website example

PDF 文件应该看起来像这样,我知道我可以将其制作为 Canva 并制作类似 Html > img > PDF 的内容,但我想允许用户选择 PDF 中页面的文本。

如果您能给我一些想法,我将非常感激!


利用木偶师 https://www.npmjs.com/package/puppeteer在服务器端可能是一个不错的选择。

人们可以创建一个nextjs 中的 API https://nextjs.org/docs/api-routes/introduction生成 PDF 并传回客户端。像下面这样的东西应该是一个很好的起点:

import { NextApiRequest, NextApiResponse } from 'next';
import puppeteer from 'puppeteer';


const saveAsPdf = async (url: string) => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto(url, {
      waitUntil: 'networkidle0'
    });

  const result = await page.pdf({
    format: 'a4',
  });
  await browser.close();

  return result;
};

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { url } = req.query; // pass the page to create PDF from as param

  res.setHeader(
    'Content-Disposition',
    `attachment; filename="file.pdf"`
  );
  res.setHeader('Content-Type', 'application/pdf');

  const pdf = await saveAsPdf(url as string);

  return res.send(pdf);
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 Nextjs 页面导出为 pdf? 的相关文章

随机推荐