Tra le numerose librerie dello Zend Framework, è presente una molto interessante che permette di creare e manipolare file in formato PDF, chiamata Zend_Pdf.
Navigando tra la documentazione si possono trovare i metodi setJavascript e getJavascript, che in linea teoria permetterebbero di inserire codice Javascript all’interno del documento PDF.
Forse non tutti sanno che Adobe Acrobat a partire dalla versione 7, consente l’utilizzo di questo linguaggio di scripting per rendere dinamici e personalizzare i file PDF.
Recentemente mi è capitato di voler utilizzare questa feature, ma ho inaspettatamente scoperto che i due metodi sopra descritti non sono utilizzati in alcuna parte del framework.
Dopo svariate ricerche in rete ho trovato l’implementazione di un metodo che permette di aggirare il problema. L’unica limitazione è che funziona solo con i documenti creati da zero e non con quelli caricati.
Utilizzo
Ho creato una classe che estende Zend_Pdf e che ha un unico metodo:
class My_Pdf extends Zend_Pdf { /** * @param string $javascript * @return void */ public function setEmbeddedJS($javascript = null) { // Names container if ( null === $javascript || '' === $javascript) { throw new Zend_Pdf_Exception('Javascript must be set.'); } $this->setJavaScript($javascript); $js_code = array( 'S' => new Zend_Pdf_Element_Name('JavaScript'), 'JS' => new Zend_Pdf_Element_String($this->getJavascript()) ); $embed[] = new Zend_Pdf_Element_String('EmbeddedJS'); $embed[] = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary($js_code)); $js_ref = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary(array('Names' => new Zend_Pdf_Element_Array($embed)))); $this->_trailer->Root->Names = new Zend_Pdf_Element_Dictionary(array('JavaScript' => $js_ref)); } }
Per utilizzarla è sufficiente seguire questo esempio:
// TODO include libraries $pdf = new My_Pdf(); // create a new page $pdfPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES); $pdfPage->setFont($font, 14); $pdfPage->drawText('Hello World!', 50, 780); // add the page to the document $pdf->pages[0] = $pdfPage; // ***** embed js code ***** $pdf->setEmbeddedJS('this.print(true)'); // render the document header("Content-Type: application/pdf"); header("Content-Disposition: attachment; filename=test.pdf"); echo $pdf->render(); exit;
Demo
La demo è consultabile a questa pagina
Download
Il pacchetto completo è scaricabile QUI
Risorse
http://osdir.com/ml/php.zend.framework.formats/2007-03/msg00010.html
http://framework.zend.com/issues/browse/ZF-3155
http://framework.zend.com/manual/en/zend.pdf.html
http://www.adobe.com/devnet/acrobat/javascript.html