SQL to PDF

Format SQL queries and export as PDF documentation. Client-side conversion with syntax-aware formatting.

Back to all tools on ToolForge

More in PDF & Export

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:

  1. Tokenization: Split SQL into tokens (keywords, identifiers, operators, punctuation)
  2. String Handling: Preserve string literals (single/double quoted) exactly as written
  3. Keyword Detection: Identify SQL keywords that should start new lines
  4. Indentation Tracking: Increase indent after opening parentheses, decrease after closing
  5. Line Building: Assemble formatted output with appropriate line breaks and indentation

SQL Keywords That Trigger Line Breaks

KeywordCategoryExample
SELECTData retrievalSELECT col1, col2 FROM table
FROMSource specificationFROM users u
WHEREFilteringWHERE active = 1
GROUP BYAggregationGROUP BY department_id
HAVINGGroup filteringHAVING COUNT(*) > 5
ORDER BYSortingORDER BY created_at DESC
LIMIT / OFFSETPaginationLIMIT 10 OFFSET 20
JOIN / ONTable joiningLEFT JOIN orders ON u.id = orders.user_id
VALUESInsert dataVALUES (1, 'name'), (2, 'other')
SETUpdate assignmentSET 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

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

FontTypeBest For
CourierMonospaceStandard code formatting (PDF built-in)
Courier BoldMonospaceEmphasized code sections
HelveticaSans-serifTitles and headings (PDF built-in)
Times RomanSerifDocument body text (PDF built-in)

Page Layout Considerations

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.