SQL to PDF
Format SQL queries and export as PDF documentation. Client-side conversion with syntax-aware formatting.
Back to all tools on ToolForge
Upload SQL File
Upload a SQL file or paste SQL directly below.
Title:
About SQL to PDF
This SQL to PDF tool converts SQL queries into formatted PDF documents using client-side JavaScript processing. The tool includes a SQL formatter that tokenizes input and adds appropriate line breaks before keywords like SELECT, FROM, WHERE, JOIN, and ORDER BY.
The conversion uses jsPDF library to generate PDF files with monospace font (Courier) for proper code alignment. All processing happens locally in your browser without any server upload.
SQL Formatting Algorithm
The formatter uses a tokenization approach to parse SQL:
- Tokenization: Split SQL into tokens (keywords, identifiers, operators, punctuation)
- String Handling: Preserve string literals (single/double quoted) exactly as written
- Keyword Detection: Identify SQL keywords that should start new lines
- Indentation Tracking: Increase indent after opening parentheses, decrease after closing
- Line Building: Assemble formatted output with appropriate line breaks and indentation
SQL Keywords That Trigger Line Breaks
| Keyword | Category | Example |
|---|---|---|
| SELECT | Data retrieval | SELECT col1, col2 FROM table |
| FROM | Source specification | FROM users u |
| WHERE | Filtering | WHERE active = 1 |
| GROUP BY | Aggregation | GROUP BY department_id |
| HAVING | Group filtering | HAVING COUNT(*) > 5 |
| ORDER BY | Sorting | ORDER BY created_at DESC |
| LIMIT / OFFSET | Pagination | LIMIT 10 OFFSET 20 |
| JOIN / ON | Table joining | LEFT JOIN orders ON u.id = orders.user_id |
| VALUES | Insert data | VALUES (1, 'name'), (2, 'other') |
| SET | Update assignment | SET name = 'new' |
PDF Generation Process
// Initialize PDF with A4 size (points unit)
const pdf = new jsPDF('p', 'pt', 'a4');
// Set fonts
pdf.setFont('helvetica', 'bold');
pdf.setFontSize(14);
pdf.text(title, margin, y); // Title line
// Switch to monospace for code
pdf.setFont('courier', 'normal');
pdf.setFontSize(9);
// Process each line
lines.forEach(line => {
const wrapped = pdf.splitTextToSize(line, usableWidth);
wrapped.forEach(segment => {
if (y > pageHeight - margin) {
pdf.addPage();
y = margin;
}
pdf.text(segment, margin, y);
y += 12; // Line height
});
});
pdf.save('sql-document.pdf');
Common Use Cases
- Query Documentation: Create readable documentation for complex stored procedures and views
- Code Review: Share SQL queries with team members in a universally readable format
- Training Materials: Generate handouts for database training sessions and workshops
- Compliance Archiving: Preserve audit queries and reporting SQL for regulatory requirements
- Specification Documents: Include SQL specifications in technical documentation packages
- Client Deliverables: Provide query definitions to clients who need PDF format
SQL Tokenization Implementation
function tokenizeSql(sql) {
let tokens = [];
let current = "";
let quote = null;
for (let i = 0; i < sql.length; i++) {
let ch = sql[i];
// Handle string literals
if (quote) {
current += ch;
if (ch === quote && sql[i-1] !== "\\") {
quote = null;
}
continue;
}
if (ch === "'" || ch === '"' || ch === "`") {
current += ch;
quote = ch;
continue;
}
// Handle whitespace
if (/\s/.test(ch)) {
if (current) {
tokens.push(current);
current = "";
}
continue;
}
// Handle punctuation
if (ch === "," || ch === "(" || ch === ")") {
if (current) {
tokens.push(current);
current = "";
}
tokens.push(ch);
continue;
}
current += ch;
}
if (current) tokens.push(current);
return tokens;
}
Font Selection for Code PDFs
| Font | Type | Best For |
|---|---|---|
| Courier | Monospace | Standard code formatting (PDF built-in) |
| Courier Bold | Monospace | Emphasized code sections |
| Helvetica | Sans-serif | Titles and headings (PDF built-in) |
| Times Roman | Serif | Document body text (PDF built-in) |
Page Layout Considerations
- Margins: 36 points (0.5 inches) on all sides provides adequate white space
- Line Height: 12 points for 9pt font gives comfortable reading spacing
- Page Breaks: Automatic when content exceeds page height minus margin
- Text Wrapping: splitTextToSize handles word breaks at usable width
Frequently Asked Questions
- How does SQL to PDF conversion work?
- The tool uses jsPDF to create PDF documents client-side. SQL text is tokenized to identify keywords (SELECT, FROM, WHERE), then rendered using monospace font (Courier) for code preservation. Each line is wrapped to fit the page width with proper margins.
- What SQL formatting is applied?
- The formatter tokenizes SQL and adds line breaks before keywords like SELECT, FROM, WHERE, JOIN, ORDER BY, GROUP BY, HAVING, LIMIT. Parentheses trigger indentation increases. Commas add line breaks for column lists. String literals are preserved exactly.
- Why use monospace font for SQL in PDFs?
- Monospace fonts (Courier, Consolas, Monaco) ensure each character has equal width, making SQL code align properly. This is essential for readability, especially with nested queries, aligned columns, and indentation-based structure visualization.
- What PDF page size is used?
- A4 size (595 x 842 points at 72 DPI) with 36-point margins. The usable width is 523 points. Text wraps at this width using jsPDF's splitTextToSize function to prevent content overflow.
- Can I include multiple SQL statements?
- Yes. Paste multiple SQL statements separated by semicolons. The tool preserves all content and formats it as a continuous code block. Each statement flows into the next with proper spacing.
- What are common use cases for SQL to PDF?
- Common uses: documenting stored procedures for team handbooks, creating query specification documents, archiving complex queries for compliance, sharing SQL reviews with stakeholders, preparing training materials for database courses, and generating report specifications.