Learn how to integrate the MegaPDF API into your applications with comprehensive guides, authentication setup, and sample code.
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.
To use the MegaPDF API, you need:
All requests to the MegaPDF API require authentication using an API key. To get your API key:
Example API Key
sk_d6c1daa54dbc95956b281fa02c544e7273ed10df60b211fe
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
There are two ways to authenticate your API requests:
Include your API key in the x-api-key
request header:
x-api-key: your-api-key
Include your API key as a query parameter:
https://mega-pdf.com/api/pdf/convert?api_key=your-api-key
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));
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"
}
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.
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 Code | Description |
---|---|
200 OK | Request successful |
400 Bad Request | Invalid request parameters |
401 Unauthorized | Invalid or missing API key |
402 Payment Required | Insufficient account balance or free operations |
500 Internal Server Error | Server-side error occurred |
The MegaPDF API enforces rate limits to ensure fair usage:
Plan | Rate Limit |
---|---|
Free | 10 requests per minute |
Basic | 60 requests per minute |
Pro | 200 requests per minute |
Enterprise | Custom 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.
MegaPDF offers a comprehensive suite of PDF processing APIs:
Convert PDFs to and from various formats
View DocumentationMerge, split, compress, and rotate PDFs
View DocumentationExtract text and create searchable PDFs
View DocumentationAdd watermarks, page numbers, and more
View DocumentationExplore all available APIs in the API Documentation.
While you can use the API directly with HTTP requests, we also provide official client libraries for popular programming languages:
Language | Repository | Installation |
---|---|---|
JavaScript/TypeScript | megapdf-js | npm install megapdf |
Python | megapdf-python | pip install megapdf |
PHP | megapdf-php | composer require megapdf/megapdf |
Java | megapdf-java | Available through Maven |
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:
npm install axios form-data
'your-api-key'
with your actual API keydocument.pdf
in the same directorynode convert-pdf.js
MegaPDF uses a credit-based billing system:
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.
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.