Reputation: 4602
I am having some problems with running JavaScript in a FPDF/PHP generated PDF viewed through the browser. The script is supposed to show the print dialog or a message box. This functionality has been working for years, but seems to have been broken with a resent update to Edge/Windows. After investigations, it seems that the behavior is different based on browser/viewer.
Findings on fully updated Windows 10:
Same story with the call for the message box.
I am extending FPDF like specified in the FPDF JavaScript support example.
<?
require('fpdf.php');
class PDF_JavaScript extends FPDF {
// My code start
function OpenPrintDialog()
{
$this->IncludeJS("print(true);");
}
function ShowMessageMessage($text)
{
$this->IncludeJS("app.alert('$text', 3);");
}
// My code end
protected $javascript;
protected $n_js;
function IncludeJS($script, $isUTF8=false) {
if(!$isUTF8)
$script=utf8_encode($script);
$this->javascript=$script;
}
function _putjavascript() {
$this->_newobj();
$this->n_js=$this->n;
$this->_put('<<');
$this->_put('/Names [(EmbeddedJS) '.($this->n+1).' 0 R]');
$this->_put('>>');
$this->_put('endobj');
$this->_newobj();
$this->_put('<<');
$this->_put('/S /JavaScript');
$this->_put('/JS '.$this->_textstring($this->javascript));
$this->_put('>>');
$this->_put('endobj');
}
function _putresources() {
parent::_putresources();
if (!empty($this->javascript)) {
$this->_putjavascript();
}
}
function _putcatalog() {
parent::_putcatalog();
if (!empty($this->javascript)) {
$this->_put('/Names <</JavaScript '.($this->n_js).' 0 R>>');
}
}
}
$pdf = new PDF_JavaScript();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 20);
$pdf->Text(90, 50, 'Print me!');
$pdf->OpenPrintDialog();
// or
//$pdf->ShowMessageMessage('Message box me!');
$pdf->Output();
?>
Is it simply not possible to count on PDF JavaScript functionality being allowed in different browsers/viewers?
Upvotes: 0
Views: 1981
Reputation: 4917
Is it simply not possible to count on PDF JavaScript functionality being allowed in different browsers/viewers?
It is not possible. The JavaScript you are trying to run only works in Adobe Acrobat and Reader and a few other desktop PDF viewers and one mobile PDF viewer that I'm aware of. The code doesn't work in Edge because Edge has its own built-in PDF viewer, Explorer will use Adobe Reader or Acrobat, Foxit, Nuance, Nitro, or some other OS level Reader to display the PDF and that's why you get the dialog.
In short, you just can't count on the right viewer/browser/OS combo to be in place to run any JavaScript in the PDF.
Upvotes: 1