I'll create a complete single-file PDF merger tool that matches the ilovepdf.com interface. Here's the complete merge-pdf.php file:
<?php
// merge-pdf.php - Complete PDF Merger Tool
session_start();
// Create necessary directories
$uploadDir = 'uploads/';
$mergedDir = 'merged/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (!is_dir($mergedDir)) {
mkdir($mergedDir, 0777, true);
}
// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json');
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'upload':
handleFileUpload();
break;
case 'merge':
handleMergePDFs();
break;
case 'delete':
handleDeleteFile();
break;
case 'download':
handleDownload();
break;
}
}
exit;
}
function handleFileUpload() {
global $uploadDir;
if (!isset($_FILES['pdf_files'])) {
echo json_encode(['success' => false, 'message' => 'No files uploaded']);
return;
}
$uploadedFiles = [];
$files = $_FILES['pdf_files'];
// Handle multiple files
for ($i = 0; $i < count($files['name']); $i++) {
if ($files['error'][$i] === UPLOAD_ERR_OK) {
$fileName = $files['name'][$i];
$tempFile = $files['tmp_name'][$i];
$fileType = $files['type'][$i];
// Validate PDF file
if ($fileType !== 'application/pdf' && strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) !== 'pdf') {
continue;
}
// Generate unique filename
$uniqueName = uniqid() . '_' . $fileName;
$targetPath = $uploadDir . $uniqueName;
if (move_uploaded_file($tempFile, $targetPath)) {
$uploadedFiles[] = [
'name' => $fileName,
'path' => $uniqueName,
'size' => formatBytes(filesize($targetPath))
];
}
}
}
echo json_encode(['success' => true, 'files' => $uploadedFiles]);
}
function handleMergePDFs() {
global $uploadDir, $mergedDir;
if (!isset($_POST['files']) || empty($_POST['files'])) {
echo json_encode(['success' => false, 'message' => 'No files to merge']);
return;
}
$files = json_decode($_POST['files'], true);
try {
// Check if Composer autoload exists
if (!file_exists('vendor/autoload.php')) {
echo json_encode(['success' => false, 'message' => 'FPDI library not found. Please run: composer require setasign/fpdi']);
return;
}
require_once 'vendor/autoload.php';
$pdf = new \setasign\Fpdi\Fpdi();
foreach ($files as $file) {
$filePath = $uploadDir . $file['path'];
if (file_exists($filePath)) {
$pageCount = $pdf->setSourceFile($filePath);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$templateId = $pdf->importPage($pageNo);
$size = $pdf->getTemplateSize($templateId);
$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
$pdf->useTemplate($templateId);
}
}
}
$mergedFileName = 'merged_' . date('Y-m-d_H-i-s') . '.pdf';
$mergedPath = $mergedDir . $mergedFileName;
$pdf->Output('F', $mergedPath);
// Clean up uploaded files
foreach ($files as $file) {
$filePath = $uploadDir . $file['path'];
if (file_exists($filePath)) {
unlink($filePath);
}
}
echo json_encode(['success' => true, 'file' => $mergedFileName]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'message' => 'Error merging PDFs: ' . $e->getMessage()]);
}
}
function handleDeleteFile() {
global $uploadDir;
if (!isset($_POST['file_path'])) {
echo json_encode(['success' => false, 'message' => 'No file specified']);
return;
}
$filePath = $uploadDir . $_POST['file_path'];
if (file_exists($filePath)) {
unlink($filePath);
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false, 'message' => 'File not found']);
}
}
function handleDownload() {
global $mergedDir;
if (!isset($_POST['file_name'])) {
echo json_encode(['success' => false, 'message' => 'No file specified']);
return;
}
$fileName = $_POST['file_name'];
$filePath = $mergedDir . $fileName;
if (file_exists($filePath)) {
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="merged_document.pdf"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
// Clean up merged file after download
unlink($filePath);
exit;
} else {
echo json_encode(['success' => false, 'message' => 'File not found']);
}
}
function formatBytes($size, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
$size /= 1024;
}
return round($size, $precision) . ' ' . $units[$i];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Merge PDF - Free Online PDF Merger</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
overflow: hidden;
}
.header {
background: #fff;
padding: 30px;
text-align: center;
border-bottom: 1px solid #eee;
}
.header h1 {
color: #333;
font-size: 2.5rem;
margin-bottom: 10px;
}
.header p {
color: #666;
font-size: 1.1rem;
}
.main-content {
padding: 40px;
}
.upload-area {
border: 2px dashed #ddd;
border-radius: 10px;
padding: 40px;
text-align: center;
background: #fafafa;
transition: all 0.3s ease;
cursor: pointer;
}
.upload-area:hover {
border-color: #e53e3e;
background: #fff5f5;
}
.upload-area.dragover {
border-color: #e53e3e;
background: #fff5f5;
}
.upload-icon {
font-size: 3rem;
color: #e53e3e;
margin-bottom: 20px;
}
.upload-text {
font-size: 1.2rem;
color: #333;
margin-bottom: 10px;
}
.upload-subtext {
color: #666;
font-size: 0.9rem;
}
.file-input {
display: none;
}
.files-container {
margin-top: 30px;
display: none;
}
.file-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px;
border: 1px solid #eee;
border-radius: 8px;
margin-bottom: 10px;
background: #fff;
}
.file-info {
display: flex;
align-items: center;
flex: 1;
}
.file-icon {
width: 40px;
height: 40px;
background: #e53e3e;
color: white;
border-radius: 6px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 15px;
font-weight: bold;
}
.file-details {
flex: 1;
}
.file-name {
font-weight: 500;
color: #333;
margin-bottom: 5px;
}
.file-size {
color: #666;
font-size: 0.9rem;
}
.file-actions {
display: flex;
gap: 10px;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 1rem;
transition: all 0.3s ease;
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 8px;
}
.btn-primary {
background: #e53e3e;
color: white;
}
.btn-primary:hover {
background: #c53030;
}
.btn-secondary {
background: #f7fafc;
color: #4a5568;
border: 1px solid #e2e8f0;
}
.btn-secondary:hover {
background: #edf2f7;
}
.btn-danger {
background: #fed7d7;
color: #c53030;
border: 1px solid #feb2b2;
}
.btn-danger:hover {
background: #fbb6ce;
}
.controls {
margin-top: 30px;
display: flex;
gap: 15px;
justify-content: center;
}
.message {
text-align: center;
padding: 20px;
margin-top: 20px;
border-radius: 8px;
}
.message.success {
background: #f0fff4;
color: #22543d;
border: 1px solid #9ae6b4;
}
.message.error {
background: #fff5f5;
color: #c53030;
border: 1px solid #feb2b2;
}
.loading {
display: none;
text-align: center;
padding: 20px;
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #e53e3e;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 15px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.instruction {
background: #f7fafc;
border-left: 4px solid #e53e3e;
padding: 20px;
margin: 20px 0;
border-radius: 0 8px 8px 0;
}
.instruction h3 {
color: #2d3748;
margin-bottom: 10px;
}
.instruction p {
color: #4a5568;
margin-bottom: 5px;
}
@media (max-width: 768px) {
.container {
margin: 10px;
}
.header {
padding: 20px;
}
.header h1 {
font-size: 2rem;
}
.main-content {
padding: 20px;
}
.controls {
flex-direction: column;
align-items: center;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>📄 Merge PDF</h1>
<p>Combine multiple PDF files into one document</p>
</div>
<div class="main-content">
<div class="upload-area" id="uploadArea">
<div class="upload-icon">📎</div>
<div class="upload-text">Select PDF files to merge</div>
<div class="upload-subtext">Drag and drop files here or click to browse</div>
<input type="file" id="fileInput" class="file-input" multiple accept=".pdf,application/pdf">
</div>
<div class="instruction">
<h3>How to merge PDFs:</h3>
<p>1. Click above to select PDF files (max 10 files)</p>
<p>2. Drag and drop to reorder files</p>
<p>3. Click "Merge PDFs" to combine them</p>
<p>4. Download your merged PDF</p>
</div>
<div class="files-container" id="filesContainer">
<div id="filesList"></div>
<div class="controls">
<button class="btn btn-secondary" id="addMoreBtn">
➕ Add More Files
</button>
<button class="btn btn-primary" id="mergeBtn">
🔄 Merge PDFs
</button>
</div>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Merging your PDFs...</p>
</div>
<div id="messageArea"></div>
</div>
</div>
<script>
let uploadedFiles = [];
let dragCounter = 0;
// DOM Elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const filesContainer = document.getElementById('filesContainer');
const filesList = document.getElementById('filesList');
const addMoreBtn = document.getElementById('addMoreBtn');
const mergeBtn = document.getElementById('mergeBtn');
const loading = document.getElementById('loading');
const messageArea = document.getElementById('messageArea');
// Event Listeners
uploadArea.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);
addMoreBtn.addEventListener('click', () => fileInput.click());
mergeBtn.addEventListener('click', mergePDFs);
// Drag and Drop
uploadArea.addEventListener('dragenter', handleDragEnter);
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);
function handleDragEnter(e) {
e.preventDefault();
dragCounter++;
uploadArea.classList.add('dragover');
}
function handleDragOver(e) {
e.preventDefault();
}
function handleDragLeave(e) {
e.preventDefault();
dragCounter--;
if (dragCounter === 0) {
uploadArea.classList.remove('dragover');
}
}
function handleDrop(e) {
e.preventDefault();
dragCounter = 0;
uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
uploadFiles(files);
}
}
function handleFileSelect(e) {
const files = e.target.files;
if (files.length > 0) {
uploadFiles(files);
}
}
function uploadFiles(files) {
if (uploadedFiles.length + files.length > 10) {
showMessage('Maximum 10 files allowed', 'error');
return;
}
const formData = new FormData();
formData.append('action', 'upload');
for (let i = 0; i < files.length; i++) {
if (files[i].type === 'application/pdf' || files[i].name.toLowerCase().endsWith('.pdf')) {
formData.append('pdf_files[]', files[i]);
}
}
showLoading(true);
fetch('', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
showLoading(false);
if (data.success) {
uploadedFiles = uploadedFiles.concat(data.files);
updateFilesList();
showFilesContainer();
fileInput.value = '';
} else {
showMessage(data.message, 'error');
}
})
.catch(error => {
showLoading(false);
showMessage('Error uploading files', 'error');
});
}
function updateFilesList() {
filesList.innerHTML = '';
uploadedFiles.forEach((file, index) => {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
fileItem.innerHTML = `
<div class="file-info">
<div class="file-icon">PDF</div>
<div class="file-details">
<div class="file-name">${file.name}</div>
<div class="file-size">${file.size}</div>
</div>
</div>
<div class="file-actions">
<button class="btn btn-danger" onclick="removeFile(${index})">🗑️</button>
</div>
`;
filesList.appendChild(fileItem);
});
}
function removeFile(index) {
const file = uploadedFiles[index];
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `action=delete&file_path=${file.path}`
})
.then(response => response.json())
.then(data => {
if (data.success) {
uploadedFiles.splice(index, 1);
updateFilesList();
if (uploadedFiles.length === 0) {
hideFilesContainer();
}
}
});
}
function mergePDFs() {
if (uploadedFiles.length < 1) {
showMessage('Please select at least one PDF file', 'error');
return;
}
showLoading(true);
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `action=merge&files=${encodeURIComponent(JSON.stringify(uploadedFiles))}`
})
.then(response => response.json())
.then(data => {
showLoading(false);
if (data.success) {
showMessage('PDFs merged successfully!', 'success');
showDownloadButton(data.file);
uploadedFiles = [];
updateFilesList();
hideFilesContainer();
} else {
showMessage(data.message, 'error');
}
})
.catch(error => {
showLoading(false);
showMessage('Error merging PDFs', 'error');
});
}
function showDownloadButton(fileName) {
const downloadBtn = document.createElement('div');
downloadBtn.className = 'controls';
downloadBtn.innerHTML = `
<a href="#" class="btn btn-primary" onclick="downloadFile('${fileName}')">
📥 Download Merged PDF
</a>
`;
messageArea.appendChild(downloadBtn);
}
function downloadFile(fileName) {
const form = document.createElement('form');
form.method = 'POST';
form.innerHTML = `
<input type="hidden" name="action" value="download">
<input type="hidden" name="file_name" value="${fileName}">
`;
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
function showFilesContainer() {
filesContainer.style.display = 'block';
}
function hideFilesContainer() {
filesContainer.style.display = 'none';
}
function showLoading(show) {
loading.style.display = show ? 'block' : 'none';
}
function showMessage(message, type) {
messageArea.innerHTML = `<div class="message ${type}">${message}</div>`;
setTimeout(() => {
messageArea.innerHTML = '';
}, 5000);
}
</script>
</body>
</html>