Here's the complete merge-pdf.php file, designed to meet all your requirements.
Before You Run:
- Save the code below as
merge-pdf.php.
- Install Composer if you haven't already: https://getcomposer.org/download/
- Open your terminal or command prompt in the directory where you saved
merge-pdf.php.
- Run the following Composer command to install the necessary libraries:
composer require setasign/fpdi
This will create a vendor/ directory and a composer.json (and composer.lock) file.
- Ensure your web server (Apache, Nginx, etc.) has write permissions to the directory where
merge-pdf.php is located, as it will create uploads/ and merged/ folders.
- Access
merge-pdf.php through your web browser (e.g., http://localhost/merge-pdf.php).
<?php
// merge-pdf.php
// --- Composer Autoload ---
// Make sure Composer's autoload file is included.
// Run 'composer require setasign/fpdi' in your project directory if you haven't.
require_once __DIR__ . '/vendor/autoload.php';
use setasign\Fpdi\Fpdi;
// --- Constants and Directory Setup ---
define('UPLOADS_DIR', __DIR__ . '/uploads/');
define('MERGED_DIR', __DIR__ . '/merged/');
/**
* Ensures that the necessary upload and merged directories exist.
*/
function ensure_dirs_exist() {
if (!is_dir(UPLOADS_DIR)) {
mkdir(UPLOADS_DIR, 0777, true);
}
if (!is_dir(MERGED_DIR)) {
mkdir(MERGED_DIR, 0777, true);
}
}
// --- AJAX Request Handling ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['pdf_files'])) {
header('Content-Type: application/json');
ensure_dirs_exist(); // Ensure directories exist before processing
$response = ['success' => false, 'message' => 'An unknown error occurred.'];
$uploaded_tmp_paths = []; // To store paths of uploaded files for cleanup
try {
// Validate overall file count
$total_files = count($_FILES['pdf_files']['name']);
if ($total_files < 1 || $total_files > 10) {
throw new Exception('Please upload between 1 and 10 PDF files.');
}
// Process each uploaded file
foreach ($_FILES['pdf_files']['name'] as $key => $name) {
$file_tmp_name = $_FILES['pdf_files']['tmp_name'][$key];
$file_type = $_FILES['pdf_files']['type'][$key];
$file_error = $_FILES['pdf_files']['error'][$key];
$file_size = $_FILES['pdf_files']['size'][$key];
if ($file_error !== UPLOAD_ERR_OK) {
throw new Exception("Upload error for '$name': Code $file_error.");
}
if ($file_type !== 'application/pdf') {
throw new Exception("File '$name' is not a PDF. Only PDF files are allowed.");
}
if ($file_size == 0) {
throw new Exception("File '$name' is empty.");
}
// Move uploaded file to a temporary location
$destination = UPLOADS_DIR . uniqid('pdf_') . '_' . basename($name);
if (!move_uploaded_file($file_tmp_name, $destination)) {
throw new Exception("Failed to move uploaded file: $name.");
}
$uploaded_tmp_paths[] = $destination;
}
if (empty($uploaded_tmp_paths)) {
throw new Exception('No valid PDF files were uploaded for merging.');
}
// Initialize FPDI
$pdf = new Fpdi();
// Iterate over uploaded files and import pages
foreach ($uploaded_tmp_paths as $file_path) {
// Set the source file for FPDI
$pageCount = $pdf->setSourceFile($file_path);
// Import all pages of the current PDF
for ($i = 1; $i <= $pageCount; $i++) {
$tplId = $pdf->importPage($i);
// Add a page to the new PDF document
$pdf->AddPage();
// Use the imported page as a template
$pdf->useTemplate($tplId);
}
}
// Define merged file path
$merged_filename = 'merged_pdf_' . time() . '.pdf';
$merged_filepath = MERGED_DIR . $merged_filename;
// Output the merged PDF to a file on the server
$pdf->Output($merged_filepath, 'F'); // 'F' saves to a local file
$response = [
'success' => true,
'message' => 'PDFs merged successfully!',
'download_url' => str_replace(__DIR__, '', $merged_filepath) // Relative URL for download
];
} catch (Exception $e) {
$response['message'] = 'Error: ' . $e->getMessage();
} finally {
// Clean up uploaded temporary files
foreach ($uploaded_tmp_paths as $file_path) {
if (file_exists($file_path)) {
unlink($file_path);
}
}
}
echo json_encode($response);
exit; // Terminate script after AJAX response
}
// --- HTML and JavaScript for the UI ---
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Merge PDF</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
:root {
--primary-red: #e53935; /* Similar to ilovepdf red */
--primary-red-hover: #c62828;
--secondary-green: #4CAF50;
--secondary-green-hover: #43A047;
--text-dark: #333;
--text-light: #666;
--border-color: #ddd;
--bg-light: #f9f9f9;
--bg-white: #fff;
--shadow-light: 0 4px 10px rgba(0,0,0,0.08);
--icon-size: 20px;
}
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 20px;
background-color: var(--bg-light);
color: var(--text-dark);
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
box-sizing: border-box;
}
.container {
background-color: var(--bg-white);
border-radius: 8px;
box-shadow: var(--shadow-light);
padding: 30px;
width: 100%;
max-width: 900px;
display: flex;
flex-direction: column;
gap: 25px;
margin-top: 50px;
}
h1 {
text-align: center;
color: var(--primary-red);
margin-bottom: 25px;
font-size: 2.2em;
font-weight: 700;
}
.main-content {
display: flex;
flex-wrap: wrap; /* Allows wrapping on smaller screens */
gap: 25px;
}
.left-panel {
flex: 2;
min-width: 300px; /* Minimum width for the panel */
background-color: var(--bg-light);
border: 2px dashed var(--border-color);
border-radius: 8px;
padding: 25px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
min-height: 250px;
transition: all 0.3s ease;
}
.left-panel.drag-over {
border-color: var(--primary-red);
background-color: rgba(229, 57, 53, 0.05);
}
.upload-icon {
font-size: 4em;
color: var(--primary-red);
margin-bottom: 10px;
}
.upload-text p {
margin: 5px 0;
color: var(--text-light);
}
.upload-button {
background-color: var(--primary-red);
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
margin-top: 15px;
transition: background-color 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
}
.upload-button:hover {
background-color: var(--primary-red-hover);
}
.upload-button svg {
fill: white;
width: var(--icon-size);
height: var(--icon-size);
}
.right-panel {
flex: 1;
min-width: 250px; /* Minimum width for the panel */
padding: 20px;
display: flex;
flex-direction: column;
gap: 15px;
border-left: 1px solid var(--border-color);
}
@media (max-width: 768px) {
.main-content {
flex-direction: column;
}
.right-panel {
border-left: none;
border-top: 1px solid var(--border-color);
padding-top: 25px;
}
.container {
padding: 20px;
margin-top: 20px;
}
h1 {
font-size: 1.8em;
}
}
.message-box {
background-color: #ffe0b2; /* Light orange for info/warning */
border: 1px solid #ffb74d;
border-radius: 5px;
padding: 15px;
color: var(--text-dark);
text-align: center;
font-weight: bold;
}
.error-message {
background-color: #ffcdd2; /* Light red for error */
border: 1px solid #ef5350;
color: var(--text-dark);
}
.success-message {
background-color: #c8e6c9; /* Light green for success */
border: 1px solid #81c784;
color: var(--text-dark);
}
.file-list {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 15px;
max-height: 300px; /* Scroll if many files */
overflow-y: auto;
padding-right: 5px; /* For scrollbar */
}
.file-item {
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--bg-white);
border: 1px solid var(--border-color);
border-radius: 5px;
padding: 10px 15px;
font-size: 0.95em;
color: var(--text-dark);
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.file-item-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-grow: 1;
padding-right: 10px;
}
.delete-file-btn {
background: none;
border: none;
color: var(--primary-red);
cursor: pointer;
font-size: 1.2em;
line-height: 1;
padding: 0 5px;
transition: color 0.2s ease;
}
.delete-file-btn:hover {
color: var(--primary-red-hover);
}
.actions {
margin-top: 20px;
display: flex;
flex-direction: column;
gap: 15px;
}
.merge-button {
background-color: var(--primary-red);
color: white;
padding: 15px 25px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1.1em;
font-weight: bold;
transition: background-color 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
}
.merge-button:hover:not(:disabled) {
background-color: var(--primary-red-hover);
}
.merge-button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.merge-button svg {
fill: white;
width: var(--icon-size);
height: var(--icon-size);
}
.download-button {
background-color: var(--secondary-green);
color: white;
padding: 15px 25px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1.1em;
font-weight: bold;
transition: background-color 0.2s ease;
display: none; /* Hidden by default */
align-items: center;
justify-content: center;
gap: 10px;
text-decoration: none; /* For anchor tag */
text-align: center;
width: 100%;
box-sizing: border-box;
}
.download-button:hover {
background-color: var(--secondary-green-hover);
}
.download-button svg {
fill: white;
width: var(--icon-size);
height: var(--icon-size);
}
/* Hidden file input */
#fileInput {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1>Merge PDF</h1>
<div class="main-content">
<div class="left-panel" id="dropZone">
<div class="upload-icon">📄</div>
<div class="upload-text">
<p>Drop PDF files here</p>
<p>or</p>
</div>
<button type="button" class="upload-button" id="selectFilesBtn">
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z"></path></svg>
Select PDF files
</button>
<input type="file" id="fileInput" accept="application/pdf" multiple>
</div>
<div class="right-panel">
<div class="message-box" id="messageBox">
Please, select 1 to 10 PDF files.
</div>
<div class="file-list" id="fileList">
<!-- Files will be listed here dynamically -->
</div>
<div class="actions">
<button type="button" class="upload-button" id="addMoreFilesBtn" style="display: none;">
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"></path></svg>
Add More Files
</button>
<button type="button" class="merge-button" id="mergeBtn" disabled>
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M19 13H5v-2h14v2zm-6-8h-2v6H5v2h6v6h2v-6h6v-2h-6V5z"></path></svg>
Merge PDF
</button>
<a href="#" class="download-button" id="downloadBtn" download style="display: none;">
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"></path></svg>
Download Merged PDF
</a>
</div>
</div>
</div>
</div>
<script>
const fileInput = document.getElementById('fileInput');
const selectFilesBtn = document.getElementById('selectFilesBtn');
const addMoreFilesBtn = document.getElementById('addMoreFilesBtn');
const mergeBtn = document.getElementById('mergeBtn');
const downloadBtn = document.getElementById('downloadBtn');
const fileList = document.getElementById('fileList');
const messageBox = document.getElementById('messageBox');
const dropZone = document.getElementById('dropZone');
let selectedFiles = []; // Array to store File objects
const MAX_FILES = 10;
const MIN_FILES = 1;
// --- UI Update Functions ---
function updateMessageBox(message, type = 'info') {
messageBox.textContent = message;
messageBox.className = 'message-box'; // Reset classes
if (type === 'error') {
messageBox.classList.add('error-message');
} else if (type === 'success') {
messageBox.classList.add('success-message');
} else { // info
messageBox.classList.add('info-message');
}
}
function renderFileList() {
fileList.innerHTML = ''; // Clear current list
if (selectedFiles.length === 0) {
updateMessageBox('Please, select 1 to 10 PDF files.');
mergeBtn.disabled = true;
addMoreFilesBtn.style.display = 'none';
return;
}
selectedFiles.forEach((file, index) => {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
fileItem.setAttribute('data-index', index);
const fileNameSpan = document.createElement('span');
fileNameSpan.className = 'file-item-name';
fileNameSpan.textContent = file.name;
fileItem.appendChild(fileNameSpan);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-file-btn';
deleteBtn.innerHTML = '×'; // Unicode 'times' character for delete icon
deleteBtn.title = `Remove ${file.name}`;
deleteBtn.onclick = () => removeFile(index);
fileItem.appendChild(deleteBtn);
fileList.appendChild(fileItem);
});
const currentFileCount = selectedFiles.length;
if (currentFileCount >= MIN_FILES && currentFileCount <= MAX_FILES) {
updateMessageBox(`Files selected: ${currentFileCount}/${MAX_FILES}`, 'info');
mergeBtn.disabled = false;
} else if (currentFileCount > MAX_FILES) {
updateMessageBox(`Too many files selected (${currentFileCount}). Max ${MAX_FILES}.`, 'error');
mergeBtn.disabled = true;
} else { // Should not happen if selectedFiles.length === 0 is handled above
updateMessageBox('Please, select 1 to 10 PDF files.', 'info');
mergeBtn.disabled = true;
}
// Show/hide "Add More Files" button
addMoreFilesBtn.style.display = (selectedFiles.length > 0 && selectedFiles.length < MAX_FILES) ? 'flex' : 'none';
}
// --- File Handling Logic ---
function addFiles(files) {
const newValidFiles = [];
let errorMessages = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type !== 'application/pdf') {
errorMessages.push(`"${file.name}" is not a PDF and was skipped.`);
} else if (selectedFiles.length + newValidFiles.length >= MAX_FILES) {
errorMessages.push(`"${file.name}" was skipped. Maximum ${MAX_FILES} files allowed.`);
} else {
newValidFiles.push(file);
}
}
selectedFiles = [...selectedFiles, ...newValidFiles];
renderFileList();
downloadBtn.style.display = 'none'; // Hide download button on new file selection
if (errorMessages.length > 0) {
updateMessageBox(errorMessages.join('<br>'), 'error');
}
}
function removeFile(index) {
selectedFiles.splice(index, 1);
renderFileList();
downloadBtn.style.display = 'none'; // Hide download button if files change
}
// --- Event Listeners ---
selectFilesBtn.addEventListener('click', () => {
fileInput.click();
});
addMoreFilesBtn.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', (event) => {
addFiles(event.target.files);
fileInput.value = null; // Clear input so same file can be selected again
});
// Drag and Drop handlers
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
addFiles(e.dataTransfer.files);
});
mergeBtn.addEventListener('click', async () => {
if (selectedFiles.length < MIN_FILES || selectedFiles.length > MAX_FILES) {
updateMessageBox(`Please select between ${MIN_FILES} and ${MAX_FILES} PDF files.`, 'error');
return;
}
updateMessageBox('Merging PDFs... Please wait.', 'info');
mergeBtn.disabled = true;
selectFilesBtn.disabled = true;
addMoreFilesBtn.disabled = true;
downloadBtn.style.display = 'none';
fileList.innerHTML = ''; // Clear file list on merge
const formData = new FormData();
selectedFiles.forEach(file => {
formData.append('pdf_files[]', file);
});
try {
const response = await fetch('merge-pdf.php', {
method: 'POST',
body: formData,
});
const result = await response.json();
if (result.success) {
updateMessageBox(result.message, 'success');
downloadBtn.href = result.download_url;
downloadBtn.style.display = 'flex';
selectedFiles = []; // Clear files after successful merge
renderFileList(); // Re-render to show empty state
} else {
updateMessageBox(result.message, 'error');
}
} catch (error) {
updateMessageBox('An error occurred during the merge process. Please try again.', 'error');
console.error('Fetch error:', error);
} finally {
mergeBtn.disabled = false;
selectFilesBtn.disabled = false;
addMoreFilesBtn.disabled = false;
}
});
// Initial render on page load
renderFileList();
</script>
</body>
</html>