gpt4 book ai didi

javascript - 如何添加前端按钮来触发pdfcrowd的node.js API生成PDF

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:03 25 4
gpt4 key购买 nike

我有一个 MERN-stack 应用程序,我正在尝试使用 pdfcrowd允许我的应用程序的用户下载我的应用程序页面的 PDF。

在我的 Node API index.js 文件中,我添加了 pdfcrowd 文档中的示例:

var pdfcrowd = require("pdfcrowd");

// create the API client instance
var client = new pdfcrowd.HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");

// run the conversion and write the result to a file
client.convertUrlToFile(
"http://www.example.com",
"example.pdf",
function(err, fileName) {
if (err) return console.error("Pdfcrowd Error: " + err);
console.log("Success: the file was created " + fileName);
});

...当我从终端运行 node index.js 来重新启动 Node 时,pdf 文件已成功创建。但是,我不想在 node index.js 上创建 pdf 文件,而是希望在应用程序的前端(在我的 React 代码中)有一个按钮,单击该按钮即可生成 PDF。

我以前从未使用过pdfcrowd,并且对react或node中的任何pdf生成都很陌生,并且不知道如何处理这个问题。例如,按钮的 onClick 处理函数必须是什么样子,才能调用后端的 pdfcrowd 代码来生成文件。

编辑:我想我会使用 convertFileToFile 函数而不是 convertUrlToFile 函数,因为我想在我的应用程序中使用本地路由。

Edit2: 我假设 convertFileToFile 使用本地 Node 路由,而不是我的 react 路由。因此,我不确定如何扩展此代码的功能以从我的应用程序的各种页面创建 PDF 页面。

非常感谢任何有关此问题的帮助!

最佳答案

尝试这样的事情:

在 html 中放置一个按钮,该按钮将调用 Node 后端函数并在前端尝试获取响应:

var fileName="MyPdfFile.pdf";
var blob = new Blob([responseData], 'application/pdf');
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = window.URL.createObjectURL(blob);
tempLink.setAttribute('download', fileName);
tempLink.click();

使用 Blob 时请注意响应数据类型并使用正确的格式。您还可以使用像“blob-util”这样的库,它提供了许多用于数据转换的默认函数。我用它来将我的数据从 base64 字符串转换为 blob。

关于javascript - 如何添加前端按钮来触发pdfcrowd的node.js API生成PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com