Jump to content

MediaWiki:Gadget-Global-DownloadPDF.js

From wikiNonStop
Revision as of 17:51, 25 December 2024 by Majestix (talk | contribs) (1 revision imported: Initial setup)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * This script prompts the user to print or download a specified set of pages
 * Documentation: https://www.mediawiki.org/wiki/Template:DownloadPDF
 * Author: Felipe Schenone (User:Sophivorus)
 * License: GNU General Public License (http://www.gnu.org/licenses/gpl.html)
 */
// <nowiki>
var DownloadPDF = {

	init: function () {
		$( '#mw-content-text' ).find( '.DownloadPDF' ).on( 'click', DownloadPDF.makePDF );
	},

	makePDF: function () {

		// Get the list of pages
		var $button = $( this );
		var separator = $button.data( 'separator' );
		var pages = $button.data( 'pages' );
		pages = pages.split( separator );

		// Make the wikitext of the book
		var wikitext = '';
		for ( var page of pages ) {
			wikitext += '\n<div class="DownloadPDF-chapter">';
			wikitext += '\n<h1 class="DownloadPDF-chapter-title">' + page + '</h1>';
			wikitext += '\n<div class="DownloadPDF-chapter-content">{{:' + page + '}}</div>';
			wikitext += '\n</div>';
		}

		// Get the HTML of the book
		new mw.Api().parse( wikitext ).then( function ( html ) {

			// Save HTML of whatever page we're at to restore it later
			var $pageContent = $( '#mw-content-text .mw-parser-output' );
			var pageContent = $pageContent.html();

			// Replace the page HTML for the book HTML
			$pageContent.html( html );

			// Wait for all images to load
			// @todo Use something like https://stackoverflow.com/a/75570052/809356
			setTimeout( function () {

				// Hide elements we don't want to print
				var $firstHeading = $( '#firstHeading' );
				$firstHeading.hide();

				// Finally, print
				window.print();

				// After print, restore the original page
				$firstHeading.show();
				$pageContent.html( pageContent );

			}, 1000 );
		} );
	}
};

$( DownloadPDF.init );
// </nowiki>