如何将 Nextjs 页面导出为 pdf?

问题描述 投票:0回答:3

我的页面上有以下结构:

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。

我们的想法是按原样导出,这意味着我希望它具有与 CSS 和 Material UI 组件相同的样式,例如,如果网站如下所示:

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

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

javascript reactjs pdf next.js export-to-pdf
3个回答
4
投票

在服务器端使用 puppeteer 可能是一个不错的选择。

可以在 nextjs 中创建一个 API 来生成 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);
};

3
投票

有几种方法可以做到这一点

  1. NPM 服务器端模块 - 更多选项 可能
  2. 客户端 PDF 对象形成,许多挑战 - 客户端依赖项
  3. 使用服务 - 费用

对于#1 - 尝试类似的东西 - https://www.npmjs.com/package/html-pdf?activeTab=readme

对于 #2 - https://github.com/parallax/jsPDF

对于 #3 - https://www.htmlpdfapi.com/


0
投票

您可以使用react-to-pdf https://github.com/ivmarcos/react-to-pdf这有助于使用react和next js轻松生成pdf。但你也可以尝试 jsPDF。

© www.soinside.com 2019 - 2024. All rights reserved.