跳至頁尾內容
USING IRONPDF FOR NODE.JS

如何在 Node.js 中從模板生成 PDF 文件

這篇文章將探討如何使用名為IronPDF for Node.js的PDF程式庫從HTML範本產生PDF文件的範例。

什麼是IronPDF for Node.js

IronPDF for Node.js是一款強大且多功能的工具,可無縫整合到Node.js中,使開發者能夠在其應用程式中輕鬆生成、操作和管理PDF文件。 通過其全面的功能集和直觀的API,IronPDF能夠讓開發者精簡他們的PDF製作相關任務,從建立視覺吸引的文件到新增互動元素,同時保持高度的控制和定制化。 無論是生成報告、發票或其他重要文件,IronPDF for Node.js提供了一個可靠且高效的解決方案,以無縫且對開發者友好的方式滿足各種PDF頁面生成需求。

IronPDF 特性

  1. 從HTML/CSS生成PDF:HTML和CSS來源生成PDF文件。 這允許您將網頁或HTML模板轉換為PDF格式。
  2. PDF操作和編輯通過在PDF文件中新增、移除或更新文字、圖片、註解和其他元素來編輯和修改現有的PDF。
  3. 合併和拆分PDF:合併多個PDF文件為一(合併)或將單個PDF拆分為多個較小的PDF
  4. 列印和表單處理:控制列印設置處理PDF中的互動表單,包括表單提交和驗證。
  5. 安全與加密實施安全措施,如密碼保護、加密、存取控制和數位簽名來保護PDF文件。
  6. 文字提取從PDF中提取文字和資料,使您可以在其他應用程式中使用內容或進行情況分析。
  7. 自定義:自定義PDF文件的外觀和佈局,包括頁面大小、字體、顏色、頁眉、頁腳和其他設計元素。
  8. 跨平台相容性:確保程式庫能與不同操作系統上的Node.js相容,對於在不同平台工作的開發者來說十分靈活。

安裝IronPDF for Node.js

本節將涵蓋如何安裝IronPDF for Node.js和設置Node.js項目。

在開始之前,確保您的系統上已安裝Node.js。

  1. 打開命令提示字元(CMD)並使用以下命令啟動一個新的Node.js專案:

    mkdir IronPDF   # Create a new directory for the project.
    
    cd IronPDF      # Navigate to the newly created directory.
    
    npm init -y     # Create a package.json file to store project-related metadata and dependencies.
    mkdir IronPDF   # Create a new directory for the project.
    
    cd IronPDF      # Navigate to the newly created directory.
    
    npm init -y     # Create a package.json file to store project-related metadata and dependencies.
    SHELL

    How to Generate A PDF File from Template in Node.js, Figure 1: Open the Command Prompt (CMD) and execute the command 打開命令提示字元(CMD)並執行命令

  2. 一旦初始設置完成,使用以下命令安裝IronPDF:

    npm install @ironsoftware/ironpdf
    npm install @ironsoftware/ironpdf
    SHELL
  3. 在Visual Studio Code中打開專案,並建立一個名為"index.js"的新文件。
  4. 打開package.json文件,並在"type"下新增以下行以啟用模組使用:

    "type": "module",

    How to Generate A PDF File from Template in Node.js, Figure 2: The sample package.json file 範例package.json文件

通過這些步驟,IronPDF for Node.js已成功安裝,並且環境已設置以運行IronPDF程式碼。

使用IronPDF for Node.js從HTML範本建立PDF

IronPDF for Node.js提供一項功能,允許使用者從HTML模板或HTML頁面建立PDF。 此功能使使用者能夠使用使用者提供的輸入填充這些範本。

下方提供的程式碼將展示如何使用HTML範本生成並撰寫PDF文件。

import { PdfDocument } from "@ironsoftware/ironpdf";
import readline from 'readline';

// Function to generate a PDF document based on user input and an HTML template
const generatePdf = async (userInput, fileName) => {
  // HTML template with placeholders for dynamic content
  const htmlTemplate = `
<!DOCTYPE html>
  <html>
  <body>
    <h1>${userInput.title}</h1>
    <p>User's name: ${userInput.userName}</p>
    <p>User's email: ${userInput.userEmail}</p>
  </body>
  </html>
`;

  // Create a PDF from the modified HTML template
  const pdf = await PdfDocument.fromHtml(htmlTemplate);

  // Save the PDF document under the specified file name
  await pdf.saveAs(fileName);
  console.log(`PDF saved as ${fileName}`);
};

// Create an interface for reading data from the terminal
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Collect user input for the PDF document
rl.question('Enter title: ', (title) => {
  rl.question('Enter user name: ', (userName) => {
    rl.question('Enter user email: ', async (userEmail) => {
      // Store user-provided data in an object
      const userInput = {
        title,
        userName,
        userEmail
      };

      // Generate the PDF using the user input
      await generatePdf(userInput, "output.pdf");

      // Close the readline interface
      rl.close();
    });
  });
});
import { PdfDocument } from "@ironsoftware/ironpdf";
import readline from 'readline';

// Function to generate a PDF document based on user input and an HTML template
const generatePdf = async (userInput, fileName) => {
  // HTML template with placeholders for dynamic content
  const htmlTemplate = `
<!DOCTYPE html>
  <html>
  <body>
    <h1>${userInput.title}</h1>
    <p>User's name: ${userInput.userName}</p>
    <p>User's email: ${userInput.userEmail}</p>
  </body>
  </html>
`;

  // Create a PDF from the modified HTML template
  const pdf = await PdfDocument.fromHtml(htmlTemplate);

  // Save the PDF document under the specified file name
  await pdf.saveAs(fileName);
  console.log(`PDF saved as ${fileName}`);
};

// Create an interface for reading data from the terminal
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Collect user input for the PDF document
rl.question('Enter title: ', (title) => {
  rl.question('Enter user name: ', (userName) => {
    rl.question('Enter user email: ', async (userEmail) => {
      // Store user-provided data in an object
      const userInput = {
        title,
        userName,
        userEmail
      };

      // Generate the PDF using the user input
      await generatePdf(userInput, "output.pdf");

      // Close the readline interface
      rl.close();
    });
  });
});
JAVASCRIPT

上面的程式碼範例定義了一個JavaScript程式,通過使用readline模塊的命令行獲取使用者輸入以獲取標題、使用者名和使用者電子郵件。 定義generatePdf()方法以使用提供的HTML範本建立PDF文件,並以給定的文件名保存。 HTML範本包含標題、使用者名和使用者電子郵件的佔位符,這些佔位符將填入使用者提供的資料。 PdfDocument類來自@Iron Software/ironpdf套件,用於從HTML範本建立PDF。 生成PDF後,會以指定的文件名保存,並在控制台上記錄確認保存的消息。

使用readline模組提示使用者輸入相關的資料,依序詢問標題、使用者名和使用者電子郵件。 對這些提示的使用者回應被收集並儲存在一個名為userInput的物件中。 然後使用此使用者輸入和預設文件名"output.pdf"調用generatePdf()方法,以基於提供的資料建立和保存或下載PDF文件。 最後,readline介面關閉,結束程式。

PDF生成測試#1

How to Generate A PDF File from Template in Node.js, Figure 3: The Console output 控制台輸出

How to Generate A PDF File from Template in Node.js, Figure 4: The output.pdf The output.pdf

PDF生成測試#2

How to Generate A PDF File from Template in Node.js, Figure 5: The Console output 控制台輸出

How to Generate A PDF File from Template in Node.js, Figure 6: The output.pdf file output.pdf文件

結論

本教程揭示了利用Node.js將動態資料與預定義範本合併以輕鬆生成PDF的過程,強調了IronPDF的重要角色。

IronPDF for Node.js與Node.js無縫整合,使開發者能夠有效地建立、操作和管理PDF文件,提供全面的功能集,如從HTML/CSS生成PDF、編輯現有PDF文件、合併/拆分它們、處理表單、確保安全性、啟用文字提取和自定義。

逐步的安裝過程和實際範例展示了如何在Node.js項目中有效實現IronPDF。 透過無縫整合基於範本的PDF生成,開發者可以有效地滿足各種文件生成需求,使Node.js和IronPDF成為一個強大的組合,用於精簡且對開發者友好的PDF生成。 這一相同技術可以用於動態生成發票。

您可以在以下npm網頁上安裝IronPDF for Node.js並找到程式碼範例。

IronPDF提供免費試用授權,因此使用者可以在購買之前試用IronPDF提供的所有功能。 欲獲取更多資訊,請存取IronPDF授權頁面

常見問題

如何在Node.js中從HTML範本生成PDF?

您可以使用IronPDF在Node.js中從HTML範本生成PDF。通過利用其PdfDocument類,您可以填充包含動態資料的HTML範本並將其轉換為PDF文件。

在Node.js環境中安裝IronPDF需要哪些步驟?

要在Node.js環境中安裝IronPDF,首先確認已安裝Node.js,然後使用npm啟動一個新專案,並運行npm install @ironsoftware/ironpdf以將IronPDF新增到您的專案中。

IronPDF為Node.js開發者提供了哪些功能?

IronPDF提供的功能包括從HTML/CSS生成PDF,編輯PDF,合併和拆分文件,表單處理,文字提取,安全和加密,以及自定義選項。

IronPDF如何增強Node.js應用程式中的PDF文件建立?

IronPDF通過提供一個強大的API來增強Node.js應用程式中的PDF文件建立,使開發者能夠輕鬆生成、操作和管理PDF。這包括從HTML範本生成動態文件,如發票。

IronPDF可以在不同的作業系統上使用嗎?

可以,IronPDF相容多個作業系統,為從事多平台工作的開發者提供了靈活性。

在PDF生成範例中'讀取'模組的用途是什麼?

範例程式碼中的'讀取'模組用於收集使用者輸入,如標題和使用者名,然後用來填充PDF生成的HTML範本。

是否有免費試用版來測試IronPDF的功能?

IronPDF提供免費試用授權,使使用者可以探索其功能和特性後再進行購買。

IronPDF如何處理PDF的安全和加密?

IronPDF提供了增加PDF安全和加密的功能,確保文件受到保護並按照要求控制存取。

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant擁有邁阿密大學的電腦科學學士學位,並在Iron Software擔任全端WebOps行銷工程師。從小就對程式設計有興趣,他認為計算既神秘又易於理解,成為創意和問題解決的完美媒介。

在Iron Software,Darrius喜歡創造新事物並簡化複雜的概念,使其更易於理解。作為我們的常駐開發人員之一,他還志願教學,將他的專業知識傳授給下一代。

對Darrius來說,他的工作是有意義的,因為它有價值且對社會有真正的影響。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話