[]
        
(Showing Draft Content)

Bun

Updated 3/06/2026.

What is Bun?

Bun is a fast all-in-one JavaScript runtime. It combines package manager, test runner, and bundler with Node.js compatibility.

Prerequisites

  • Node.js (version 16 or higher)

  • npm (version 7 or higher)

  • Bun installed

  • A code editor (VS Code recommended)

  • Basic knowledge of JavaScript and modern runtimes (Node.js/Bun)

Installation

Install Bun:

npm install -g bun

Verify installation:

bun --version

Working Example

Step 1 — Create a Project

mkdir dspdf-bun-demo
cd dspdf-bun-demo
bun init -y

Step 2 — Install DsPdfJS

bun add @mescius/ds-pdf

Step 3 — Create bun-pdf-example.mjs

// bun-pdf-example.mjs
// Example: Generate a PDF file in Bun using @mescius/ds-pdf (ESM + npm)

import path from "path";
import { fileURLToPath } from "url";
import { connectDsPdf, DsPdfConfig, ObjectManager, PdfDocument } from "@mescius/ds-pdf";

// Resolve the current file and directory (ESM replacement for __dirname)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Configure the absolute path to the DsPdf.wasm file.
// In Bun (non-browser environment), you must explicitly specify the WASM location.
const wasmPath = path.resolve(
  __dirname,
  "node_modules/@mescius/ds-pdf/assets/DsPdf.wasm"
);
DsPdfConfig.wasmUrl = wasmPath;

// Main function that creates and saves a PDF document
async function createPdf() {
  console.log("🚀 Starting PDF generation in Bun...");

  // Initialize the DsPdfJS runtime (loads and connects to the WASM module)
  const connected = await connectDsPdf();
  if (!connected) {
    throw new Error("Failed to initialize DsPdfJS.");
  }

  // Create an ObjectManager instance (required for managing PDF resources)
  const om = new ObjectManager();

  try {
    // Create a new PDF document
    const doc = new PdfDocument(om);

    // Create a new page context for drawing content
    const page = doc.newPageContext();

    // Draw text on the page at coordinates (x: 50, y: 50)
    page.drawText(
      {
        text: "Hello from Bun!",
        fontSize: 18,
        foreColor: "DarkBlue",
      },
      50,
      50
    );

    // Save the PDF and obtain the binary data
    const pdfData = doc.savePdf();

    // Convert ArrayBuffer to a Node-compatible Buffer
    const buffer = Buffer.from(pdfData.buffer || pdfData);

    // Save the file using Bun's native file system API
    await Bun.write("bun-example.pdf", buffer);

    console.log("✅ bun-example.pdf created successfully!");
  } finally {
    // Always dispose ObjectManager to release WASM resources
    om.dispose();
  }
}

// Execute the PDF generation function
createPdf().catch(console.error);

Step 4 — Run the Example

bun run bun-pdf-example.mjs

Open your folder — you should see bun-example.pdf containing the text:

Hello from Bun!

Project Structure

dspdf-bun-demo/
├── node_modules/
├── package.json
├── bun.lock
└── bun-pdf-example.mjs