// 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 . /** * Client-side PDF generation for block_recopila. * * Converts the rendered SCORM content page into a downloadable PDF * using html2pdf.js, html2canvas, and jsPDF. * * Supports both eXeLearning v2 (div#outer) and v3 (main.page) structures. * * @package block_recopila * @copyright 2026 Ayesa Engineering * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * Get localized strings from PHP or fallback to defaults. * * @return {Object} Localized string map. */ var getStrings = function () { return window.RECOPILA_STRINGS || { generatingpdf: 'Generating PDF content...', generationcomplete: 'Generation complete', pleasewait: 'Please wait...' }; }; /** * Find all elements matching a tag name and id attribute. * * @param {string} tagName The HTML tag name to search. * @param {string} idValue The id attribute value to match. * @return {Array} Array of matching DOM elements. */ var getElementsById = function (tagName, idValue) { var elementCollection = []; var allElements = document.getElementsByTagName(tagName); for (var i = 0; i < allElements.length; i++) { if (allElements[i].id === idValue) { elementCollection.push(allElements[i]); } } return elementCollection; }; /** * Remove the lock-screen overlay from the page. * * @return {void} */ var removeLockScreen = function () { var lockScreen = document.getElementsByClassName('lock-screen')[0]; if (lockScreen && lockScreen.parentNode) { lockScreen.parentNode.removeChild(lockScreen); } }; /** * Find the content page elements for PDF generation. * * Supports both eXeLearning v2 structure (div#outer) and v3 (main.page). * Falls back to direct body children if neither structure is found. * * @return {Array|NodeList} The page elements to convert to PDF. */ var findContentPages = function () { // eXeLearning v2: content is wrapped in div#outer elements. var pages = getElementsById('div', 'outer'); if (pages.length > 0) { return pages; } // eXeLearning v3: content is wrapped in main.page elements. pages = document.querySelectorAll('main.page'); if (pages.length > 0) { return pages; } // Fallback: use div.exe-content elements (v3 wrapper). pages = document.querySelectorAll('div.exe-content'); if (pages.length > 0) { return pages; } // Final fallback: use all non-utility direct children of body. pages = document.querySelectorAll('body > div:not(.lock-screen):not([style*="page-break"])'); if (pages.length > 0) { return pages; } // Absolute fallback: wrap the entire body. return [document.body]; }; /** * Update the loading overlay with status information. * * @param {string|null} txtTitle New title text, or null to keep current. * @param {string} newInfo New info text to display. */ var infoToUser = function (txtTitle, newInfo) { var title = document.getElementById('titleInfo'); if (title && txtTitle) { title.innerHTML = txtTitle; } var el = document.getElementById('infoPerPage'); if (el) { el.innerHTML = newInfo; } }; /** * Lock the scroll position to prevent movement during PDF generation. * * @return {Object} Object with a stop() method to unlock scrolling. */ var lockScroll = function () { var lockX = window.scrollX; var lockY = window.scrollY; function lockIt() { window.scrollTo(lockX, lockY); return false; } window.addEventListener('scroll', lockIt, false); return { stop: function () { window.removeEventListener('scroll', lockIt, false); } }; }; /** * Prepare the DOM for PDF rendering. * * eXeLearning v3 uses CSS classes like 'pre-js' and 'siteNav-hidden' that * depend on JavaScript to toggle visibility. Since head scripts are excluded * in PDF mode, these classes may hide content. This function removes them * and applies layout fixes so html2canvas can capture clean, A4-friendly content. * * @return {void} */ var prepareForRendering = function () { var i, j, els; // eXeLearning v3: remove 'pre-js' class that may hide interactive content. els = document.querySelectorAll('.exe-content.pre-js'); for (i = 0; i < els.length; i++) { els[i].classList.remove('pre-js'); els[i].classList.add('js'); } // Remove 'siteNav-hidden' which hides navigation elements. els = document.querySelectorAll('.siteNav-hidden'); for (i = 0; i < els.length; i++) { els[i].classList.remove('siteNav-hidden'); } // Collapse interactive toggle buttons used in v3 to static content. els = document.querySelectorAll('button.box-toggle'); for (i = 0; i < els.length; i++) { els[i].style.display = 'none'; } // Ensure collapsed/minimized boxes are expanded for PDF capture. els = document.querySelectorAll('article.minimized'); for (i = 0; i < els.length; i++) { els[i].classList.remove('minimized'); } // Hide navigation, footer, and other non-content elements. var hideSelectors = [ 'nav.site-nav', '.site-nav', '.exe-pagination', 'footer', '#made-with-eXe', '.exe-go-top', '#teacher-mode-toggler-wrapper', '#exe-client-search', '#exe-client-search-reset', '.page-counter' ]; for (i = 0; i < hideSelectors.length; i++) { els = document.querySelectorAll(hideSelectors[i]); for (j = 0; j < els.length; j++) { els[j].style.display = 'none'; } } // Fix V3 fixed-position headers: convert to static flow. els = document.querySelectorAll('.page > header, main.page > header'); for (i = 0; i < els.length; i++) { var hdr = els[i]; hdr.style.position = 'relative'; hdr.style.top = 'auto'; hdr.style.left = 'auto'; hdr.style.right = 'auto'; hdr.style.height = 'auto'; hdr.style.width = '100%'; hdr.style.zIndex = 'auto'; hdr.style.marginBottom = '10px'; hdr.style.boxSizing = 'border-box'; } // Fix V3 header titles: remove ellipsis/overflow. els = document.querySelectorAll('.page > header .package-title, .page > header .page-title'); for (i = 0; i < els.length; i++) { els[i].style.position = 'relative'; els[i].style.width = '100%'; els[i].style.whiteSpace = 'normal'; els[i].style.overflow = 'visible'; els[i].style.textOverflow = 'clip'; els[i].style.padding = '2px 0'; } // Fix V3 package subtitle absolute positioning. els = document.querySelectorAll('.package-subtitle'); for (i = 0; i < els.length; i++) { els[i].style.position = 'relative'; els[i].style.left = 'auto'; els[i].style.bottom = 'auto'; } // Force all images to constrain within their container. els = document.querySelectorAll('img'); for (i = 0; i < els.length; i++) { els[i].style.maxWidth = '100%'; els[i].style.height = 'auto'; } // Constrain tables to fit within the A4 page width for PDF. // Tables in eXeLearning v3 often overflow the page boundaries. els = document.querySelectorAll('table'); for (i = 0; i < els.length; i++) { var table = els[i]; var parent = table.parentElement; // Measure natural width before constraining. var parentWidth = parent ? parent.clientWidth : document.body.clientWidth; var naturalWidth = table.scrollWidth; // Apply table constraints to force content within page width. table.style.maxWidth = '100%'; table.style.width = '100%'; table.style.tableLayout = 'fixed'; table.style.overflowWrap = 'break-word'; table.style.wordWrap = 'break-word'; // If the table was significantly wider than its container, // reduce the font size proportionally (minimum 7px). if (naturalWidth > parentWidth * 1.15 && parentWidth > 0) { var scaleFactor = parentWidth / naturalWidth; var baseFontSize = 14; var newFontSize = Math.max(7, Math.round(baseFontSize * scaleFactor)); table.style.fontSize = newFontSize + 'px'; } // Ensure all cells can wrap text and don't force overflow. var cells = table.querySelectorAll('td, th'); for (j = 0; j < cells.length; j++) { cells[j].style.overflowWrap = 'break-word'; cells[j].style.wordWrap = 'break-word'; cells[j].style.overflow = 'hidden'; cells[j].style.maxWidth = '100%'; } } // Fix containers with explicit inline widths that exceed the page. // eXeLearning uses elements like
// which are much wider than A4 content area (~680px). Override these to fit. els = document.querySelectorAll('.codigo, .elemento_centrado, div[style*="width"]'); for (i = 0; i < els.length; i++) { var inlineW = els[i].style.width; if (inlineW && inlineW !== '100%' && inlineW !== 'auto') { els[i].style.setProperty('width', '100%', 'important'); els[i].style.setProperty('max-width', '100%', 'important'); els[i].style.setProperty('box-sizing', 'border-box', 'important'); } } // Constrain code blocks and preformatted text to wrap instead of overflow. //
 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();