first
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Uji alur pratinjau PDF di browser:
|
||||
* 1. buka file HTML di Chrome/Edge headless
|
||||
* 2. klik tombol "Pratinjau PDF"
|
||||
* 3. pastikan modal terbuka dan PDF termuat di dalam iframe (bukan langsung diunduh)
|
||||
* 4. ambil PDF dari blob URL, lalu cek ukuran halaman & pindai QR-nya
|
||||
*
|
||||
* Pemakaian: node scripts/verify-browser-preview.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { spawn } = require('child_process');
|
||||
const { PNG } = require('pngjs');
|
||||
const jsQR = require('jsqr');
|
||||
const { PDFDocument } = require('pdf-lib');
|
||||
|
||||
const BROWSERS = [
|
||||
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
||||
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
||||
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
|
||||
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'
|
||||
];
|
||||
|
||||
function wait(ms) {
|
||||
return new Promise(function (resolve) { setTimeout(resolve, ms); });
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const browser = BROWSERS.find(function (candidate) { return fs.existsSync(candidate); });
|
||||
if (!browser) {
|
||||
process.stderr.write('Browser Chrome/Edge tidak ditemukan.\n');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const htmlFile = path.resolve(process.argv[2] || 'template_label_qr_eppos_rp4610b_100mm_3kolom.html');
|
||||
const port = 9500 + Math.floor(Math.random() * 300);
|
||||
const proc = spawn(browser, [
|
||||
'--headless=new',
|
||||
'--disable-gpu',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--user-data-dir=' + path.join(os.tmpdir(), 'label-preview-' + Date.now()),
|
||||
'--remote-debugging-port=' + port,
|
||||
'about:blank'
|
||||
], { stdio: 'ignore' });
|
||||
|
||||
let cdp = null;
|
||||
try {
|
||||
let version = null;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
try {
|
||||
version = await (await fetch('http://127.0.0.1:' + port + '/json/version')).json();
|
||||
break;
|
||||
} catch (err) {
|
||||
await wait(250);
|
||||
}
|
||||
}
|
||||
if (!version) { throw new Error('DevTools tidak dapat dihubungi'); }
|
||||
|
||||
const ws = new WebSocket(version.webSocketDebuggerUrl);
|
||||
await new Promise(function (resolve, reject) {
|
||||
ws.addEventListener('open', resolve);
|
||||
ws.addEventListener('error', reject);
|
||||
});
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', function (event) {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
const entry = pending.get(message.id);
|
||||
pending.delete(message.id);
|
||||
if (message.error) { entry.reject(new Error(message.error.message)); }
|
||||
else { entry.resolve(message.result); }
|
||||
}
|
||||
});
|
||||
const send = function (method, params, sessionId) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const messageId = ++id;
|
||||
pending.set(messageId, { resolve: resolve, reject: reject });
|
||||
ws.send(JSON.stringify({ id: messageId, method: method, params: params || {}, sessionId: sessionId }));
|
||||
});
|
||||
};
|
||||
|
||||
const target = await send('Target.createTarget', { url: 'about:blank' });
|
||||
const attached = await send('Target.attachToTarget', { targetId: target.targetId, flatten: true });
|
||||
const sessionId = attached.sessionId;
|
||||
await send('Page.enable', {}, sessionId);
|
||||
await send('Runtime.enable', {}, sessionId);
|
||||
await send('Page.navigate', { url: 'file:///' + htmlFile.replace(/\\/g, '/') }, sessionId);
|
||||
await wait(2500);
|
||||
|
||||
// Klik tombol "Pratinjau PDF"
|
||||
const click = await send('Runtime.evaluate', {
|
||||
expression: 'document.getElementById("btn-pdf").click(); "klik"',
|
||||
returnByValue: true
|
||||
}, sessionId);
|
||||
await wait(2500);
|
||||
|
||||
const state = await send('Runtime.evaluate', {
|
||||
expression: 'JSON.stringify({' +
|
||||
'modalTerbuka: !document.getElementById("pdf-modal").hidden,' +
|
||||
'iframeSrc: (document.getElementById("pdf-frame").src||"").slice(0,20),' +
|
||||
'info: document.getElementById("pdf-info").textContent,' +
|
||||
'tombolCetakAda: !!document.getElementById("btn-print"),' +
|
||||
'tombolUnduhAda: !!document.getElementById("btn-download")' +
|
||||
'})',
|
||||
returnByValue: true
|
||||
}, sessionId);
|
||||
const summary = JSON.parse(state.result.value);
|
||||
|
||||
// Ambil PDF dari blob URL di dalam halaman
|
||||
const pdfBase64 = await send('Runtime.evaluate', {
|
||||
expression: '(async () => {' +
|
||||
'const src = document.getElementById("pdf-frame").src;' +
|
||||
'const buf = await (await fetch(src)).arrayBuffer();' +
|
||||
'let binary = ""; const bytes = new Uint8Array(buf);' +
|
||||
'for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); }' +
|
||||
'return btoa(binary);' +
|
||||
'})()',
|
||||
awaitPromise: true,
|
||||
returnByValue: true
|
||||
}, sessionId);
|
||||
|
||||
const outFile = path.resolve('output', 'browser-preview.pdf');
|
||||
fs.writeFileSync(outFile, Buffer.from(pdfBase64.result.value, 'base64'));
|
||||
|
||||
const pdf = await PDFDocument.load(fs.readFileSync(outFile));
|
||||
const sizes = pdf.getPages().map(function (page) {
|
||||
const size = page.getSize();
|
||||
return {
|
||||
pt: [Number(size.width.toFixed(4)), Number(size.height.toFixed(4))],
|
||||
mm: [Number((size.width / 72 * 25.4).toFixed(3)), Number((size.height / 72 * 25.4).toFixed(3))]
|
||||
};
|
||||
});
|
||||
|
||||
const mupdf = await import('mupdf');
|
||||
const doc = mupdf.Document.openDocument(fs.readFileSync(outFile), 'application/pdf');
|
||||
const page = doc.loadPage(0);
|
||||
const pixmap = page.toPixmap(mupdf.Matrix.scale(300 / 72, 300 / 72), mupdf.ColorSpace.DeviceRGB, false, false);
|
||||
const raw = pixmap.asPNG();
|
||||
const png = PNG.sync.read(Buffer.from(raw.buffer ? raw.buffer : raw, raw.byteOffset || 0, raw.byteLength || raw.length));
|
||||
|
||||
const LabelLayout = require('../src/layout');
|
||||
const layout = LabelLayout.create();
|
||||
const boxes = layout.contentBoxes(0);
|
||||
const ppm = 300 / 25.4;
|
||||
const x = Math.round((boxes.qrBox.xMm - 2) * ppm);
|
||||
const y = Math.round((boxes.qrBox.yMm - 2) * ppm);
|
||||
const w = Math.round((boxes.qrBox.widthMm + 4) * ppm);
|
||||
const h = Math.round((boxes.qrBox.heightMm + 4) * ppm);
|
||||
const crop = new Uint8ClampedArray(w * h * 4);
|
||||
for (let r = 0; r < h; r++) {
|
||||
for (let c = 0; c < w; c++) {
|
||||
const si = ((y + r) * png.width + (x + c)) * 4;
|
||||
const di = (r * w + c) * 4;
|
||||
crop[di] = png.data[si];
|
||||
crop[di + 1] = png.data[si + 1];
|
||||
crop[di + 2] = png.data[si + 2];
|
||||
crop[di + 3] = 255;
|
||||
}
|
||||
}
|
||||
const decoded = jsQR(crop, w, h);
|
||||
|
||||
const shot = await send('Page.captureScreenshot', { format: 'png' }, sessionId);
|
||||
const shotFile = path.resolve('output', 'browser-preview.png');
|
||||
fs.writeFileSync(shotFile, Buffer.from(shot.data, 'base64'));
|
||||
|
||||
process.stdout.write(JSON.stringify({
|
||||
browser: path.basename(browser),
|
||||
klik: click.result.value,
|
||||
ui: summary,
|
||||
pdfFile: outFile,
|
||||
screenshot: shotFile,
|
||||
jumlahHalaman: pdf.getPageCount(),
|
||||
pageSizes: sizes,
|
||||
qrFirstLabel: decoded ? decoded.data : null
|
||||
}, null, 2) + '\n');
|
||||
} finally {
|
||||
if (cdp) { cdp.close(); }
|
||||
proc.kill();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(function (err) {
|
||||
process.stderr.write('Error: ' + err.stack + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in New Issue
Block a user