// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see
and elements have white-space:pre by default, which causes
// long lines (SQL statements, URLs, etc.) to exceed the PDF page width.
// We force wrapping so NO content is lost or clipped.
els = document.querySelectorAll('pre, code, .code, .CodeMirror, samp, kbd');
for (i = 0; i < els.length; i++) {
els[i].style.setProperty('white-space', 'pre-wrap', 'important');
els[i].style.setProperty('word-wrap', 'break-word', 'important');
els[i].style.setProperty('overflow-wrap', 'break-word', 'important');
els[i].style.setProperty('word-break', 'break-all', 'important');
els[i].style.setProperty('max-width', '100%', 'important');
els[i].style.setProperty('overflow-x', 'visible', 'important');
els[i].style.setProperty('box-sizing', 'border-box', 'important');
// Also fix any ancestor with an explicit wide inline width.
var codeParent = els[i].parentElement;
while (codeParent && codeParent !== document.body) {
var pw = codeParent.style.width;
if (pw && pw !== '100%' && pw !== 'auto') {
codeParent.style.setProperty('width', '100%', 'important');
codeParent.style.setProperty('max-width', '100%', 'important');
codeParent.style.setProperty('box-sizing', 'border-box', 'important');
}
// Stop at content boundaries.
if (codeParent.classList && (
codeParent.classList.contains('exe-content') ||
codeParent.classList.contains('page') ||
codeParent.id === 'outer'
)) {
break;
}
codeParent = codeParent.parentElement;
}
}
// Constrain any generic container that overflows
// (blockquotes, wide divs, etc.) — wrap text, don't clip.
els = document.querySelectorAll('blockquote, .exe-content div');
for (i = 0; i < els.length; i++) {
if (els[i].scrollWidth > els[i].clientWidth + 5) {
els[i].style.setProperty('overflow-wrap', 'break-word', 'important');
els[i].style.setProperty('word-wrap', 'break-word', 'important');
els[i].style.setProperty('max-width', '100%', 'important');
els[i].style.setProperty('width', '100%', 'important');
}
}
// Resolve CSS custom properties that html2canvas cannot process.
// Read computed styles and apply them inline so html2canvas sees real values.
els = document.querySelectorAll('.exe-content .box header');
for (i = 0; i < els.length; i++) {
var computed = window.getComputedStyle(els[i]);
els[i].style.backgroundColor = computed.backgroundColor;
els[i].style.color = computed.color;
}
// Also resolve CSS variables on box content backgrounds.
els = document.querySelectorAll('.exe-content .box .box-content, .exe-content .box .idevice_body');
for (i = 0; i < els.length; i++) {
var comp = window.getComputedStyle(els[i]);
if (comp.backgroundColor && comp.backgroundColor !== 'rgba(0, 0, 0, 0)') {
els[i].style.backgroundColor = comp.backgroundColor;
}
}
if (typeof console !== 'undefined') {
console.log('[Recopila PDF] DOM prepared for rendering');
}
};
/**
* Extract the document title for the PDF filename.
*
* Supports eXeLearning v2 (h1#nodeTitle) and v3 (h2.page-title) structures.
* Skips elements with empty or whitespace-only text content.
*
* @return {string} The document title or 'document' as fallback.
*/
var getDocumentTitle = function () {
var candidates = [
document.querySelector('h1#nodeTitle'),
document.querySelector('h2.page-title'),
document.querySelector('h1'),
document.querySelector('h2')
];
for (var i = 0; i < candidates.length; i++) {
if (candidates[i]) {
// Use textContent to get raw text, strip whitespace and non-breaking spaces.
var text = (candidates[i].textContent || '')
.replace(/[\u00A0]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (text.length > 0) {
return text;
}
}
}
return 'document';
};
/**
* Generate a PDF from the rendered SCORM content.
*
* Iterates through all content pages, rendering each to a separate
* PDF page. Shows progress overlay during generation.
* Includes error handling and timeout protection.
*/
var generatePDF = function () {
var strings = getStrings();
var locker = lockScroll();
// Verify html2pdf library is available.
if (typeof html2pdf !== 'function') {
if (typeof console !== 'undefined' && console.error) {
console.error('[Recopila PDF] html2pdf library not loaded');
}
removeLockScreen();
locker.stop();
return;
}
// Prepare DOM for rendering (fix v3 CSS visibility classes).
prepareForRendering();
var pages = findContentPages();
// Safety check: if no pages found, remove overlay and exit.
if (!pages || pages.length === 0) {
if (typeof console !== 'undefined') {
console.warn('[Recopila PDF] No content pages found');
}
removeLockScreen();
locker.stop();
return;
}
var titleDocument = getDocumentTitle();
var underscoreTitleDocument = titleDocument.split(' ').join('_');
// Ensure filename is valid (not empty or only underscores/whitespace).
if (!underscoreTitleDocument || /^[_\s]*$/.test(underscoreTitleDocument)) {
underscoreTitleDocument = 'document';
}
var totalPages = pages.length;
// Reduce canvas scale for large documents to prevent memory issues.
// At scale 2, each A4 page is ~3174x4490px. With 10+ pages this
// can exceed browser memory limits and cause html2canvas to fail.
var canvasScale = (totalPages > 10) ? 1 : 2;
var opt = {
margin: 15,
pagebreak: {mode: ['avoid-all', 'css', 'legacy']},
enableLinks: true,
image: {type: 'jpeg', quality: 0.95},
html2canvas: {
scale: canvasScale,
logging: false,
useCORS: true,
allowTaint: true,
scrollX: 0,
scrollY: -window.scrollY
},
jsPDF: {unit: 'mm', format: 'a4', orientation: 'portrait'}
};
// Safety timeout: if generation exceeds 5 minutes, clean up.
var timeoutId = setTimeout(function () {
if (typeof console !== 'undefined') {
console.error('[Recopila PDF] Generation timed out after 5 minutes');
}
infoToUser('Error', 'Timeout');
setTimeout(function () {
removeLockScreen();
locker.stop();
}, 3000);
}, 300000);
if (typeof console !== 'undefined') {
console.log('[Recopila PDF] Starting generation: ' + totalPages
+ ' pages, scale=' + canvasScale);
}
// Show initial progress.
infoToUser(strings.generatingpdf, '1 / ' + totalPages);
try {
// Build the promise chain: start with the first page.
var worker = html2pdf().set(opt).from(pages[0]).toContainer().toCanvas().toPdf();
// Chain remaining pages with progress updates.
for (var i = 1; i < totalPages; i++) {
worker = worker.get('pdf').then(
(function (index) {
return function (pdf) {
pdf.addPage();
infoToUser(null, (index + 1) + ' / ' + totalPages);
if (typeof console !== 'undefined') {
console.log('[Recopila PDF] Processing page ' + (index + 1)
+ ' / ' + totalPages);
}
};
})(i)
).set(opt).from(pages[i]).toContainer().toCanvas().toPdf();
}
// Final step: save PDF and clean up.
worker.get('pdf').then(function (pdf) {
clearTimeout(timeoutId);
var elWait = document.getElementById('userespere');
if (elWait) {
elWait.innerHTML = '';
}
infoToUser(strings.generationcomplete, '');
if (typeof console !== 'undefined') {
console.log('[Recopila PDF] Generation complete, saving file');
}
pdf.save(underscoreTitleDocument + '.pdf');
setTimeout(function () {
removeLockScreen();
locker.stop();
}, 2000);
})['catch'](function (error) {
clearTimeout(timeoutId);
// Log the error and clean up so the user isn't stuck.
if (typeof console !== 'undefined' && console.error) {
console.error('[Recopila PDF] Generation failed:', error);
}
infoToUser('Error', String(error && error.message ? error.message : error || 'PDF generation failed'));
setTimeout(function () {
removeLockScreen();
locker.stop();
}, 4000);
});
} catch (err) {
// Synchronous error during chain setup.
clearTimeout(timeoutId);
if (typeof console !== 'undefined' && console.error) {
console.error('[Recopila PDF] Setup error:', err);
}
infoToUser('Error', String(err && err.message ? err.message : err || 'PDF setup failed'));
setTimeout(function () {
removeLockScreen();
locker.stop();
}, 4000);
}
};
generatePDF();