如何在 JavaScript 中創建 PDF 文件
在文件共享領域中,由Adobe首創的可攜式文件格式(PDF)在保持文本豐富和視覺吸引力內容的完整性方面發揮了至關重要的作用。 線上訪問PDF檔通常需要專用程式。 在當今的數位環境中,PDF檔已成為各種重要出版物不可或缺的存在。 許多企業依賴PDF檔來製作專業文件和發票。 此外,開發人員常利用PDF創建庫來滿足特定客戶需求。 隨著現代化程式庫的出現,生成PDF的過程已得到簡化。 在選擇適合的程式庫來進行涉及PDF生成的專案時,考慮構建、讀取和轉換能力等因素至關重要,以確保無縫整合和最佳性能。
JavaScript程式庫
例如,我們希望客戶可以輕鬆下載並列印我們的PDF發票副本。 此外,保持發票的精確佈局並確保無瑕疵的列印質量對我們至關重要。
在本節中,我們將深入探討一系列備受推崇的JavaScript程式庫,這些程式庫在將HTML轉換為PDF文件中表現優異,為我們提供多功能工具來高效和準確地進行文件生成和轉換。
1. PDFKit
PDFKit是首批推出到廣泛JavaScript庫生態系統中的PDF庫之一。 自2012年首次發布以來,其受歡迎程度顯著增長,截至2021年仍在定期升級。
使用Webpack,PDFKit提供對Node library和網頁瀏覽器的支援,並支援自定義字型和圖像嵌入。
然而,正如我們在比較中將看到的,有些PDF庫實際上只是PDFKit的封裝,可能比PDFKit更容易使用。
PDFKit沒有高階API。 文件通常也很難理解。 正如您可能預期的,那裡使用起來需要一些時間熟悉,您可能會發現使用JavaScript生成PDF並不總是輕而易舉的工作。
// Requiring the necessary modules for file system and PDF document creation.
const fs = require('fs');
const PDFDocument = require('pdfkit');
// Create a new PDF document instance
const doc = new PDFDocument();
// Add text content to the PDF document
doc.text('Hello world!');
// Define the output file location and start writing the PDF content to it
doc.pipe(fs.createWriteStream('Demo.pdf'));
// Finalize the PDF file
doc.end();// Requiring the necessary modules for file system and PDF document creation.
const fs = require('fs');
const PDFDocument = require('pdfkit');
// Create a new PDF document instance
const doc = new PDFDocument();
// Add text content to the PDF document
doc.text('Hello world!');
// Define the output file location and start writing the PDF content to it
doc.pipe(fs.createWriteStream('Demo.pdf'));
// Finalize the PDF file
doc.end();2. pdfmake
與使用傳統命令式方法生成內容的PDFKit不同,pdfmake採用了聲明式方法。 因此,使用pdfmake程式庫使得更容易集中於PDF生成的預期功能,而不是浪費時間教程式庫如何完成某個結果。
需要謹記,儘管某些解決方案可能看似有前景,但它們可能並不完美。 一個例子是在使用Webpack時將自定義字型與pdfmake整合,這可能會導致問題。 遺憾的是,關於此特定問題的線上文件有限。 然而,如果您未使用Webpack,您可以輕鬆克隆Git庫,並執行字型嵌入腳本,以克服與自定義字型整合相關的潛在障礙。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
</head>
<body>
<script type="text/javascript">
// Function to create and print a PDF document
function CreatePdf() {
// Define document content and styles
var docDefinition = {
content: [
{ text: "Hello world" } // Text content to be included in the PDF
],
defaultStyle: {}
};
// Create and print the PDF using pdfMake library
pdfMake.createPdf(docDefinition).print();
}
</script>
<button onclick="CreatePdf()">Print pdf</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
</head>
<body>
<script type="text/javascript">
// Function to create and print a PDF document
function CreatePdf() {
// Define document content and styles
var docDefinition = {
content: [
{ text: "Hello world" } // Text content to be included in the PDF
],
defaultStyle: {}
};
// Create and print the PDF using pdfMake library
pdfMake.createPdf(docDefinition).print();
}
</script>
<button onclick="CreatePdf()">Print pdf</button>
</body>
</html>
3. IronPDF
IronPDF旨在助開發者輕鬆創建、瀏覽和編輯PDF文件。 它作為功能強大的PDF轉換器,提供創建、編輯和處理PDF文件的基本API。
IronPDF for Node.js簡化了通過程式生成和自定義PDF文件的過程。 這是由可靠的高性能文件處理程式庫供應商Iron Software開發,IronPDF為Node.js環境內的PDF生成提供了強大的解決方案。 它能夠與Node.js專案無縫整合,為開發者提供強大的工具,輕鬆生成、格式化和編輯PDF。
IronPDF程式庫具有一系列豐富功能,包括能夠在新的或現有PDF文件中拆分和合併頁面,讀取和編輯現有PDF文件,從PDF文件中提取圖像,向PDF文件添加文本、圖形、書籤、水印、標頭和頁腳,這一切都不需要Acrobat Reader。 從CSS和CSS媒體文件中可以產生PDF文件。 IronPDF允許使用者創建、上傳和更新新和現有的PDF表單。
IronPDF for Node.js的主要功能:
- 多樣化的PDF生成:使用IronPDF,開發者可以從各種來源生成PDF,包括HTML、CSS、JavaScript、圖像和其他檔案類型。這種靈活性使得能夠創建符合特定需求的動態且視覺吸引力的PDF文件。
- 進階文件自定義:IronPDF使開發者能夠通過功能如標頭、頁腳、附件、數位簽名、水印和書籤來增強PDF文件。 這允許創建具有豐富內容和互動元素的專業級PDF。
- 安全功能:IronPDF提供強大的安全功能來保護PDF不受未經授權的訪問。 開發者可以實施安全措施如密碼、數位簽名、中繼資料和其他安全設置,以保護PDF文件中包含的敏感信息。
- 優化的性能:IronPDF針對最佳性能設計完全支援多線程和異步操作。 這確保了高效的PDF生成,使其適合需要高性能的關鍵任務應用。
- 全面的功能集:IronPDF提供了超過50種功能,用於創建、格式化和編輯PDF文件,是所有PDF相關任務的全面解決方案。 從基礎文件生成到高級自定義和安全,IronPDF提供了滿足開發者需求的眾多能力。
以下代碼示例說明瞭如何使用JavaScript將HTML轉換為像素完美的PDF檔:
import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// HTML content containing JavaScript to be executed upon rendering
const htmlWithJavaScript = `<h1>This is HTML</h1>
<script>
document.write('<h1>This is JavaScript</h1>');
window.ironpdf.notifyRender(); // Notify IronPDF when rendering is done
</script>`;
// Rendering options to enable JavaScript
const renderOptions = {
enableJavaScript: true,
};
// Render HTML content to a PDF
const pdf = await PdfDocument.fromHtml(htmlWithJavaScript, { renderOptions });
// Save the PDF to a file
await pdf.saveAs("javascript-in-html.pdf");
})();import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// HTML content containing JavaScript to be executed upon rendering
const htmlWithJavaScript = `<h1>This is HTML</h1>
<script>
document.write('<h1>This is JavaScript</h1>');
window.ironpdf.notifyRender(); // Notify IronPDF when rendering is done
</script>`;
// Rendering options to enable JavaScript
const renderOptions = {
enableJavaScript: true,
};
// Render HTML content to a PDF
const pdf = await PdfDocument.fromHtml(htmlWithJavaScript, { renderOptions });
// Save the PDF to a file
await pdf.saveAs("javascript-in-html.pdf");
})();您還可以執行能夠輕鬆修改HTML內容外觀的自定義JavaScript:
import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// JavaScript code to change the text color of header tags to red
const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){ el.style.color = 'red'; })";
// HTML content which will be affected by the custom JavaScript
const htmlContent = "<h1>Happy New Year!</h1>";
// Rendering options to enable and apply the custom JavaScript
const renderOptions = {
enableJavaScript: true,
javascript: javascriptCode,
};
// Render HTML content to a PDF
const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions });
// Save the PDF with the applied JavaScript effects
await pdf.saveAs("executed_js.pdf");
})();import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// JavaScript code to change the text color of header tags to red
const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){ el.style.color = 'red'; })";
// HTML content which will be affected by the custom JavaScript
const htmlContent = "<h1>Happy New Year!</h1>";
// Rendering options to enable and apply the custom JavaScript
const renderOptions = {
enableJavaScript: true,
javascript: javascriptCode,
};
// Render HTML content to a PDF
const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions });
// Save the PDF with the applied JavaScript effects
await pdf.saveAs("executed_js.pdf");
})();
當我們點擊下載按鈕時,它會像上圖的PDF頁面顯示那樣下載PDF文件。 創建的PDF文件將如下所示。

結論
應該註意的是,當其他人使用時,上述JavaScript代碼可能會被濫用和引發安全問題。 在將此類代碼置於網頁或網站時,考慮未經授權的訪問和數據安全漏洞等風險至關重要。此外,還需考慮支持可能沒有所有必要功能的過時瀏覽器以及各系統和瀏覽器的不兼容問題。
IronPDF不僅可用於Node.js,還可用於其他受歡迎的平台,包括.NET、Java和Python。 這種跨平台的可用性為跨不同技術堆疊工作的開發者確保了一致性和靈活性。 憑藉其豐富的功能集、無縫整合和強大的性能,IronPDF是一個具有 開發者尋求在其Node.js專案中簡化PDF生成的寶貴工具。
為滿足不同開發者需求,該程式庫提供多種授權選擇,包括一個免費試用授權和其他可供購買的開發者授權。 $799 Lite套件隨附永久授權、30天退款保障、一年軟體支持和升級選項。 初次購買之外不會再有額外費用。







