執行自訂 JavaScript
import {PdfDocument} from "@ironsoftware/ironpdf";

(async () => {
    // Define the JavaScript code to change text color to red
    const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){el.style.color='red';})";

    // Create rendering options object
    const renderOptions = {
        enableJavaScript: true,
        javascript: javascriptCode,
    };

    // HTML content to be rendered
    const htmlContent = "<h1>Happy New Year!</h1>";

    // Render HTML content to a PDF
    const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions: renderOptions });

    // Save the PDF with the executed JavaScript
    await pdf.saveAs("executed_js.pdf");
})();
npm i @ironsoftware/ironpdf
執行自訂 JavaScript

執行自訂 JavaScript

使用IronPDF,輕鬆地使用JavaScript程式碼修改HTML內容的外觀。 IronPDF是Iron Software產品程式庫的一部分,以其在支援JavaScript、CSS等轉換HTML到PDF時的強大功能而聞名。

要實現這一點,首先定義JavaScript程式碼。 在我們的例子中,我們將所有H1標籤的文字顏色更改為紅色。

接下來,建立一個渲染選項物件,並將enableJavaScript屬性設置為true。 將先前定義的JavaScript程式碼分配給此物件中的javascript屬性。

使用PdfDocument.FromHtml方法將HTML內容渲染為PDF文件。 將renderOptions物件作為第二個參數傳遞。

最後,將生成的PDF保存為'incorporates the effects of the executed JavaScript code (changing text color to red)',命名為'executed_js.pdf'。

欲了解更多有關IronPDF或其他Iron Software程式庫(如IronBarcode、IronOCR等)的功能,請造訪Iron Software的官方網站。

立即探索執行自定義JavaScript程式碼範例!
在 GitHub 上查看

準備好開始了嗎?

版本:2026.11剛剛發布