Skip to content

YouvenZ/D2_ink

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

D2 Diagram Generator for Inkscape

Inkscape D2 License

Create declarative diagrams in Inkscape using D2's modern diagramming language

Transform simple text descriptions into beautiful, professional diagrams directly within Inkscape. D2 offers a cleaner syntax than traditional tools, with automatic layout algorithms and stunning visual output.


πŸ“‹ Table of Contents

  • Demo
  • Features
  • Why D2?
  • Requirements
  • Installation
  • Quick Start
  • Usage Guide
  • Configuration
  • Examples
  • Troubleshooting
  • Contributing
  • License

πŸ“Ί Demo

Watch the Demo

Click to watch the full tutorial on YouTube

✨ Features

  • πŸ“Š Full D2 Support

    • All diagram types and features
    • Native SVG output for full editability
    • High-quality PNG export option
  • 🎨 Professional Styling

    Feature Description
    8 Themes From neutral to colorful options
    Sketch Mode Hand-drawn aesthetic
    4 Layout Engines Dagre, ELK, TALA, Custom
    Custom Fonts Regular, italic, and bold
  • πŸ“ Smart Positioning

    • 9 preset positions (center, corners, edges)
    • Selection-relative placement
    • Custom X/Y offsets
    • Page or viewport alignment
  • πŸ”§ Advanced Features

    • Direct SVG import (fully editable)
    • Auto-scaling to fit dimensions
    • Layer management
    • Object locking
    • Metadata support (title, description)

πŸ€” Why D2?

D2 is a modern diagram scripting language designed for clarity and aesthetics:

Feature D2 Traditional Tools
Syntax Clean, readable Often verbose
Auto-layout Built-in, smart Manual positioning
Styling Simple inline Separate config
Connections Intuitive arrows Complex syntax
Containers Easy nesting Difficult grouping
Icons Built-in library External dependencies

D2 Example:

server -> database: queries
database -> server: results

This simple text produces a professional diagram with automatic layout!


πŸ“¦ Requirements

Core Requirements

Component Version Purpose
Inkscape 1.0+ Vector graphics editor
D2 0.6+ Diagram generation CLI

Optional Dependencies

Component Purpose
Pillow (Python) Automatic PNG dimension detection
TALA Advanced layout engine (commercial)

πŸš€ Installation

Step 1: Install D2

Windows

Option A: Using winget (Recommended)

winget install terrastruct.d2

Option B: Using Chocolatey

choco install d2

Option C: Manual Installation

  1. Download from D2 Releases
  2. Extract to a folder (e.g., C:\Program Files\D2)
  3. Add to system PATH

Verify installation:

d2 --version
macOS
# Using Homebrew (Recommended)
brew install d2

# Or using curl
curl -fsSL https://d2lang.com/install.sh | sh -s --

Verify installation:

d2 --version
Linux
# Universal installer (Recommended)
curl -fsSL https://d2lang.com/install.sh | sh -s --

# Ubuntu/Debian (via .deb)
# Download .deb from releases page
sudo dpkg -i d2_x.x.x_amd64.deb

# Arch Linux (AUR)
yay -S d2

Verify installation:

d2 --version
# Should output: v0.x.x

Step 2: Install the Extension

Locate your Inkscape extensions directory:

OS Path
Windows C:\Users\[YourName]\AppData\Roaming\inkscape\extensions\
macOS ~/Library/Application Support/org.inkscape.Inkscape/config/inkscape/extensions/
Linux ~/.config/inkscape/extensions/

πŸ’‘ Tip: In Inkscape: Edit β†’ Preferences β†’ System shows extensions path

Install files:

  1. Create extension folder:

    mkdir -p [extensions-directory]/d2_ink
  2. Copy files:

    cp d2_diagram.py [extensions-directory]/d2_ink/
    cp d2_diagram.inx [extensions-directory]/d2_ink/
  3. Set permissions (Linux/macOS):

    chmod +x [extensions-directory]/d2_ink/d2_diagram.py
  4. Restart Inkscape

Step 3: Verify Installation

  1. Open Inkscape
  2. Navigate to Extensions β†’ Render β†’ D2 Diagram
  3. Extension dialog should appear

🎯 Quick Start

Create Your First Diagram

  1. Open Inkscape
  2. Go to Extensions β†’ Render β†’ D2 Diagram
  3. In the Diagram tab, enter:
direction: right

User -> Frontend: request
Frontend -> API: call
API -> Database: query
Database -> API: data
API -> Frontend: response
Frontend -> User: display
  1. Click Apply

Your diagram appears in the document, fully editable as SVG!


πŸ“– Usage Guide

Tab Overview

Tab Purpose
Diagram Enter D2 code or load from file
Style Theme, layout engine, sketch mode
Format Output format, scale, quality
Position Placement and alignment options
Scale Auto-scaling and size limits
Config CLI path, custom fonts
Advanced Timeout, temp files, quiet mode
Layer Layer management, object properties

Input Methods

Direct Code Entry

Enter D2 syntax directly in the code field:

x -> y: connection
y -> z

Load from File

  1. Check "Use external file"
  2. Enter path to .d2 file
  3. Click Apply

D2 Syntax Basics

Simple Connections

# Basic arrow
a -> b

# Labeled connection
a -> b: sends data

# Bidirectional
a <-> b: communicates

Shapes and Styling

# Different shapes
server: Server {shape: cylinder}
user: User {shape: person}
cloud: Cloud {shape: cloud}

user -> server -> cloud

Containers (Grouping)

aws: AWS Cloud {
  vpc: VPC {
    ec2: EC2 Instance
    rds: RDS Database
    ec2 -> rds
  }
}

user -> aws.vpc.ec2

Styling

important: Critical System {
  style: {
    fill: "#ff6b6b"
    stroke: "#c92a2a"
    font-color: white
    bold: true
  }
}

Output Formats

Format Best For Editable
SVG Editing, scalability βœ… Yes
PNG Presentations, sharing ❌ No

Theme Options

Theme ID Name Description
0 Default Neutral, professional
1 Neutral Grey Subtle grey tones
3 Flagship Terrastruct Vibrant colors
4 Cool Classics Blue-based palette
5 Mixed Berry Blue Purple-blue tones
6 Grape Soda Purple theme
7 Aubergine Dark purple
8 Colorblind Clear Accessibility-focused
100 Terminal Dark terminal style
101 Terminal Grayscale Monochrome terminal
102 Origami Paper-like aesthetic

Layout Engines

Engine Description Best For
dagre Default, hierarchical Most diagrams
elk Eclipse Layout Kernel Complex graphs
tala Advanced (premium) Professional layouts

Position Modes

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ top_left    top_center    top_right β”‚
β”‚                                     β”‚
β”‚ middle_left   center   middle_right β”‚
β”‚                                     β”‚
β”‚ bottom_left bottom_center bottom_right β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Special options:

  • cursor: Place at view center
  • Use selection bbox: Position relative to selected object

βš™οΈ Configuration

Style Tab

Option Description Default
Theme Color scheme (0-102) 0 (Default)
Layout Layout engine dagre
Sketch Mode Hand-drawn style βœ—
Padding Diagram padding (px) 100

Format Tab

Option Description Default
Output Format SVG or PNG SVG
Scale Factor Size multiplier 1.0
Quality PNG resolution (1-4x) 2
Embed Image Embed or link PNG βœ“

Scale Tab

Option Description Default
Auto Scale Fit to max dimensions βœ—
Max Width Maximum width (0=none) 0
Max Height Maximum height (0=none) 0
Maintain Aspect Ratio Keep proportions βœ“
Lock Object Prevent edits βœ—

Config Tab

Option Description Default
D2 Path Path to d2 executable d2
Font Regular Custom regular font (system)
Font Italic Custom italic font (system)
Font Bold Custom bold font (system)
Inkscape Path Path to Inkscape CLI inkscape

Advanced Tab

Option Description Default
Timeout Generation timeout (sec) 30
Keep Temp Files Don't delete temp files βœ—
Temp Directory Custom temp location (system)
Quiet Mode Suppress debug output βœ“
Fit to Content Crop empty space βœ“

Layer Tab

Option Description Default
Create Layer New layer for diagram βœ—
Layer Name Name for new layer D2 Diagrams
Object ID Custom SVG ID (auto)
Add Title Include title element βœ—
Add Description Include desc element βœ—

πŸ’‘ Examples

Example 1: Network Architecture

direction: right

internet: Internet {shape: cloud}

firewall: Firewall {
  shape: hexagon
  style.fill: "#ffcccc"
}

dmz: DMZ {
  web: Web Server {shape: cylinder}
  api: API Gateway
}

internal: Internal Network {
  app: App Servers {
    shape: rectangle
    style.multiple: true
  }
  db: Database {shape: cylinder}
  cache: Redis Cache {shape: cylinder}
}

internet -> firewall -> dmz.web
dmz.web -> dmz.api
dmz.api -> internal.app
internal.app -> internal.db
internal.app -> internal.cache

Example 2: User Authentication Flow

User -> Login Page: visits
Login Page -> Auth Service: credentials
Auth Service -> Database: validate
Database -> Auth Service: user data
Auth Service -> Token Service: generate JWT
Token Service -> Auth Service: token
Auth Service -> Login Page: success + token
Login Page -> User: redirect to dashboard

Example 3: Class Diagram

Animal: Animal {
  shape: class
  +name: string
  +age: int
  +makeSound(): void
}

Dog: Dog {
  shape: class
  +breed: string
  +bark(): void
  +fetch(): void
}

Cat: Cat {
  shape: class
  +indoor: bool
  +meow(): void
  +purr(): void
}

Animal <- Dog: extends
Animal <- Cat: extends

Example 4: Sequence Diagram Style

direction: right

alice: Alice {shape: person}
bob: Bob {shape: person}
server: Server {shape: cylinder}

alice -> bob: "Hello!"
bob -> alice: "Hi there!"
alice -> server: login request
server -> alice: session token
alice -> bob: "I'm logged in"

Example 5: System Components with Icons

frontend: Frontend {
  icon: https://icons.terrastruct.com/essentials/092-map.svg
  react: React App
  nginx: Nginx
}

backend: Backend {
  icon: https://icons.terrastruct.com/essentials/213-server.svg
  api: REST API
  worker: Background Worker
}

data: Data Layer {
  icon: https://icons.terrastruct.com/essentials/119-database.svg
  postgres: PostgreSQL
  redis: Redis
  s3: S3 Storage {shape: cloud}
}

frontend.react -> backend.api
backend.api -> data.postgres
backend.worker -> data.redis
backend.api -> data.s3

Example 6: Sketch Mode Flowchart

Enable Sketch Mode in Style tab for hand-drawn aesthetic:

start: Start {shape: oval}
process: Process Data
decision: Valid? {shape: diamond}
success: Success {
  style.fill: "#90EE90"
}
error: Error {
  style.fill: "#FFB6C1"
}
end: End {shape: oval}

start -> process
process -> decision
decision -> success: yes
decision -> error: no
success -> end
error -> process: retry

Example 7: Database Schema

users: users {
  shape: sql_table
  id: int {constraint: primary_key}
  email: varchar(255) {constraint: unique}
  name: varchar(100)
  created_at: timestamp
}

posts: posts {
  shape: sql_table
  id: int {constraint: primary_key}
  user_id: int {constraint: foreign_key}
  title: varchar(200)
  content: text
  published: boolean
}

comments: comments {
  shape: sql_table
  id: int {constraint: primary_key}
  post_id: int {constraint: foreign_key}
  user_id: int {constraint: foreign_key}
  body: text
}

users.id <-> posts.user_id
posts.id <-> comments.post_id
users.id <-> comments.user_id

Example 8: Organizational Chart

direction: down

ceo: CEO {
  shape: person
  style.fill: "#4a90d9"
}

cto: CTO {shape: person}
cfo: CFO {shape: person}
coo: COO {shape: person}

engineering: Engineering {
  lead: Tech Lead
  dev1: Developer
  dev2: Developer
}

finance: Finance {
  accountant: Accountant
  analyst: Analyst
}

operations: Operations {
  manager: Manager
  support: Support Team
}

ceo -> cto
ceo -> cfo
ceo -> coo

cto -> engineering
cfo -> finance
coo -> operations

πŸ› Troubleshooting

Common Issues

Extension not appearing in menu

Solutions:

  1. Verify files are correctly placed:
    ls [extensions-directory]/d2_ink/
    # Should show: d2_diagram.py, d2_diagram.inx
  2. Check file permissions:
    chmod +x d2_diagram.py
  3. Restart Inkscape completely
  4. Check Inkscape error log: Edit β†’ Preferences β†’ System β†’ Open Error Log
D2 CLI not found

Error: D2 CLI not found at: d2

Solutions:

  1. Verify D2 is installed:
    d2 --version
  2. Install if missing (see Installation section)
  3. Windows: Use full path in Config tab:
    C:\Program Files\D2\d2.exe
    
    Or add D2 to system PATH
  4. Linux/macOS: Find path:
    which d2
    # Use this path in Config tab
Diagram syntax error

Error: D2 CLI error: ...

Solutions:

  1. Test syntax in command line:
    echo "a -> b" | d2 - output.svg
  2. Check for:
    • Missing colons in labels
    • Unclosed braces for containers
    • Invalid shape names
    • Incorrect style syntax
  3. Refer to D2 Documentation
SVG import issues

Error: Error importing SVG...

Solutions:

  1. Try PNG format instead
  2. Update Inkscape to latest version
  3. Check temp file permissions
  4. Enable Keep Temp Files and inspect generated SVG
Diagram appears but positioning is wrong

Solutions:

  1. Check Position Mode setting
  2. Verify Align to Page vs viewport setting
  3. Adjust X/Y Offset values
  4. Try Auto Scale with max dimensions
Font issues in diagram

Solutions:

  1. Specify custom fonts in Config tab:
    • Font Regular: Path to .ttf or .otf
    • Font Bold: Path to bold variant
    • Font Italic: Path to italic variant
  2. Use system fonts that D2 can find
  3. Check font file permissions

Debug Mode

Enable detailed output for troubleshooting:

  1. Uncheck Quiet Mode in Advanced tab
  2. Check Keep Temp Files
  3. Run Inkscape from terminal:
    inkscape
  4. Check console for debug output

Temp Files Location

With Keep Temp Files enabled:

File Purpose
diagram.d2 Input D2 code
diagram.svg Generated SVG
diagram_converted.png Converted PNG (if PNG format)

πŸ“ File Structure

d2_ink/
β”œβ”€β”€ d2_diagram.py           # Main extension code
β”œβ”€β”€ d2_diagram.inx          # Inkscape extension definition
β”œβ”€β”€ README.md               # This file
└── examples/               # Example diagrams (optional)
    β”œβ”€β”€ architecture.d2
    β”œβ”€β”€ flowchart.d2
    └── database.d2

πŸ“š D2 Language Reference

Shapes

Shape Syntax Description
Rectangle shape: rectangle Default
Square shape: square Equal sides
Circle shape: circle Round
Oval shape: oval Ellipse
Diamond shape: diamond Decision
Hexagon shape: hexagon Process
Cylinder shape: cylinder Database/storage
Cloud shape: cloud Cloud service
Person shape: person Human actor
Package shape: package Module/component
Class shape: class UML class
SQL Table shape: sql_table Database table

Connection Types

Type Syntax Description
Arrow -> Directed
Double Arrow <-> Bidirectional
Line -- Undirected

Style Properties

element: Label {
  style: {
    fill: "#hexcolor"
    stroke: "#hexcolor"
    stroke-width: 2
    stroke-dash: 3
    opacity: 0.8
    font-color: "#hexcolor"
    font-size: 16
    bold: true
    italic: true
    underline: true
    shadow: true
    multiple: true
    3d: true
    animated: true
  }
}

πŸ“š Resources


🀝 Contributing

Contributions are welcome!

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-feature)
  3. Commit changes (git commit -m 'Add new feature')
  4. Push to branch (git push origin feature/new-feature)
  5. Open a Pull Request

Development Setup:

git clone https://github.com/YouvenZ/D2_ink.git
cd D2_ink
# Symlink for testing
ln -s $(pwd) ~/.config/inkscape/extensions/d2_ink

πŸ“„ License

This project is licensed under the MIT License - see LICENSE file for details.


πŸ“§ Support


πŸ™ Acknowledgments

  • D2 by Terrastruct - The diagram scripting language
  • Inkscape - Open source vector graphics
  • D2 community for excellent documentation

πŸ”„ Changelog

v1.0.0 (2024)

  • ✨ Initial release
  • βœ… Full D2 syntax support
  • βœ… SVG and PNG output
  • βœ… 11 built-in themes
  • βœ… Sketch mode
  • βœ… Multiple layout engines
  • βœ… Auto-scaling
  • βœ… Layer management
  • βœ… Custom font support
  • βœ… Position and alignment options

About

Inkscape extension to add D2 diagram within inkscape

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors