簡體   English   中英

如何添加前端按鈕以觸發pdfcrowd的node.js API以生成PDF

[英]How to add front-end button to trigger pdfcrowd's node.js API to generate PDFs

我有一個MERN-stack應用程序,並且我試圖使用pdfcrowd允許我的應用程序的用戶下載我應用程序頁面的PDF。

在我的Node APIs 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以重新啟動節點時,便成功創建了pdf文件。 但是,我不想在node index.js上創建pdf文件,而是希望在應用程序的前端(在我的React代碼中)有一個按鈕,單擊該按鈕可以生成PDF。

我以前從未使用過pdfcrowd ,並且對React或Node中的任何pdf代都不熟悉,並且不確定如何處理此問題。 例如,按鈕的onClick處理函數必須具有什么樣的外觀,才能調用后端的pdfcrowd代碼以生成文件。

編輯:我想我將使用convertFileToFile函數而不是convertUrlToFile函數,因為我想在我的應用程序中使用本地路由。

Edit2:我假設convertFileToFile使用本地節點路由,而不是我的convertFileToFile路由。 因此,我不確定如何擴展此代碼的功能,以從我的應用程序的各種頁面創建PDF頁面。

任何幫助,我們將不勝感激!

嘗試這樣的事情:

在您的html中放置一個按鈕,該按鈕將調用您的節點后端功能,並在前端返回響應時嘗試:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM