Thursday, September 6, 2012

TCPDF PrintScaling

Today while using the TCPDF PHP class to generate Avery 5267 labels I discovered that when I went to go print, Page Scaling was automatically set to "Fit to printable area" and I needed to have it as "None". After about 20 minutes of poking around forums I finally found something that led me to the TCPDF::setViewerPreferences() method and the PrintScaling preference. I decided the cleanest way to achieve this was to write a new method.

If you are extending TCPDF this is going to be pretty easy, do something like

<?php
class PDF extends TCPDF {
    
    ...

    /**
     * @author Brian Wendt (http://ontodevelopment.blogspot.com/)
     * @link http://www.tcpdf.org/doc/classTCPDF.html#ad09b32089f8e68c9d8424a2777627c21
     * @param string $preference key of preference 
     * @param mixed $value
     */
    function setViewerPreference($preference, $value){
        $this->viewer_preferences[$preference] = $value;
    }
} 

Use

$pdf->setViewerPreference('PrintScaling', 'None');

Otherwise, you'll need to be modifying the TCPDF class directly to do this cleanly.
Add the setViewerPreference() method from above to the TCPDF class. If you aren't extending and you aren't interested in changing the TCPDF class, then you'd simply use TCPDF::setViewerPreferences() like below but it has drawbacks.

$pdf->setViewerPreferences(array(
    'PrintScaling' => 'None'
));

(Note: using TCPFD::setViewerPreferences() overwrites other preferences you've set which is why I suggest creating the setViewerPreference() method)

TCPDF (©Nicola Asuni) is a powerful PHP class to generate PDF documents.