如何在 JavaScript 中創建 PDF 文件
在文件共享領域,由 Adobe 首創的便攜式文件格式 (PDF) 在保持富含文字且視覺效果吸引人的內容的完整性方面發揮著至關重要的作用。 在線訪問PDF文件通常需要專門的程序。 在當今的數位環境中,PDF 文件已成為各種重要出版物不可或缺的一部分。 許多企業依靠PDF文件來創建專業文件和發票。 此外,開發人員經常利用 PDF 建立庫來滿足客戶的特定需求。 隨著現代圖書館的出現,生成 PDF 的過程也得到了簡化。 在為涉及 PDF 生成的專案選擇最合適的程式庫時,必須考慮建置、讀取和轉換功能等因素,以確保無縫整合和最佳效能。
JavaScript 函式庫
例如,假設我們希望客戶能夠輕鬆下載和列印我們的 PDF 發票副本。 此外,保持發票的精確佈局和確保完美的列印品質對我們來說至關重要。
在本節中,我們將深入探討一系列備受推崇的 JavaScript 程式庫,這些程式庫擅長將 HTML 轉換為 PDF 文檔,為我們提供了高效、準確的文檔生成和轉換的多功能工具。
1.PDFKit
PDFKit 是一個 PDF 函式庫,它是最早進入龐大的 JavaScript 函式庫生態系統的函式庫之一。 自 2012 年首次發布以來,它的受歡迎程度顯著提高,截至 2021 年,它仍在定期進行升級。
PDFKit 使用 Webpack,同時支援 Node 庫和 Web 瀏覽器,並支援自訂字體和圖像嵌入。
但是,正如我們將在比較中看到的那樣,一些 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 to trigger PDF creation and printing -->
<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 to trigger PDF creation and printing -->
<button onclick="CreatePdf()">Print pdf</button>
</body>
</html>3.IronPDF。
IronPDF 的建立旨在讓開發人員更容易建立、瀏覽和編輯 PDF 文件。 它是一款功能強大的 PDF 轉換器,並提供用於建立、編輯和處理 PDF 文件的基礎 API。
IronPDF for Node.js 簡化了以程式設計方式建立和自訂 PDF 文件的過程。 IronPDF 由高效能文件處理庫的可靠提供者 Iron Software 開發,為在 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");
})();您也可以執行自訂 JavaScript ,輕鬆修改 HTML 內容的外觀:
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 天退款保證、一年軟體支援和升級選項。 除了初始購買費用外,沒有其他費用。





