w

API Reference

This document provides technical details about the Markdown to PDF converter's internal API and integration possibilities.

Overview

The Markdown to PDF converter is built using modern web technologies and provides a robust API for document processing and PDF generation.

Core Technologies

Frontend Framework

  • Vue.js 3: Reactive frontend framework
  • TypeScript: Type-safe development
  • Composition API: Modern Vue.js patterns

PDF Generation

  • marked.js: Markdown parsing and rendering

Styling & UI

  • TailwindCSS: Utility-first CSS framework
  • Lucide Icons: Modern icon library
  • Vue Sonner: Toast notifications

Internal API Structure

Markdown Processing

parseMarkdown(content: string): string

Converts Markdown content to HTML.

Parameters:

  • content (string): Raw Markdown content

Returns:

  • string: Rendered HTML

Example:

const html = parseMarkdown('# Hello World\nThis is **bold** text.');
// Returns: '<h1>Hello World</h1>\n<p>This is <strong>bold</strong> text.</p>'

validateMarkdown(content: string): boolean

Validates Markdown content for potential issues.

Parameters:

  • content (string): Markdown content to validate

Returns:

  • boolean: True if content is valid

Example:

const isValid = validateMarkdown('# Valid Header\nValid content.');
// Returns: true

PDF Generation

generatePDF(options: PDFOptions): Promise<Blob>

Generates a PDF from HTML content.

Parameters:

  • options (PDFOptions): PDF generation options

PDFOptions Interface:

interface PDFOptions {
  content: string; // HTML content
  pageSize: 'A4' | 'A3' | 'Letter' | 'Legal';
  orientation: 'portrait' | 'landscape';
  marginTop: number; // in mm
  marginBottom: number; // in mm
  marginLeft: number; // in mm
  marginRight: number; // in mm
  includeToc: boolean;
  includePageNumbers: boolean;
}

Returns:

  • Promise<Blob>: Generated PDF as Blob

Example:

const options = {
  content: '<h1>Document</h1><p>Content</p>',
  pageSize: 'A4',
  orientation: 'portrait',
  marginTop: 20,
  marginBottom: 20,
  marginLeft: 20,
  marginRight: 20,
  includeToc: true,
  includePageNumbers: true,
};

const pdfBlob = await generatePDF(options);

downloadPDF(blob: Blob, filename?: string): void

Downloads a PDF blob as a file.

Parameters:

  • blob (Blob): PDF blob to download
  • filename (string, optional): Custom filename

Example:

downloadPDF(pdfBlob, 'my-document.pdf');

History Management

saveToHistory(record: HistoryRecord): void

Saves a conversion record to history.

HistoryRecord Interface:

interface HistoryRecord {
  id: string;
  title: string;
  content: string;
  contentLength: number;
  pdfOptions: PDFOptions;
  timestamp: number;
}

Example:

const record = {
  id: Date.now().toString(),
  title: 'My Document',
  content: '# My Document\nContent here...',
  contentLength: 25,
  pdfOptions: options,
  timestamp: Date.now(),
};

saveToHistory(record);

loadFromHistory(id: string): HistoryRecord | null

Loads a history record by ID.

Parameters:

  • id (string): History record ID

Returns:

  • HistoryRecord | null: History record or null if not found

clearHistory(): void

Clears all history records.

deleteHistoryRecord(id: string): void

Deletes a specific history record.

Parameters:

  • id (string): History record ID to delete

Component API

MarkdownToPDF Component

Props

interface Props {
  id: string; // Component ID
  docHref?: string; // Documentation link
  class?: string; // CSS classes
}

Events

interface Events {
  'pdf-generated': (blob: Blob) => void;
  'history-saved': (record: HistoryRecord) => void;
  error: (error: Error) => void;
}

Methods

interface Methods {
  generatePDF(): Promise<void>;
  clearContent(): void;
  loadExample(): void;
  downloadPDF(): void;
}

Reactive Data

markdownContent: Ref<string>

Reactive reference to the current Markdown content.

renderedHtml: Ref<string>

Reactive reference to the rendered HTML.

pdfOptions: Ref<PDFOptions>

Reactive reference to PDF generation options.

isGenerating: Ref<boolean>

Reactive reference to PDF generation status.

pdfBlob: Ref<Blob | null>

Reactive reference to the generated PDF blob.

Utility Functions

Content Processing

extractTitle(content: string): string

Extracts the first heading from Markdown content as the document title.

Parameters:

  • content (string): Markdown content

Returns:

  • string: Extracted title or default title

Example:

const title = extractTitle('# My Document\nContent...');
// Returns: 'My Document'

formatDate(timestamp: number): string

Formats a timestamp into a readable date string.

Parameters:

  • timestamp (number): Unix timestamp

Returns:

  • string: Formatted date string

Example:

const date = formatDate(Date.now());
// Returns: '2024-01-15 14:30:25'

Validation Functions

validatePDFOptions(options: PDFOptions): boolean

Validates PDF generation options.

Parameters:

  • options (PDFOptions): Options to validate

Returns:

  • boolean: True if options are valid

sanitizeContent(content: string): string

Sanitizes content to prevent XSS attacks.

Parameters:

  • content (string): Content to sanitize

Returns:

  • string: Sanitized content

Error Handling

Error Types

PDFGenerationError

Thrown when PDF generation fails.

class PDFGenerationError extends Error {
  constructor(message: string, cause?: Error) {
    super(message);
    this.name = 'PDFGenerationError';
    this.cause = cause;
  }
}

ValidationError

Thrown when content validation fails.

class ValidationError extends Error {
  constructor(message: string, field?: string) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

Error Handling Patterns

try {
  const pdfBlob = await generatePDF(options);
  downloadPDF(pdfBlob);
} catch (error) {
  if (error instanceof PDFGenerationError) {
    console.error('PDF generation failed:', error.message);
    // Handle PDF generation error
  } else if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
    // Handle validation error
  } else {
    console.error('Unexpected error:', error);
    // Handle unexpected error
  }
}

Performance Considerations

Memory Management

  • Blob Cleanup: PDF blobs are automatically cleaned up
  • DOM Cleanup: Temporary DOM elements are removed
  • Event Listeners: Event listeners are properly cleaned up

Optimization Strategies

  • Lazy Loading: Resources are loaded only when needed
  • Debouncing: Input changes are debounced to prevent excessive processing
  • Caching: Rendered content is cached for performance
  • Background Processing: PDF generation happens in the background

Browser Compatibility

Supported Browsers

  • Chrome: 80+
  • Firefox: 75+
  • Safari: 13+
  • Edge: 80+

Feature Detection

// Check for required features
const hasRequiredFeatures = () => {
  return (
    'Blob' in window &&
    'URL' in window &&
    'createObjectURL' in URL &&
    'download' in document.createElement('a')
  );
};

Integration Examples

Basic Integration

import { generatePDF, downloadPDF } from '@/utils/pdf-generator';

const convertMarkdownToPDF = async (markdownContent, options) => {
  try {
    const html = parseMarkdown(markdownContent);
    const pdfBlob = await generatePDF({ ...options, content: html });
    downloadPDF(pdfBlob, 'document.pdf');
  } catch (error) {
    console.error('Conversion failed:', error);
  }
};

Advanced Integration with History

import { generatePDF, saveToHistory, loadFromHistory } from '@/utils/pdf-generator';

const convertWithHistory = async (content, options) => {
  const record = {
    id: Date.now().toString(),
    title: extractTitle(content),
    content,
    contentLength: content.length,
    pdfOptions: options,
    timestamp: Date.now(),
  };

  const pdfBlob = await generatePDF({ ...options, content });
  saveToHistory(record);

  return pdfBlob;
};

Future API Enhancements

Planned Features

  • Batch Processing: Convert multiple documents
  • Template System: Predefined formatting templates
  • Custom Fonts: Support for custom font embedding
  • Watermarks: Add watermarks to generated PDFs
  • Digital Signatures: Add digital signature support

API Versioning

Future API versions will maintain backward compatibility while adding new features. Version information will be available through the API.

For more examples and advanced usage, see the Examples documentation.

Was this page helpful?