Preview Generation

FileLens provides both synchronous and asynchronous preview generation capabilities for various file formats. This guide covers how to use both modes effectively, configure options, and handle different scenarios.


Synchronous Processing

Synchronous processing generates previews immediately and returns download URLs in the response. This is ideal for small to medium files that can be processed quickly.

When to Use Sync Processing

  • Files smaller than 10MB
  • Documents with fewer than 20 pages
  • Quick preview generation for immediate display
  • Simple images and short videos

Basic Sync Request

curl -X POST http://localhost:3000/preview \
  -H "Content-Type: application/json" \
  -d '{
    "input": "https://example.com/document.pdf",
    "output_format": "jpg",
    "options": {
      "width": 800,
      "height": 600,
      "quality": 85
    }
  }'

Sync Response Format

{
  "success": true,
  "message": "Preview generated successfully",
  "preview_urls": [
    "/download/sync_1641312000_12345_def4_1.jpg",
    "/download/sync_1641312000_12345_def4_2.jpg"
  ],
  "total_pages": 2,
  "job_id": null
}

Asynchronous Processing

Asynchronous processing submits a job for background processing and returns a job ID. This is ideal for large files, complex documents, or when you don't need immediate results.

When to Use Async Processing

  • Files larger than 10MB
  • Documents with more than 20 pages
  • Complex presentations or spreadsheets
  • Batch processing multiple files
  • When immediate results aren't required

Async Workflow

  1. Submit Job: Send POST request to /preview/async
  2. Get Job ID: Receive job ID in response
  3. Poll Status: Check job status with /preview/status/{job_id}
  4. Download Results: Use result URLs when job completes
# Submit job
curl -X POST http://localhost:3000/preview/async \
  -H "Content-Type: application/json" \
  -d '{
    "input": "https://example.com/large-presentation.pptx",
    "output_format": "png",
    "options": {
      "width": 1920,
      "height": 1080,
      "all_pages": true
    }
  }'

# Response
{
  "success": true,
  "message": "Job created successfully",
  "job_id": "550e8400-e29b-41d4-a716-446655440000"
}

Async Implementation Examples

class AsyncPreviewHandler {
  constructor(baseUrl = 'http://localhost:3000') {
    this.baseUrl = baseUrl;
  }

  async submitJob(input, outputFormat, options) {
    const response = await fetch(`${this.baseUrl}/preview/async`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        input,
        output_format: outputFormat,
        options
      })
    });

    const result = await response.json();
    if (!result.success) {
      throw new Error(result.message);
    }

    return result.job_id;
  }

  async pollStatus(jobId, onProgress = null) {
    while (true) {
      const response = await fetch(`${this.baseUrl}/preview/status/${jobId}`);
      const status = await response.json();

      if (onProgress) {
        onProgress(status);
      }

      if (status.status === 'completed') {
        return status;
      } else if (status.status === 'failed') {
        throw new Error(status.message);
      }

      // Wait 2 seconds before next check
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }

  async processFile(input, outputFormat, options) {
    const jobId = await this.submitJob(input, outputFormat, options);
    console.log(`Job submitted: ${jobId}`);

    const result = await this.pollStatus(jobId, (status) => {
      console.log(`Progress: ${status.progress}% - ${status.status}`);
    });

    console.log(`Job completed! Generated ${result.total_pages} previews`);
    return result;
  }
}

// Usage
const handler = new AsyncPreviewHandler();
const result = await handler.processFile(
  'https://example.com/large-file.pptx',
  'png',
  { width: 1920, height: 1080, all_pages: true }
);

Options and Parameters

Output Formats

  • Name
    jpg
    Type
    string
    Description

    JPEG format - Good compression, widely supported. Best for photos and complex images.

  • Name
    png
    Type
    string
    Description

    PNG format - Lossless compression, supports transparency. Best for graphics and text.

  • Name
    gif
    Type
    string
    Description

    GIF format - Limited color palette, supports animation. Good for simple graphics.

Dimension Options

Auto-sizing (Recommended)

{
  "width": 800,
  "height": 600
}

Maintains aspect ratio while fitting within bounds.

Specific Dimensions

{
  "width": 1920,
  "height": 1080
}

Forces exact dimensions (may distort image).

Quality Settings

  • Name
    90-100
    Type
    integer
    Description

    High Quality: Best for detailed viewing, presentations. Larger file sizes.

  • Name
    70-89
    Type
    integer
    Description

    Medium Quality: Good balance for web display. Moderate file sizes.

  • Name
    50-69
    Type
    integer
    Description

    Low Quality: Fast processing, thumbnails. Smaller file sizes.

Video Options

For video files, use the preview_time option:

{
  "input": "https://example.com/video.mp4",
  "output_format": "jpg",
  "options": {
    "preview_time": "00:01:30.000",
    "width": 1280,
    "height": 720
  }
}

Examples

Document Processing

{
  "input": "https://example.com/report.pdf",
  "output_format": "jpg",
  "options": {
    "width": 800,
    "height": 600,
    "quality": 90,
    "all_pages": true
  }
}

Image Processing

{
  "input": "https://example.com/large-image.png",
  "output_format": "jpg",
  "options": {
    "width": 800,
    "height": 600,
    "quality": 85
  }
}

Video Processing

{
  "input": "https://example.com/video.mp4",
  "output_format": "jpg",
  "options": {
    "preview_time": "00:00:05.000",
    "width": 1280,
    "height": 720,
    "quality": 85
  }
}

Performance Optimization

For Speed

  • Use lower quality settings (60-80)
  • Smaller dimensions
  • JPEG format
  • Single page processing

For Quality

  • Higher quality settings (90-95)
  • Larger dimensions
  • PNG format for graphics
  • Original aspect ratios

Error Handling

async function generatePreviewSafely(input, options) {
  try {
    const response = await fetch('http://localhost:3000/preview', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        input,
        output_format: 'jpg',
        options
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();

    if (!result.success) {
      throw new Error(`Preview failed: ${result.message}`);
    }

    return result;

  } catch (error) {
    console.error('Preview generation failed:', error.message);

    // Handle specific error types
    if (error.message.includes('404')) {
      console.error('File not found - check URL');
    } else if (error.message.includes('422')) {
      console.error('File processing failed - check format');
    } else if (error.message.includes('timeout')) {
      console.error('Request timed out - try async processing');
    }

    throw error;
  }
}