在next js中下载PDF

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

我在尝试在下一个 js 应用程序中下载 pdf 文件时遇到问题。 基本上我想下载放置在下一个js应用程序的公共文件夹中的pdf文件,但它给出错误“文件在站点上不可用”。这是代码。

code of button and utility function used to download pdf file

按钮代码:

"use client";

// utility functions
import downloadPDF from "@/utils/downloadPDF";

// components
import Button from "@/components/common/Button";

// import resume from "../../public/resume.pdf";

const ResumeButton = () => {
  const resumeClick = (e) => {
    e.preventDefault();
    // window.open("../../public/resume.pdf", "_blank");

    downloadPDF("../../public/resume.pdf", "HaroonAhmed.pdf");
  };
  return (
    <Button
      bgColor="bg-lime-600"
      textColor="text-white"
      className="my-4"
      handleClick={resumeClick}
    >
      Download Resume
    </Button>
  );
};

export default ResumeButton;

下载文件的实用功能

const downloadPDF = (url, filename) => {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export default downloadPDF;

我尝试使用 window.open("../../public/resume.pdf", "_blank"); 在新选项卡中打开 pdf以及pdf下载功能,但这两种方式都面临同样的错误。文件未找到。如果其中一种方法有效,我会很高兴。

javascript reactjs pdf download
1个回答
0
投票

您遇到的问题可能是由于您在 Next.js 应用程序中引用 PDF 文件的方式造成的。公共文件夹中的文件由根 URL 提供,与 JavaScript 文件或组件无关。因此,在尝试访问这些文件时,您不需要在路径中包含 ../../public/。

解决方案 要解决此问题,您应该使用站点根目录的绝对路径引用 PDF 文件,假设resume.pdf 直接位于公共文件夹内。这意味着您应该使用 /resume.pdf 而不是 ../../public/resume.pdf。

以下是调整 ResumeButton 组件和 downloadPDF 实用功能的方法:

调整了 ResumeButton 组件:

const ResumeButton = () => {
  const resumeClick = (e) => {
    e.preventDefault();
    // Use an absolute path from the root
    downloadPDF("/resume.pdf", "HaroonAhmed.pdf");
  };
  return (
    <Button
      bgColor="bg-lime-600"
      textColor="text-white"
      className="my-4"
      handleClick={resumeClick}
    >
      Download Resume
    </Button>
  );
};

导出默认的ResumeButton; 下载PDF实用功能(无需更改):

您的 downloadPDF 函数应该可以正常工作,前提是传递给它的 URL 是正确的:

const downloadPDF = (url, filename) => {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

导出默认下载PDF; 附加说明 对于 window.open 方法,您还应该使用正确的路径:

window.open("/resume.pdf", "_blank");

此更改可确保您的应用程序正确指向公共文件夹中的 PDF 文件,从而允许您的用户按预期下载或查看文件。

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