title: Merge two PDFs using php
body: <p>I know we already have a number of posts in SO and this might be a duplicate.</p>
  
  <p>But, I have been working on this from last 24 hours without any success. I have 
  gone through all the posts and nothing worked for me.</p>
  
  <p>What I am trying out is quite simple and I saw many examples which people say are working for them but never worked for me.</p>
  
  <p>Below is the code which I am trying out without any luck. The commented portion has the ways which I have been trying. Please help me in this regard.</p>
  
  <pre><code>&lt;?php
      error_reporting(E_ALL);
  
  /*
      require __DIR__ . '/vendor/autoload.php';
      use iio\libmergepdf\Merger;
      use iio\libmergepdf\Pages;
  
  
      $m = new Merger();
      $m-&gt;addFromFile($file1);
      $m-&gt;addFromFile($file2);
      file_put_contents($outputName, $m-&gt;merge());
  
      $fileArray= array($file1, $file2);
  
      // Using Ghostscript
      $cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$outputName ";
      //Add each pdf file to the end of the command
      foreach($fileArray as $file) {
          $cmd .= $file." ";
      }
      echo $cmd;
      $result = shell_exec($cmd);
  
      //using fpdf
  
      require('fpdf181/fpdf.php');
      require('fpdi162/fpdi.php');
  
      $pdf = new FPDI();
  
      foreach ($fileArray as $file) {
          print_r($file);
          $pageCount = $pdf-&gt;setSourceFile($file);
          for ($i = 0; $i &lt; $pageCount; $i++) {
              echo $i;
              $tpl = $pdf-&gt;importPage($i + 1, '/MediaBox');
              $pdf-&gt;addPage();
              $pdf-&gt;useTemplate($tpl);
          }
      }
  
      // output the pdf as a file (http://www.fpdf.org/en/doc/output.htm)
      $pdf-&gt;Output('F', $outputName);
  
  */
      $file1 = "pdf1/file1.pdf";
      $file2 = "pdf2/file2.pdf";
      $datadir = "merged_pdf/";
      $outputName = $datadir."merged.pdf";
  
      include 'PDFMerger/PDFMerger.php';
  
      $pdf = new PDFMerger; // or use $pdf = new \PDFMerger; for Laravel
  
      $pdf-&gt;addPDF($file1);
      $pdf-&gt;addPDF($file2);
  
      $pdf-&gt;merge('file', "merged.pdf"); // generate the file
  
      // $pdf-&gt;merge('download', 'samplepdfs/test.pdf'); // force download
  
      // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options
  
  
  ?&gt;
  </code></pre>