跳過到頁腳內容
NODE 說明

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

數據可視化是現代網頁開發中一個關鍵的面向,有助於將複雜的數據集轉化為易於理解和可行的見解。 在各種可用的工具和程式庫中,D3.js(數據驅動文件)以其強大和靈活的方法脫穎而出,十多年來在數據從業者中創建動態和互動圖形。 當將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:設置組件

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:使用組件

現在,在您的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生成功能納入您的項目變得直截了當。

無論您是在構建網頁應用程式、伺服器端腳本還是命令行工具,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需要授權金鑰,您可以從試用授權頁面獲取並將其放置在上述代碼中。

添加以下代碼以接受來自用戶的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創建了BarChart組件。
  3. 添加輸入和按鈕來生成PDF文件。

輸出

API:

d3 NPM(對於開發者的運作方式):圖3 - D3條形圖輸入部分

從此IronPDF URL生成的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 來說,工作令人滿意因為它被重視且有實際影響。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me