Getting Started

Learn how to integrate the MegaPDF API into your applications with comprehensive guides, authentication setup, and sample code.

Quick Start Guide
Get up and running with the MegaPDF API in minutes

Welcome to the MegaPDF API! This guide will help you quickly integrate our API into your applications. The MegaPDF API provides a comprehensive set of PDF manipulation tools that you can access through simple HTTP requests.

Prerequisites

To use the MegaPDF API, you need:

  • A MegaPDF account
  • An API key (get yours from the API Keys Dashboard)
  • Basic knowledge of HTTP requests and JSON

1. Get Your API Key

All requests to the MegaPDF API require authentication using an API key. To get your API key:

  1. Log in to your MegaPDF account
  2. Navigate to the API Keys Dashboard
  3. Click "Generate New API Key"
  4. Copy your API key and store it securely

Example API Key

sk_d6c1daa54dbc95956b281fa02c544e7273ed10df60b211fe

2. API Base URL

All API endpoints are available at the following base URL:

https://mega-pdf.com/api

For example, to access the PDF conversion endpoint, you would use:

https://mega-pdf.com/api/pdf/convert

3. Authentication

There are two ways to authenticate your API requests:

Option 1: HTTP Header (Recommended)

Include your API key in the x-api-key request header:

x-api-key: your-api-key

Option 2: Query Parameter

Include your API key as a query parameter:

https://mega-pdf.com/api/pdf/convert?api_key=your-api-key

4. Making Your First API Request

Let's make a simple API request to convert a PDF to an image using cURL:

curl -X POST https://mega-pdf.com/api/pdf/convert \
  -H "x-api-key: your-api-key" \
  -F "file=@/path/to/document.pdf" \
  -F "outputFormat=jpg"

And here's how to do the same request in JavaScript:

const formData = new FormData();
formData.append('file', fs.createReadStream('document.pdf'));
formData.append('outputFormat', 'jpg');

fetch('https://mega-pdf.com/api/pdf/convert', {
  method: 'POST',
  headers: {
    'x-api-key': 'your-api-key'
  },
  body: formData
})
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      console.log('Conversion successful:', data.fileUrl);
    } else {
      console.error('Conversion failed:', data.error);
    }
  })
  .catch(error => console.error('Error:', error));

5. Response Format

All API responses include a success boolean indicating if the request was successful:

// Success response
{
  "success": true,
  "message": "Operation completed successfully",
  "fileUrl": "/api/file?folder=conversions&filename=abc123.jpg",
  "filename": "abc123.jpg",
  // Additional operation-specific data...
}

// Error response
{
  "success": false,
  "error": "Detailed error message"
}

6. Downloading Results

For operations that generate files, the response will include a fileUrl path. To download the file, prepend the base URL:

https://mega-pdf.com/api/file?folder=conversions&filename=abc123.jpg

Files remain available for download for 24 hours, after which they are automatically deleted.

7. Error Handling

When an error occurs, the API returns a JSON response with success: false and an error message explaining what went wrong:

{
  "success": false,
  "error": "Authentication failed: Invalid API key"
}

Common HTTP status codes you may encounter:

Status CodeDescription
200 OKRequest successful
400 Bad RequestInvalid request parameters
401 UnauthorizedInvalid or missing API key
402 Payment RequiredInsufficient account balance or free operations
500 Internal Server ErrorServer-side error occurred

8. Rate Limits

The MegaPDF API enforces rate limits to ensure fair usage:

PlanRate Limit
Free10 requests per minute
Basic60 requests per minute
Pro200 requests per minute
EnterpriseCustom rate limits

When you exceed your rate limit, the API returns a 429 Too Many Requests response. The response includes a Retry-After header indicating how many seconds to wait before making another request.

9. Available APIs

MegaPDF offers a comprehensive suite of PDF processing APIs:

Conversion API

Convert PDFs to and from various formats

View Documentation
Manipulation API

Merge, split, compress, and rotate PDFs

View Documentation
OCR API

Extract text and create searchable PDFs

View Documentation
Editing API

Add watermarks, page numbers, and more

View Documentation

Explore all available APIs in the API Documentation.

10. SDKs and Client Libraries

While you can use the API directly with HTTP requests, we also provide official client libraries for popular programming languages:

LanguageRepositoryInstallation
JavaScript/TypeScriptmegapdf-jsnpm install megapdf
Pythonmegapdf-pythonpip install megapdf
PHPmegapdf-phpcomposer require megapdf/megapdf
Javamegapdf-javaAvailable through Maven

11. Complete Example: PDF to DOCX Conversion

Here's a complete example of converting a PDF to a DOCX file using Node.js:

// Save as convert-pdf.js
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');

// Configuration
const API_KEY = 'your-api-key'; // Replace with your actual API key
const API_URL = 'https://mega-pdf.com/api/pdf/convert';
const PDF_FILE_PATH = './document.pdf'; // Path to your PDF file
const OUTPUT_FORMAT = 'docx';

async function convertPDF() {
  try {
    // Create form data
    const formData = new FormData();
    formData.append('file', fs.createReadStream(PDF_FILE_PATH));
    formData.append('outputFormat', OUTPUT_FORMAT);
    
    // Make API request
    console.log('Converting PDF to DOCX...');
    const response = await axios.post(API_URL, formData, {
      headers: {
        'x-api-key': API_KEY,
        ...formData.getHeaders()
      },
      responseType: 'json'
    });
    
    // Check if the request was successful
    if (response.data.success) {
      console.log('Conversion successful!');
      
      // Download the converted file
      const fileUrl = `https://mega-pdf.com${response.data.fileUrl}`;
      const outputPath = `./converted-${path.basename(PDF_FILE_PATH, '.pdf')}.${OUTPUT_FORMAT}`;
      
      console.log(`Downloading converted file from ${fileUrl}...`);
      const fileResponse = await axios.get(fileUrl, { responseType: 'stream' });
      
      // Save the file
      const writer = fs.createWriteStream(outputPath);
      fileResponse.data.pipe(writer);
      
      return new Promise((resolve, reject) => {
        writer.on('finish', () => {
          console.log(`File saved to ${outputPath}`);
          resolve(outputPath);
        });
        writer.on('error', reject);
      });
    } else {
      throw new Error(response.data.error || 'Conversion failed');
    }
  } catch (error) {
    console.error('Error:', error.message);
    if (error.response) {
      console.error('Response data:', error.response.data);
      console.error('Response status:', error.response.status);
    }
    throw error;
  }
}

// Run the conversion
convertPDF()
  .then(outputPath => console.log('Done!'))
  .catch(error => console.error('Conversion failed:', error));

To run this example:

  1. Install dependencies: npm install axios form-data
  2. Replace 'your-api-key' with your actual API key
  3. Place a PDF file named document.pdf in the same directory
  4. Run the script: node convert-pdf.js

12. Billing and Usage

MegaPDF uses a credit-based billing system:

  • Each API operation costs 1 credit
  • Free accounts receive 10 free operations per month
  • Paid plans include a monthly credit allocation
  • Additional credits can be purchased from your dashboard

When you make an API request, you'll receive billing information in the response:

{
  "success": true,
  "message": "Operation successful",
  "fileUrl": "/api/file?folder=conversions&filename=abc123.jpg",
  "billing": {
    "usedFreeOperation": true,
    "freeOperationsRemaining": 9,
    "currentBalance": 50.00,
    "operationCost": 0.00
  }
}

You can view your current usage and billing information on the Billing Dashboard.

Next Steps

Now that you're familiar with the basics, explore the documentation for specific API endpoints to learn more about their capabilities and parameters:

If you need help, check out our Support Center or contact our Support Team.