Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Last active September 4, 2020 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterdavis/9993455 to your computer and use it in GitHub Desktop.
Save walterdavis/9993455 to your computer and use it in GitHub Desktop.
<?php
// only run this if the form has been submitted
if(isset($_POST['files'])){
// where are the PDFs stored on your server?
$source_directory = '/data/www/scripty/pdfs/';
$files = array();
// loop over the chosen PDFs
foreach($_POST['files'] as $key => $val){
// protect against malicious forms -- strip off anything besides a filename
$safe_val = array_pop(preg_split('/\//', $val, -1, PREG_SPLIT_NO_EMPTY));
// concatenate each path so you know which file you're sending
$files[$key] = $source_directory . $safe_val;
}
// call GhostScript to concatenate the PDFs into a single file at STDOUT
$cmd = 'gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=- ' . implode(' ', $files);
$result = shell_exec($cmd);
// send the headers to the browser
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=merged.pdf');
//send data
print $result;
// don't send the HTML page
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PDF Merge</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css" media="screen">
body {
font: 13px/1.4 'Lucida Grande', sans-serif;
background-color: #eee;
padding: 0;
margin: 0;
}
#PageDiv {
width: 400px;
margin: 40px auto;
padding: 40px 80px;
background-color: #fff;
}
ul {
list-style-type: none;
padding: 0;
}
h1 {
font-weight: normal;
}
</style>
</head>
<body>
<div id="PageDiv">
<form action="" method="post" accept-charset="utf-8">
<h1>Choose your adventure:</h1>
<ul>
<li><label><input type="checkbox" name="files[]" value="page1.pdf" /> Page 1</label></li>
<li><label><input type="checkbox" name="files[]" value="page2.pdf" /> Page 2</label></li>
<li><label><input type="checkbox" name="files[]" value="page3.pdf" /> Page 3</label></li>
<li><label><input type="checkbox" name="files[]" value="page4.pdf" /> Page 4</label></li>
<li><label><input type="checkbox" name="files[]" value="page5.pdf" /> Page 5</label></li>
<li><label><input type="checkbox" name="files[]" value="page6.pdf" /> Page 6</label></li>
</ul>
<p><input type="submit" value="Get PDF"/></p>
</form>
</div>
</body>
</html>
@ramakrishnavrkr
Copy link

ramakrishnavrkr commented May 18, 2018

is there any way '$cmd ' can use in foreach loop instead of out side of loop.
because i have to merge more than 100 pdfs some times it goes around 1000.

@mmunawar
Copy link

mmunawar commented Sep 4, 2020

Thanks for the great script. Kindly provide code to view merged PDF in a DIV.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment