跳過到頁腳內容
NODE 說明

d3 NPM(開發者的使用方法)

數據可視化是現代網頁開發的一個關鍵方面,幫助將複雜的數據集轉換為可理解和可操作的見解。 在各種可用的工具和庫中,D3.js(Data-Driven Documents)以其強大和靈活的方法,在數據從業者中脫穎而出,創建動態交互式圖表已有十年以上。 結合 D3.js 和 React,一個流行的 JavaScript 庫來構建用戶界面,您可以創建堅固、可維護且高效的數據可視化應用程序。

本文將指導您如何將 D3.js 與 React 集成,及其在數據可視化中如何發揮作用。 此外,我們還將重點介紹IronPDF PDF 生成庫以從網站 URL 生成 PDF 文件。

D3.js 是什麼?

D3.js 是一種 JavaScript 庫,充當生成動態、交互式數據驅動圖形可視化在網頁瀏覽器中的基礎構建塊。 它使用 HTML、SVG 和 CSS 通過各種類型的圖表和曲線圖將數據變為現實。D3 提供了一個強大的框架,用於將數據綁定到文檔對象模型(DOM),並對文檔應用數據驅動轉換,它被用作許多高級圖表庫的基礎。

React 是什麼?

React 是由 Facebook 構建的一個開源 JavaScript 庫。 它允許開發人員創建可重用的 UI 組件,效率地管理狀態,並在數據變更時更新 DOM。

設置您的環境

確保您的系統上已安裝 Node.js 和 npm。 如果沒有,您可以從官方Node.js網站下載並安裝它們。

步驟 1:創建一個新的 React 應用程序

首先,使用 Create React App 創建一個新的 React 應用程序,這是一個設置新 React 項目的工具,具有良好的默認配置。 您可以在終端中使用以下命令來完成此操作:

npx create-react-app d3-react-app
cd d3-react-app
npx create-react-app d3-react-app
cd d3-react-app
SHELL

步驟 2:安裝 D3.js

接下來,通過以下命令安裝 D3.js npm 包:

npm install d3
npm install d3
SHELL

創建一個簡單的柱狀圖

為了展示如何將 D3.js 用於 React,我們將創建一個簡單的柱狀圖。

步驟 1:設置組件

src文件夾中創建一個名為BarChart.js的新組件,並為該組件使用以下代碼:

// src/BarChart.js
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';

// BarChart component
const BarChart = ({ data }) => {
  const svgRef = useRef();

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const width = 500;
    const height = 300;
    const margin = { top: 20, right: 30, bottom: 40, left: 40 };

    // Set up the SVG dimensions
    svg.attr('width', width).attr('height', height);

    // Define the x scale
    const x = d3.scaleBand()
      .domain(data.map(d => d.name))
      .range([margin.left, width - margin.right])
      .padding(0.1);

    // Define the y scale
    const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .nice()
      .range([height - margin.bottom, margin.top]);

    // Define the x-axis
    const xAxis = g => g
      .attr('transform', `translate(0,${height - margin.bottom})`)
      .call(d3.axisBottom(x).tickSizeOuter(0));

    // Define the y-axis
    const yAxis = g => g
      .attr('transform', `translate(${margin.left},0)`)
      .call(d3.axisLeft(y))
      .call(g => g.select('.domain').remove());

    svg.append('g').call(xAxis);
    svg.append('g').call(yAxis);

    // Create bars
    svg.append('g')
      .selectAll('rect')
      .data(data)
      .join('rect')
      .attr('x', d => x(d.name))
      .attr('y', d => y(d.value))
      .attr('height', d => y(0) - y(d.value))
      .attr('width', x.bandwidth())
      .attr('fill', 'steelblue');
  }, [data]);

  return <svg ref={svgRef}></svg>;
};

export default BarChart;
// src/BarChart.js
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';

// BarChart component
const BarChart = ({ data }) => {
  const svgRef = useRef();

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const width = 500;
    const height = 300;
    const margin = { top: 20, right: 30, bottom: 40, left: 40 };

    // Set up the SVG dimensions
    svg.attr('width', width).attr('height', height);

    // Define the x scale
    const x = d3.scaleBand()
      .domain(data.map(d => d.name))
      .range([margin.left, width - margin.right])
      .padding(0.1);

    // Define the y scale
    const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .nice()
      .range([height - margin.bottom, margin.top]);

    // Define the x-axis
    const xAxis = g => g
      .attr('transform', `translate(0,${height - margin.bottom})`)
      .call(d3.axisBottom(x).tickSizeOuter(0));

    // Define the y-axis
    const yAxis = g => g
      .attr('transform', `translate(${margin.left},0)`)
      .call(d3.axisLeft(y))
      .call(g => g.select('.domain').remove());

    svg.append('g').call(xAxis);
    svg.append('g').call(yAxis);

    // Create bars
    svg.append('g')
      .selectAll('rect')
      .data(data)
      .join('rect')
      .attr('x', d => x(d.name))
      .attr('y', d => y(d.value))
      .attr('height', d => y(0) - y(d.value))
      .attr('width', x.bandwidth())
      .attr('fill', 'steelblue');
  }, [data]);

  return <svg ref={svgRef}></svg>;
};

export default BarChart;
JAVASCRIPT

步驟 2:使用組件

現在,在您的App.js文件中使用BarChart組件,並向其傳遞一些數據。

// src/App.js
import React from 'react';
import BarChart from './BarChart';

const App = () => {
  const data = [
    { name: 'A', value: 30 },
    { name: 'B', value: 80 },
    { name: 'C', value: 45 },
    { name: 'D', value: 60 },
    { name: 'E', value: 20 },
    { name: 'F', value: 90 },
    { name: 'G', value: 55 },
  ];

  return (
    <div className="App">
      <h1>Bar Chart</h1>
      <BarChart data={data} />
    </div>
  );
};

export default App;
// src/App.js
import React from 'react';
import BarChart from './BarChart';

const App = () => {
  const data = [
    { name: 'A', value: 30 },
    { name: 'B', value: 80 },
    { name: 'C', value: 45 },
    { name: 'D', value: 60 },
    { name: 'E', value: 20 },
    { name: 'F', value: 90 },
    { name: 'G', value: 55 },
  ];

  return (
    <div className="App">
      <h1>Bar Chart</h1>
      <BarChart data={data} />
    </div>
  );
};

export default App;
JAVASCRIPT

輸出

d3 NPM(對於開發者的工作原理):圖1 - 輸出的柱狀圖

介紹IronPDF

d3 NPM(對於開發者的工作原理):圖2 - IronPDF網頁

IronPDF是一個強大的 npm 包,專為 Node.js 應用程序內的 PDF 生成提供便利。 它在從 HTML 內容、URL 或現有 PDF 文件創建 PDF 文檔方面提供了無與倫比的靈活性。 無論是生成發票、報告或其他文檔,IronPDF 都通過其直觀的 API 和豐富的功能集簡化了這個過程。

IronPDF 的主要特點

  • HTML 到 PDF 轉換:輕鬆將 HTML 內容轉換為 PDF 文檔,非常適合從網絡內容生成動態 PDF。

  • URL 到 PDF 轉換:直接從 URL 創建 PDF,程式化地捕捉網頁內容並保存它們為 PDF 文件。

  • PDF 操作:輕鬆合併、拆分和操控現有的 PDF 文檔。 IronPDF 允許您附加頁面、拆分文檔等。

  • PDF 設置:通過用密碼加密或者應用數字簽名來保護您的 PDF 文檔,以防止未經授權的訪問。

  • 高品質輸出:生成高品質的 PDF 文檔,精確渲染文本、圖片和格式,確保與原始內容的一致性。

  • 跨平台兼容性:IronPDF 與多個平台兼容,包括 Windows、Linux 和 macOS,適用於多種開發環境。

  • 簡單集成:使用 npm 容易將 IronPDF 集成到您的 Node.js 應用程序中。 良好記錄的 API 使 PDF 生成功能整合到您的項目中變得簡單直接。

無論您是在構建 Web 應用程序、服務器端腳本、還是命令行工具,IronPDF 都能夠高效和可靠地創建專業級 PDF 文檔。

IronPDF 和 D3 npm 包:輕鬆實現 PDF 生成

安裝依賴項:首先,使用以下命令創建一個新的 Next.js 項目(如果還未創建):

npx create-next-app@latest d3charts-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest d3charts-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

接下來,導航至您的項目目錄:

cd d3charts-pdf
cd d3charts-pdf
SHELL

最後,安裝所需的包:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add d3
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add d3
SHELL

PDF 生成 API:第一步是創建一個後端 API 來生成 PDF 文檔。 由於 IronPDF 僅在服務器端運行,我們需要創建一個在用戶想要生成 PDF 時調用的 API。 在路徑pages/api/pdf.js創建一個文件並添加以下內容:

// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const url = req.query.url;
    const pdf = await PdfDocument.fromUrl(url);
    const data = await pdf.saveAsBuffer();
    console.error('data PDF:', data);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
    res.send(data);
  } catch (error) {
    console.error('Error generating PDF:', error);
    res.status(500).end();
  }
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    const url = req.query.url;
    const pdf = await PdfDocument.fromUrl(url);
    const data = await pdf.saveAsBuffer();
    console.error('data PDF:', data);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
    res.send(data);
  } catch (error) {
    console.error('Error generating PDF:', error);
    res.status(500).end();
  }
}
JAVASCRIPT

IronPDF 需要一個許可證密鑰,您可以從試用許可證頁面獲得,並將其放在上面的代碼中。

添加以下代碼以接受用戶的 URL,然後在index.js文件中從給定的 URL 生成 PDF。該代碼還展示了如何添加由 D3 生成的圖表和一個後端 API 以接受用戶的 URL。

// index.js
"use client";
import React, { useState } from 'react';
import D3BarChart from './d3BarChart';
import styles from "../../styles/Home.module.css";

export default function D3Demo() {
  const [text, setText] = useState("");
  const data = [
    { name: 'A', value: 30 },
    { name: 'B', value: 80 },
    { name: 'C', value: 45 },
    { name: 'D', value: 60 },
    { name: 'E', value: 20 },
    { name: 'F', value: 90 },
    { name: 'G', value: 55 },
  ];

  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text, {
        method: "GET",
      });
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <h1>Bar Chart</h1>
      <D3BarChart data={data} />
      <p>
        <span>Enter URL To Convert to PDF:</span>{" "}
        <input type="text" value={text} onChange={handleChange} />
      </p>
      <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
        Generate PDF
      </button>
    </div>
  );
}
// index.js
"use client";
import React, { useState } from 'react';
import D3BarChart from './d3BarChart';
import styles from "../../styles/Home.module.css";

export default function D3Demo() {
  const [text, setText] = useState("");
  const data = [
    { name: 'A', value: 30 },
    { name: 'B', value: 80 },
    { name: 'C', value: 45 },
    { name: 'D', value: 60 },
    { name: 'E', value: 20 },
    { name: 'F', value: 90 },
    { name: 'G', value: 55 },
  ];

  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text, {
        method: "GET",
      });
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <h1>Bar Chart</h1>
      <D3BarChart data={data} />
      <p>
        <span>Enter URL To Convert to PDF:</span>{" "}
        <input type="text" value={text} onChange={handleChange} />
      </p>
      <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
        Generate PDF
      </button>
    </div>
  );
}
JAVASCRIPT

請記住定義D3BarChart組件:

// d3BarChart.js
"use client";
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';

// D3BarChart component
export default function D3BarChart({ data }) {
  const svgRef = useRef(); // ref svg element

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const width = 500;
    const height = 300;
    const margin = { top: 20, right: 30, bottom: 40, left: 40 };

    // Set up the SVG dimensions
    svg.attr('width', width).attr('height', height);

    // Define the x scale
    const x = d3.scaleBand()
      .domain(data.map(d => d.name))
      .range([margin.left, width - margin.right])
      .padding(0.1);

    // Define the y scale
    const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .nice()
      .range([height - margin.bottom, margin.top]);

    // Define the x-axis
    const xAxis = g => g
      .attr('transform', `translate(0,${height - margin.bottom})`)
      .call(d3.axisBottom(x).tickSizeOuter(0));

    // Define the y-axis
    const yAxis = g => g
      .attr('transform', `translate(${margin.left},0)`)
      .call(d3.axisLeft(y))
      .call(g => g.select('.domain').remove());

    svg.append('g').call(xAxis);
    svg.append('g').call(yAxis);

    // Create bars
    svg.append('g')
      .selectAll('rect')
      .data(data)
      .join('rect')
      .attr('x', d => x(d.name))
      .attr('y', d => y(d.value))
      .attr('height', d => y(0) - y(d.value))
      .attr('width', x.bandwidth())
      .attr('fill', 'steelblue');
  }, [data]);

  return <svg ref={svgRef}></svg>;
}
// d3BarChart.js
"use client";
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';

// D3BarChart component
export default function D3BarChart({ data }) {
  const svgRef = useRef(); // ref svg element

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const width = 500;
    const height = 300;
    const margin = { top: 20, right: 30, bottom: 40, left: 40 };

    // Set up the SVG dimensions
    svg.attr('width', width).attr('height', height);

    // Define the x scale
    const x = d3.scaleBand()
      .domain(data.map(d => d.name))
      .range([margin.left, width - margin.right])
      .padding(0.1);

    // Define the y scale
    const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .nice()
      .range([height - margin.bottom, margin.top]);

    // Define the x-axis
    const xAxis = g => g
      .attr('transform', `translate(0,${height - margin.bottom})`)
      .call(d3.axisBottom(x).tickSizeOuter(0));

    // Define the y-axis
    const yAxis = g => g
      .attr('transform', `translate(${margin.left},0)`)
      .call(d3.axisLeft(y))
      .call(g => g.select('.domain').remove());

    svg.append('g').call(xAxis);
    svg.append('g').call(yAxis);

    // Create bars
    svg.append('g')
      .selectAll('rect')
      .data(data)
      .join('rect')
      .attr('x', d => x(d.name))
      .attr('y', d => y(d.value))
      .attr('height', d => y(0) - y(d.value))
      .attr('width', x.bandwidth())
      .attr('fill', 'steelblue');
  }, [data]);

  return <svg ref={svgRef}></svg>;
}
JAVASCRIPT

代碼說明:

  1. 我們創建了一個 Next.js 應用程序並添加了必要的包:IronPDF 和 D3。
  2. 然後,我們使用 D3 創建柱狀圖組件。
  3. 添加輸入和按鈕以生成 PDF 文檔。

輸出s

API:

d3 NPM(對於開發者的工作原理):圖3 - 包含 D3 柱狀圖的輸入部分

從這個 [IronPDF URL](/nodejs/) 生成的 PDF:

d3 NPM(對於開發者的工作原理):圖4 - 從用戶給定的 URL 生成的 PDF

IronPDF 授權

d3 NPM(對於開發者的工作原理):圖5 - IronPDF 授權頁面

IronPDF 試用許可證允許用戶在購買前檢查其豐富的功能。 有關永久許可的更多詳情,請查看IronPDF 許可頁面。

在此處放置許可證密鑰:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

結論

通過結合 D3.js 和 React,您可以利用這兩個庫的優勢,創建強大和交互式的數據可視化。 React 提供了一個構建用戶界面的強大框架,而 D3.js 提供了廣泛的數據處理和可視化功能。 使用 NPM 管理依賴項確保您的項目可維護和可擴展。 這個簡單柱狀圖的示例僅僅是個開始; 使用這些工具,您可以創建多種類型的專門針對您特定需求的複雜和互動的數據可視化。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。