跳過到頁腳內容
NODE 說明

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

資料視覺化是現代網路開發的關鍵方面,它有助於將複雜的資料集轉化為可理解和可操作的見解。 在眾多可用的工具和函式庫中, D3.js (資料驅動文件)憑藉其強大而靈活的方式,在資料從業者中創建動態和互動式圖表,十多年來一直備受青睞。 將 D3.js 與 React(一個流行的用於建立使用者介面的 JavaScript 庫)結合使用,可以創建強大、易於維護且高效的資料視覺化應用程式。

本文將指導您如何將 D3.js 與 React 集成,以及它如何幫助實現資料視覺化。 此外,我們還將研究IronPDF PDF 生成庫,以便根據網站 URL 生成 PDF 文件。

什麼是D3.js?

D3.js是一個 JavaScript 函式庫,它作為基礎建構模組,用於在 Web 瀏覽器中產生動態、互動的資料驅動圖形視覺化。 它使用 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 文檔,非常適合從 Web 內容產生動態 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 只能在伺服器端運行,我們需要建立一個 API,以便在使用者想要產生 PDF 時呼叫。 在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 需要許可證金鑰,您可以從試用許可證頁面取得該金鑰並將其放入上面的程式碼中。

index.js檔案中加入以下程式碼,使其能夠接收使用者輸入的 URL,並根據該 URL 產生 PDF 檔案。程式碼也展示如何新增一個 D3 產生的圖表和一個接收使用者 URL 的後端 API。

// 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 來建立 BarChart 組件。
  3. 新增輸入框和按鈕以產生 PDF 文件。

輸出

API:

! d3 NPM(開發者使用指南):圖 3 - 帶有 D3 長條圖的輸入部分

由此生成的 PDF IronPDF網址:

! 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 來說,工作令人滿意因為它被重視且有實際影響。