File size: 6,798 Bytes
16855a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c81a9
16855a8
 
 
34c81a9
16855a8
 
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16855a8
 
34c81a9
16855a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import HTMLtoDOCX from 'html-to-docx';
import puppeteer from 'puppeteer';
import * as cheerio from 'cheerio';
import ExcelJS from 'exceljs';

// Convert HTML to DOCX Buffer
export const convertToDocx = async (htmlContent, title) => {
    // html-to-docx expects a string and options
    const fileBuffer = await HTMLtoDOCX(htmlContent, null, {
        table: { row: { cantSplit: true } },
        footer: true,
        pageNumber: true,
        title: title
    });
    return fileBuffer;
};

// Convert HTML to PDF Buffer — rasterizes Three.js canvases via Puppeteer element screenshots
export const convertToPdf = async (htmlContent) => {
    const browser = await puppeteer.launch({
        headless: 'new',
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--enable-webgl', '--use-gl=swiftshader']
    });

    try {
        const page = await browser.newPage();
        await page.setViewport({ width: 1280, height: 1800, deviceScaleFactor: 2 });

        // Load page — wait for network idle so importmaps + CDN scripts resolve
        await page.setContent(htmlContent, { waitUntil: 'networkidle0', timeout: 30000 });

        // Check if page has any Three.js canvases
        const hasThreeCanvases = await page.evaluate(
            () => document.querySelectorAll('canvas[data-threejs]').length > 0
        );

        if (hasThreeCanvases) {
            // Give Three.js time to initialise and render its first frame
            console.log('PDF export: Three.js canvases detected — waiting for render...');
            await new Promise(r => setTimeout(r, 4000));

            // Get all canvas element handles
            const canvasHandles = await page.$$('canvas[data-threejs]');
            let rasterized = 0;

            for (const canvasHandle of canvasHandles) {
                try {
                    // Take a screenshot of just this element using Puppeteer's compositor capture
                    // This works regardless of preserveDrawingBuffer since it captures screen pixels
                    const screenshotBuf = await canvasHandle.screenshot({ type: 'png' });
                    const base64 = screenshotBuf.toString('base64');
                    const dataUrl = `data:image/png;base64,${base64}`;

                    // Replace canvas with <img> in the page DOM
                    await page.evaluate((canvas, src) => {
                        const img = document.createElement('img');
                        img.src = src;
                        img.style.width = Math.min(canvas.offsetWidth, 700) + 'px';
                        img.style.maxWidth = '100%';
                        img.style.height = 'auto';
                        img.style.display = 'block';
                        img.style.margin = '0 auto';
                        img.style.borderRadius = '4px';
                        img.style.border = '1px solid #d0d8e8';
                        img.alt = '3D Perspective View (rendered for PDF)';
                        canvas.parentNode.replaceChild(img, canvas);
                    }, canvasHandle, dataUrl);

                    rasterized++;
                } catch (canvasErr) {
                    console.warn('PDF export: could not screenshot canvas, hiding it:', canvasErr.message);
                    // Gracefully replace with a text note
                    await page.evaluate((canvas) => {
                        canvas.style.display = 'none';
                        const note = document.createElement('div');
                        note.style.cssText = 'padding:16px;text-align:center;font-size:11px;color:#718096;font-family:Arial;border:1px dashed #e2e8f0;border-radius:4px;margin:8px auto;max-width:700px';
                        note.textContent = '[ 3D Perspective View — open this document in a browser for an interactive view ]';
                        canvas.parentNode.insertBefore(note, canvas);
                    }, canvasHandle);
                }
            }

            console.log(`PDF export: rasterized ${rasterized}/${canvasHandles.length} Three.js canvas(es)`);
        }

        // Hide any remaining canvases that weren't tagged (safety net)
        await page.evaluate(() => {
            document.querySelectorAll('canvas:not(img)').forEach(c => {
                if (!c.getAttribute('data-threejs')) return;
                c.style.display = 'none';
            });
        });

        const pdfBuffer = await page.pdf({
            format: 'A4',
            printBackground: true,
            margin: { top: '15px', bottom: '20px', left: '15px', right: '15px' }
        });

        return pdfBuffer;
    } finally {
        await browser.close();
    }
};


// NEW: Convert to XLSX using ExcelJS
export const convertToXlsx = async (htmlContent, title) => {
    const $ = cheerio.load(htmlContent);
    const table = $('table').first();

    if (table.length === 0) {
        throw new Error("No table found to convert.");
    }

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(title.substring(0, 30) || 'Sheet 1'); // Excel limits sheet names to 31 chars

    // Parse Headers (th)
    const headerRow = [];
    table.find('tr').first().find('th').each((i, el) => {
        headerRow.push($(el).text().trim());
    });
    
    // If no TH, try first row TD
    if(headerRow.length === 0) {
         table.find('tr').first().find('td').each((i, el) => {
            headerRow.push($(el).text().trim());
        });
    }

    // Add Header Row with Styling
    const header = worksheet.addRow(headerRow);
    header.eachCell((cell) => {
        cell.font = { bold: true, color: { argb: 'FFFFFFFF' } };
        cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2E7D32' } }; // Emerald Green
    });

    // Parse Data Rows
    table.find('tr').each((i, row) => {
        // Skip header row if we already parsed it
        if ($(row).find('th').length > 0) return;

        const rowData = [];
        $(row).find('td').each((j, col) => {
            // Handle basic numbers vs strings
            const text = $(col).text().trim();
            const num = parseFloat(text.replace(/,/g, '')); // Simple check for currency/numbers
            rowData.push(!isNaN(num) && text.match(/\d/) ? num : text);
        });
        
        if (rowData.length > 0) {
            worksheet.addRow(rowData);
        }
    });

    // Auto-width columns (basic estimation)
    worksheet.columns.forEach(column => {
        column.width = 20;
    });

    // Write to buffer
    const buffer = await workbook.xlsx.writeBuffer();
    return buffer;
};