User:Incnis Mrsi/PDF-PNG.js
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)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
// Fixes for some deficiencies of [[mw:Extension:PdfHandler]]
var jpgE = /jpg$/;
var JP_E_G = /JPE?G/;
function PdfToPNG() {
var images = document.getElementsByTagName( "img" );
var replaced = 0; // counter
for (var i = 0, n = images.length; i < n; i++) {
var src = images[i].getAttribute('src');
if ( src.match(/\/page.*\.jpg$/) // MediaWiki PDF → JPEG conversion
) {
images[i].setAttribute('src', src.replace(jpgE, 'png') );
replaced++;
}
}
if (replaced) {
// The following code is relevent to File: pages only
var resolutioninfo = document.getElementsByClassName( "mw-filepage-resolutioninfo" );
if (
resolutioninfo.length
// && resolutioninfo[0].innerHTML.match(JP_E_G) -- made redundant by later checks
) {
var childr = resolutioninfo[0].children;
if ( (childr.length > 1) && (childr[1].tagName == 'SPAN') ) {
// We have (in resolutioninfo[0]) the mw-filepage-resolutioninfo thing arranged as we expected:
var JPGtext = resolutioninfo[0].firstChild;
if ( JPGtext.textContent.match(JP_E_G) ) {
var newRes = childr[1].cloneNode(true); // the future list of PNG thumb links in other resolutions
// add the *current* resolution to the list of .jpg links
childr[1].insertBefore(childr[0].cloneNode(true), childr[1].lastNode);
// now change .jpg to .png in the first (the current image) link...
if (childr[0].tagName == 'A') {
childr[0].setAttribute('href',
childr[0].getAttribute('href').replace(jpgE, 'png')
);
};
// ... and edit the respective text
var tn = document.createTextNode( JPGtext.textContent.replace(JP_E_G, 'PNG') );
resolutioninfo[0].insertBefore(tn, JPGtext);
JPGtext.remove();
// The old other-resolutions now points to JPEGs, whereas on the page we already have PNG
var otherres = childr[1].firstChild;
tn = document.createTextNode(' JPEG: ');
childr[1].insertBefore(tn, otherres);
otherres.remove();
// And now make replacements in newRes
var ress = newRes.children;
for (var j = 0, n = ress.length; j < n; j++) {
if (ress[j].tagName == 'A') {
ress[j].setAttribute('href',
ress[j].getAttribute('href').replace(jpgE, 'png')
);
}
};
resolutioninfo[0].insertBefore(newRes, childr[1]);
} // match(JP_E_G)
} // childr[1].tagName == 'SPAN'
else {
// childr.length may be 0 on cross-wiki (not local) File:⋯.pdf pages
if (childr.length) {
alert('Error at PDF-PNG.js: the mw-filepage-resolutioninfo thing is present and has ' +
childr.length + ' child elements, but can’t locate “other resolutions” links among them.');
}
}
} // resolutioninfo.length
} // replaced
}; // function PdfToPNG()
// At the end, add hooks:
$( document ).load( PdfToPNG );
mw.hook( 'wikipage.content' ).add( PdfToPNG );