Extension:Pdf Export/Source Code

From MediaWiki.org
Jump to: navigation, search
This code represents version 2.4.2 of this extension. All newer versions are in MW version control and may be obtained from there. See this extensions home page for further information.

Overview[edit | edit source]

This is the source code for Pdf Export extension. There are four files.

To start using this extension you can:

  • Copy each of the following into the files as indicated
  • Use this script to get these files via the commandline.

PdfExport.php[edit | edit source]

Put the following into $IP/extensions/PdfExport/PdfExport.php:

<?php
if ( !defined( 'MEDIAWIKI' ) )
     die ();
 
$wgExtensionCredits['specialpage'][] = array(
        'name' => 'PdfExport',
        'author' => array( 'Thomas Hempel', '...' ),
        'version' => '2.4.2 (2011-02-23)',
        'description' => 'renders a page as pdf',
        'url' => 'http://www.mediawiki.org/wiki/Extension:Pdf_Export'
);
 
$dir = dirname(__FILE__) . '/';
# Internationalisation file
$wgExtensionMessagesFiles['PdfPrint'] = $dir . 'PdfExport.i18n.php';
$wgExtensionAliasesFiles['PdfPrint'] = $dir . 'PdfExport.i18n.alias.php';
$wgSpecialPageGroups['PdfPrint'] = 'pagetools';
 
# Add special page.
$wgSpecialPages['PdfPrint'] = 'SpecialPdf';
$wgAutoloadClasses['SpecialPdf'] = $dir . 'PdfExport_body.php';
 
$wgHooks['SkinTemplateBuildNavUrlsNav_urlsAfterPermalink'][] = 'wfSpecialPdfNav';
$wgHooks['SkinTemplateToolboxEnd'][] = 'wfSpecialPdfToolbox';
 
function wfSpecialPdfNav( &$skintemplate, &$nav_urls, &$oldid, &$revid ) {
	wfLoadExtensionMessages( 'PdfPrint' );
        $nav_urls['pdfprint'] = array(
                        'text' => wfMsg( 'pdf_print_link' ),
                        'href' => $skintemplate->makeSpecialUrl( 'PdfPrint', "page=" . wfUrlencode( "{$skintemplate->thispage}" )  )
                );
        return true;
}
 
function wfSpecialPdfToolbox( &$monobook ) {
	wfLoadExtensionMessages( 'PdfPrint' );
        if ( isset( $monobook->data['nav_urls']['pdfprint'] ) )
                if ( $monobook->data['nav_urls']['pdfprint']['href'] == '' ) {
                        ?><li id="t-ispdf"><?php echo $monobook->msg( 'pdf_print_link' ); ?></li><?php
                } else {
                        ?><li id="t-pdf">
<?php
                                ?><a href="<?php echo htmlspecialchars( $monobook->data['nav_urls']['pdfprint']['href'] ) ?>"><?php
                                        echo $monobook->msg( 'pdf_print_link' );
                                ?></a><?php
                        ?></li><?php
                }
        return true;
}

PdfExport_body.php[edit | edit source]

Put the following into $IP/extensions/PdfExport/PdfExport_body.php:

<?php
// define maximum width of images
if(!defined('MAX_IMAGE_WIDTH'))
	define("MAX_IMAGE_WIDTH", 670);
 
if ( !defined( 'MEDIAWIKI' ) ) 
     die();
 
global $wgPdfExportAttach, $wgPdfExportHttpsImages;
$wgPdfExportAttach = false; // set to true if you want output as an attachment
$wgPdfExportHttpsImages = false; // set to true if page is on a HTTPS server and contains images that are on the HTTPS server and also
                                 // reachable with HTTP
 
        class SpecialPdf extends SpecialPage {
                var $title;
                var $article;
                var $html;
                var $parserOptions;
                var $bhtml;
	        public $iswindows;
 
	        function SpecialPdf() {
		        global $iswindows;
                        SpecialPage::SpecialPage( 'PdfPrint' );
                        $os = getenv ("SERVER_SOFTWARE");
                        $iswindows = strstr ($os, "Win32");
                }
 
                public function save1page ( $page ) {
		        global $wgUser;
                        global $wgParser;
                        global $wgScriptPath;
                        global $wgServer;
                        global $wgPdfExportHttpsImages;
 
			$title = Title::newFromText( $page );
			if( is_null( $title ) ) { 
			  return null;
                        }
			if( !$title->userCanRead() ){
                          return null;
                        }
                        $article = new Article ($title);
                        $parserOptions = ParserOptions::newFromUser( $wgUser );
                        $parserOptions->setEditSection( false );
                        $parserOptions->setTidy(true);
                        $wgParser->mShowToc = false;
                        $parserOutput = $wgParser->parse( $article->preSaveTransform( $article->getContent() ) ."\n\n",
                                        $title, $parserOptions );
 
                        $bhtml = $parserOutput->getText();
                        // XXX Hack to thread the EUR sign correctly
                        $bhtml = str_replace(chr(0xE2) . chr(0x82) . chr(0xAC), chr(0xA4), $bhtml);
                        $bhtml = utf8_decode($bhtml);
 
                        // add the '"'. so links pointing to other wikis do not get erroneously converted.
                        $bhtml = str_replace ('"'.$wgScriptPath, '"'.$wgServer . $wgScriptPath, $bhtml);
                        $bhtml = str_replace ('/w/',$wgServer . '/w/', $bhtml);
 
// Comment out previous two code lines if wiki is on the root folder and uncomment the following lines
// global $wgUploadPath,$wgScript;
// $bhtml = str_replace ($wgUploadPath, $wgServer.$wgUploadPath,$bhtml);
// if (strlen($wgScriptPath)>0)
// 	$pathToTitle=$wgScriptPath;
// else $pathToTitle=$wgScript;
//	$bhtml = str_replace ("href=\"$pathToTitle", 'href="'.$wgServer.$pathToTitle, $bhtml);
 
                        // removed heights of images
                        $bhtml = preg_replace ('/height="\d+"/', '', $bhtml);
                        // set upper limit for width
                        $bhtml = preg_replace ('/width="(\d+)"/e', '"width=\"".($1> MAX_IMAGE_WIDTH ?  MAX_IMAGE_WIDTH : $1)."\""', $bhtml);
 
                        if ($wgPdfExportHttpsImages) {
                            $bhtm = str_replace('img src=\"https:\/\/','img src=\"http:\/\/', $bhtml);
                        }
 
                        $html = "<html><head><title>" . utf8_decode($page) . "</title></head><body>" . $bhtml . "</body></html>";
                        return $html;
		}
 
                function outputpdf ($pages, $landscape, $permissions, $fontface, $fontsize, $margintop, $marginsides, $marginbottom, $size, $filename) {
		        global $iswindows;
		        global $wgPdfExportAttach;
                        global $wgRequest;
			global $wgPdfExportBackground;
 
                        $returnStatus = 0;
			$pagestring = "";
                        $pagefiles = array();
                        $foundone = false;
 
                        foreach ($pages as $pg) {
			  $pagestring .= $this->save1page ($pg);
                          if ($pagestring == null) {
			    continue;
                          }
                          }
 
                        if ($pagestring == "") {
			  return;
                        }
                        putenv("HTMLDOC_NOCGI=1");
 
                        # Write the content type to the client...
                        header("Content-Type: application/pdf");
			header(sprintf('Content-Disposition: attachment; filename="' . $filename . '"', $wgRequest->getVal('page')));
 
			$htmldoc_descriptorspec = array(
							// stdin is a pipe that the child will read from
							0 => array("pipe", "r"),  
							// stdout is a pipe that the child will write to */
							1 => array("pipe", "w"));
                        # Run HTMLDOC to provide the PDF file to the user...
			$htmldoc_process = proc_open("htmldoc -t pdf14 --charset iso-8859-15 --color --quiet --jpeg --bodyfont " . $fontface . " --textfont " . $fontface . " --headingfont " . $fontface . " --fontsize " . $fontsize . " --bodyimage " . $wgPdfExportBackground . " --top " . $margintop . " --left " . $marginsides . " --right " . $marginsides . " --bottom " . $marginbottom . " --permissions " . $permissions . " --size " . $size . " " . $landscape . "--webpage -", $htmldoc_descriptorspec, $pipes);
 
			fwrite($pipes[0], $pagestring);
			fclose($pipes[0]);
 
			fpassthru($pipes[1]);
			fclose($pipes[1]);
 
			$returnStatus = proc_close($htmldoc_process);
 
                        if($returnStatus == 1)
                        {
                                error_log("Generating PDF failed, check path to HTMLDoc, return status was:" . $returnStatus, 0);
                        }
                        flush();
                        foreach ($pagefiles as $pgf) {
			  unlink ($pgf);
			}
                }  
 
 
 
                function execute( $par ) {
		        global $wgRequest;
                        global $wgOut; 
 
                        wfLoadExtensionMessages ('PdfPrint');
                        $dopdf = false;
                        if ($wgRequest->wasPosted()) {
			  $pagel = $wgRequest->getText ('pagel');
		          $pages = array_filter( explode( "\n", $pagel ), 'wfFilterPage1' );
		          $filename = $wgRequest->getText ('filename');
			  $fontface = $wgRequest->getText ('fontface');
			  $fontsize = $wgRequest->getText ('fontsize');
			  $size = $wgRequest->getText ('Size', 'Letter');
			  $margintop = $wgRequest->getText ('margintop');
			  $marginsides = $wgRequest->getText ('marginsides');
			  $marginbottom = $wgRequest->getText ('marginbottom');
			  $permissions = $wgRequest->getVal ('permissions');
                          $orientations = $wgRequest->getVal ('orientation');
                          if ($orientations == 'landscape') {
			    $orientation = " --landscape --browserwidth 1200 ";
                          }
                          else {
                            $orientation = " --portrait ";
                          }
                          $dopdf = true;
			}
                        else {
                          $page = isset( $par ) ? $par : $wgRequest->getText( 'page' );
                          if ($page != "") {
			    $dopdf = true; 
                          }
                          $pages = array ($page);
			  $fontface = "times";
			  $fontsize = "11";
			  $margintop = "20mm";
			  $marginsides = "20mm";
			  $marginbottom = "20mm";
			  $permissions = "all";
 
                          $orientation = " --portrait ";
                          $size = "A4";
                          $filename = "%s.pdf";
                        }
 
			if ($dopdf) {
			  $wgOut->setPrintable();
			  $wgOut->disable();
 
			  $this->outputpdf ($pages, $orientation, $permissions, $fontface, $fontsize, $margintop, $marginsides, $marginbottom, $size, $filename);
                          return;
                        }
 
			$self = SpecialPage::getTitleFor( 'PdfPrint' );
			$wgOut->addHtml( wfMsgExt( 'pdf_print_text', 'parse' ) );
 
			$form = Xml::openElement( 'form', array( 'method' => 'post',
								 'action' => $self->getLocalUrl( 'action=submit' ) ) );
 
			$form .= Xml::openElement( 'textarea', array( 'name' => 'pagel', 'cols' => 40, 'rows' => 10 ) );
			$form .= Xml::closeElement( 'textarea' );
			$form .= '<br />';
                        $form .= '<br />' . wfMsg('pdf_size') .": ";
	                $form .= Xml::listDropDown ('Size', wfMsg ('pdf_size_options'),'', wfMsg('pdf_size_default'));
			$form .= Xml::radioLabel(wfMsg ('pdf_portrait'), 'orientation' , 'portrait' , 'portrait', true); 	
			$form .= Xml::radioLabel(wfMsg ('pdf_landscape'), 'orientation' , 'landscape' , 'landscape', false);  
			$form .= '<br />';
			$form .= wfMsg ('pdf_fontface_label').": ";
			$form .= Xml::listDropDown ('fontface', wfMsg ('pdf_fontface_options'),'', wfMsg('pdf_fontface_default'));
			$form .= " " .wfMsg ('pdf_fontsize_label').": ";
			$form .= Xml::openElement( 'input', array( 'type'=>'text', 'name' => 'fontsize', 'value' => '11' ) );
			$form .= Xml::closeElement( 'input' );
			$form .= '<br />';
			$form .= wfMsg ('pdf_permissions_label').":";
			$form .= Xml::radioLabel(wfMsg ('pdf_permissions_all'), 'permissions' , 'all' , 'all', true);
			# "no-copy,print" results in a not-printable PDF (tested in KPDF & Acrobat Reader 9)
			//$form .= Xml::radioLabel(wfMsg ('pdf_permissions_print'), 'permissions' , 'no-copy,print' , 'no-copy,print', false);
			$form .= Xml::radioLabel(wfMsg ('pdf_permissions_none'), 'permissions' , 'none' , 'none', false);
			$form .= '<br />';
			$form .= wfMsg ('pdf_margins_label').":";
			$form .= '<ul>';
			$form .= ' <li>';
			$form .= Xml::openElement( 'input', array( 'type'=>'text', 'name' => 'margintop', 'value' => '20mm' ) );
			$form .= Xml::closeElement( 'input' );
			$form .= ' (' . wfMsg ('pdf_margins_label_top') . ')';
			$form .= ' </li>';
			$form .= ' <li>';
			$form .= Xml::openElement( 'input', array( 'type'=>'text', 'name' => 'marginsides', 'value' => '20mm' ) );
			$form .= Xml::closeElement( 'input' );
			$form .= ' (' . wfMsg ('pdf_margins_label_sides') . ')';
			$form .= ' </li>';
			$form .= ' <li>';
			$form .= Xml::openElement( 'input', array( 'type'=>'text', 'name' => 'marginbottom', 'value' => '20mm' ) );
			$form .= Xml::closeElement( 'input' );
			$form .= ' (' . wfMsg ('pdf_margins_label_bottom') . ')';
			$form .= ' </li>';
			$form .= '</ul>';
			$form .= '<br />';
			// input field for name of PDF
			$form .= wfMsg ('pdf_filename').": ";
			$form .= Xml::openElement( 'input', array( 'type'=>'text', 'name' => 'filename', 'value' => 'print.pdf' ) );
			$form .= Xml::closeElement( 'input' );
			$form .= '<br /><br />';
			$form .= Xml::submitButton( wfMsg( 'pdf_submit' ) );
	                $form .= Xml::closeElement( 'form' );
	                $wgOut->addHtml( $form );
 
        }
}
 
function wfFilterPage1( $page ) {
	return $page !== '' && $page !== null;
}

PdfExport.i18n.php[edit | edit source]

Put the following into $IP/extensions/PdfExport/PdfExport.i18n.php:

<?php
/**
 * Internationalisation file for PdfExport extension.
 *
 * @addtogroup Extensions
*/
 
$messages = array();
 
$messages['de'] = array(
        'pdfprint' => 'PDF-Druck' ,
	'pdf_fontface_label' => 'Schriftart',
	'pdf_fontface_default' => 'times',
	'pdf_fontface_options' => 'times
				   courier
				   helvetica',
	'pdf_fontsize_label' => 'Schriftgr&ouml;&szlig;e',
	'pdf_margins_label' => 'Einz&uuml;ge',
	'pdf_margins_label_top' => 'oben',
	'pdf_margins_label_sides' => 'seitlich',
	'pdf_margins_label_bottom' => 'unten',
        'pdf_print_link' => 'Als PDF ausgeben',
        'pdf_print_text' => 'Gib eine Liste von einer oder mehr Seiten an (ein Seitenname pro Zeile)',
        'pdf_submit' => 'PDF erstellen',
        'pdf_portrait' => 'Hochformat',
        'pdf_landscape' => 'Querformat',
	'pdf_permissions_label' => 'Berechtigungen',
	'pdf_permissions_all' => 'Alle',
	'pdf_permissions_none' => 'Keine',
        'pdf_size' => 'Papiergr&ouml;&szlig;e',
        'pdf_size_default' => 'A4',
        'pdf_size_options' => 'A4
                               Letter
                               Universal',
        'pdf_filename' => 'Dateiname',
);
$messages['de-formal'] = array(
        'pdfprint' => 'PDF-Druck' ,
	'pdf_fontface_label' => 'Schriftart',
	'pdf_fontface_default' => 'times',
	'pdf_fontface_options' => 'times
				   courier
				   helvetica',
	'pdf_fontsize_label' => 'Schriftgr&ouml;&szlig;e',
	'pdf_margins_label' => 'Einz&uuml;ge',
	'pdf_margins_label_top' => 'oben',
	'pdf_margins_label_sides' => 'seitlich',
	'pdf_margins_label_bottom' => 'unten',
        'pdf_print_link' => 'Als PDF ausgeben',
        'pdf_print_text' => 'Geben Sie eine Liste von einer oder mehr Seiten an (ein Seitenname pro Zeile)',
        'pdf_submit' => 'PDF erstellen',
        'pdf_portrait' => 'Hochformat',
        'pdf_landscape' => 'Querformat',
	'pdf_permissions_label' => 'Berechtigungen',
	'pdf_permissions_all' => 'Alle',
	'pdf_permissions_none' => 'Keine',
        'pdf_size' => 'Papiergr&ouml;&szlig;e',
        'pdf_size_default' => 'A4',
        'pdf_size_options' => 'A4
                               Letter
                               Universal',
        'pdf_filename' => 'Dateiname',
);
$messages['en'] = array(
        'pdfprint' => 'Pdf Export' ,
	'pdf_fontface_label' => 'Fontface',
	'pdf_fontface_default' => 'times',
	'pdf_fontface_options' => 'times
				   courier
				   helvetica',
	'pdf_fontsize_label' => 'Fontsize',
	'pdf_margins_label' => 'Margins',
	'pdf_margins_label_top' => 'top',
	'pdf_margins_label_sides' => 'sides',
	'pdf_margins_label_bottom' => 'bottom',
        'pdf_print_link' => 'Print as PDF',
        'pdf_print_text' => 'Enter a list of one or more pages to export to PDF, one page name per line',
        'pdf_submit' => 'Make PDF',
        'pdf_portrait' => 'Portrait',
        'pdf_landscape' => 'Landscape',
	'pdf_permissions_label' => 'Permissions',
	'pdf_permissions_all' => 'All',
	'pdf_permissions_none' => 'None',
        'pdf_size' => 'Paper Size',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal',
        'pdf_filename' => 'file name',
);
$messages['es'] = array(
        'pdfprint' => 'Imprimir PDF' ,
        'pdf_print_link' => 'Generar PDF',
        'pdf_print_text' => 'Ingrese una lista de una o m&aacute;s p&aacute;ginas para exportar en PDF, escriba solo un nombre de p&aacute;gina por linea.',
        'pdf_submit' => 'Hacer PDF',
        'pdf_portrait' => 'Portaretratos',
        'pdf_landscape' => 'Paisaje',
        'pdf_size' => 'Tama&ntilde;o del papel: ',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);
$messages['ca'] = array(
        'pdfprint' => 'Imprimir PDF' ,
        'pdf_print_link' => 'Generar PDF',
        'pdf_print_text' => 'Poseu una llista de p&agrave;gines per exportar a PDF, escriviu nom&eacute;s un nom de p&agrave;gina per l&iacute;nia.',
        'pdf_submit' => 'Fer PDF',
        'pdf_portrait' => 'Portaretrats',
        'pdf_landscape' => 'Apa&iuml;sat',
        'pdf_size' => 'Mida del paper: ',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);
$messages['fr'] = array(
        'pdfprint' => 'PdfPrint' ,
        'pdf_print_link' => 'Imprimer en PDF',
        'pdf_print_text' => 'Entrez une liste d\'une ou plusieurs pages à exporter en PDF, un nom de page par ligne',
        'pdf_submit' => 'Transformer en PDF',
        'pdf_portrait' => 'Portrait',
        'pdf_landscape' => 'Paysage',
        'pdf_size' => 'Papier',
        'pdf_size_default' => 'A4',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);
$messages['it'] = array(
        'pdf_fontface_label' => 'Carattere',
        'pdf_fontface_default' => 'times',
        'pdf_fontface_options' => 'times 
                                   courier 
                                   helvetica',
        'pdf_fontsize_label' => 'Dimensione caratteri',
        'pdf_permissions_label' => 'Permessi',
        'pdf_permissions_all' => 'Tutti',
        'pdf_permissions_none' => 'Nessuno',
        'pdfprint' => 'Esportazione in PDF' ,
        'pdf_print_link' => 'Stampa come PDF',
        'pdf_print_text' => 'Inserire un elenco di una o pi&ugrave; pagine da esportare, un nome pagina per linea',
        'pdf_submit' => 'Crea PDF',
        'pdf_margins_label' => 'Margini',
        'pdf_margins_label_top' => 'cima',
        'pdf_margins_label_sides' => 'lati',
        'pdf_margins_label_bottom' => 'fondo',
        'pdf_portrait' => 'Verticale',
        'pdf_landscape' => 'Orizzontale',
        'pdf_size' => 'Formato carta',
        'pdf_filename' => 'Nome file',
        'pdf_size_default' => 'A4',
        'pdf_size_options' => 'Letter 
                               A4 
                               Universal'
);
$messages['nl'] = array(
        'pdfprint' => 'Pdf afdruk' ,
        'pdf_print_link' => 'Print als PDF',
        'pdf_print_text' => 'Geef een lijst van een of meer paginas om naar PDF te exporteren, &eacute;&eacute;n paginanaam per regel',
        'pdf_submit' => 'PDF Aanmaken',
        'pdf_portrait' => 'Portret',
        'pdf_landscape' => 'Landschap',
        'pdf_size' => 'Papierafmetingen',
        'pdf_size_default' => 'A4',
        'pdf_size_options' => 'Letter
                               A4
                               Universal',
        'pdf_filename' => 'bestandsnaam',
);
$messages['ksh'] = array(
        'pdfprint' => 'Pdf Drokke' ,
        'pdf_print_link' => 'PDF ußjÀve',
        'pdf_print_text' => 'Enter a list of one or more pages to export to PDF, one page name per line',
        'pdf_submit' => 'Make PDF',
        'pdf_portrait' => 'Portrait',
        'pdf_landscape' => 'Landscape',
        'pdf_size' => 'Paper Size',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);
$messages['nds'] = array(
        'pdfprint' => 'Pdf-Drok' ,
        'pdf_print_link' => 'PDF utgeven',
        'pdf_print_text' => 'Enter a list of one or more pages to export to PDF, one page name per line',
        'pdf_submit' => 'Make PDF',
        'pdf_portrait' => 'Portrait',
        'pdf_landscape' => 'Landscape',
        'pdf_size' => 'Paper Size',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);
 
$messages['sv'] = array(
        'pdfprint' => 'Pdf-export' ,
        'pdf_print_link' => 'Generera PDF',
        'pdf_print_text' => 'Skriv in en lista med en eller flera sidor att exportera till PDF, ett sidnamn per rad',
        'pdf_submit' => 'Skapa PDF',
        'pdf_portrait' => 'Stående',
        'pdf_landscape' => 'Liggande',
        'pdf_size' => 'Pappersstorlek',
        'pdf_size_default' => 'Brev',
        'pdf_size_options' => 'Brev
                               A4
                               Universell',
        'pdf_filename' => 'Filnamn',
);
 
$messages['tr'] = array(
        'pdfprint' => 'Pdf Yazdir' ,
        'pdf_print_link' => 'PDF olarak yazdir',
        'pdf_print_text' => 'Enter a list of one or more pages to export to PDF, one page name per line',
        'pdf_submit' => 'Make PDF',
        'pdf_portrait' => 'Portrait',
        'pdf_landscape' => 'Landscape',
        'pdf_size' => 'Paper Size',
        'pdf_size_default' => 'Letter',
        'pdf_size_options' => 'Letter
                               A4
                               Universal'
);

PdfExport.i18n.alias.php[edit | edit source]

Put the following into $IP/extensions/PdfExport/PdfExport.i18n.alias.php:

<?php
/**
 * Aliases for Special:PdfExport
 *
 * @addtogroup Extensions
 *
$aliases = array();
 
/** English */
$aliases['en'] = array(
	'PdfPrint' => array( 'Pdfprint' ,'Pdf Export'),
);