How do I rotate all or specific pages in a PDF using PHP?
<p>I have PDF documents uploaded by users that need to be processed by auditors. Sometimes the scanned pages in a PDF are sideways or upside down. How do I rotate the pages using php?</p>

<p>I'm using TCPDF and TCPDI, which I believe are the same as fpdf/fpdi</p>

<p>My code, below, will rotate all pages just fine, but when I specify just one page, let's say page 3 of 5. It will leave pages 1 and 2 alone, rotate page 3 and will continue to rotate page 4 and 5. Why?</p>

<p>Also, does this code make sense? Is this the proper way to do this or is there an easier way?</p>

<pre><code>function rotatePDF($file, $degrees, $page = 'all'){

    $pdf = new TCPDI(); // new object
    $pdf-&gt;setPrintHeader(false); // no headers
    $pdf-&gt;setPrintFooter(false); // no footers

    $pagecount = $pdf-&gt;setSourceFile($file); //the original file

    // rotate all - THIS WORKS FINE
    if($page=="all"){
        for ($i = 1; $i &lt;= $pagecount; $i++) { 
            $pageformat = array('Rotate'=&gt;$degrees);

            $tpage = $pdf-&gt;importPage($i);
            $size = $pdf-&gt;getTemplateSize($tpage);

            // get original page orientation        
            $orientation = $size['w'] &gt; $size['h'] ? 'L' : 'P';

            $pdf-&gt;AddPage($orientation,$pageformat);
            $pdf-&gt;useTemplate($tpage);      
        }
    }else{
        for ($i = 1; $i &lt;= $pagecount; $i++) {
            if($page == $i){
                $pageformat = array('Rotate'=&gt;$degrees);

                $tpage = $pdf-&gt;importPage($i);
                $size = $pdf-&gt;getTemplateSize($tpage);

                // get original page orientation
                $orientation = $size['w'] &gt; $size['h'] ? 'L' : 'P';

                $pdf-&gt;AddPage($orientation,$pageformat);
                $pdf-&gt;useTemplate($tpage);                      
            }else{      
                $tpage = $pdf-&gt;importPage($i);

                $pdf-&gt;AddPage();
                $pdf-&gt;useTemplate($tpage);                      
            }
        }
    }
    $out = realpath($file);

    if(rename($file,"files/1/file.bak")){
        $result = $pdf-&gt;Output($out, "F"); 
        if($result == "" ){
            echo "ok";
        }
    }else{
        echo "Failed to rename old PDF";
        die;
    }
}

$file = "files/1/1.pdf";
rotatePDF($file,90); // rotating all works fine
rotatePDF($file,90,3); // rotates page 3 AND all following
</code></pre>