first
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Bundel untuk browser (tanpa CDN):
|
||||
* 1. assets/qrcode-core.js - core QR Code dari paket npm "qrcode"
|
||||
* 2. assets/helvetica-metrics.js - tabel lebar glif Helvetica & Helvetica-Bold
|
||||
*
|
||||
* Tabel metrik diambil dari file AFM milik PDFKit sehingga pengukuran teks di
|
||||
* browser identik dengan pengukuran di dalam PDF (tidak ada teks terpotong).
|
||||
*
|
||||
* Jalankan: node scripts/build-browser-assets.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const esbuild = require('esbuild');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const assetsDir = path.join(root, 'assets');
|
||||
const qrOutfile = path.join(assetsDir, 'qrcode-core.js');
|
||||
const metricsOutfile = path.join(assetsDir, 'helvetica-metrics.js');
|
||||
|
||||
function parseAfm(afmPath) {
|
||||
const content = fs.readFileSync(afmPath, 'utf8');
|
||||
const widths = {};
|
||||
const re = /^\s*C\s+(-?\d+)\s*;\s*WX\s+([\d.]+)\s*;/gm;
|
||||
let match;
|
||||
while ((match = re.exec(content)) !== null) {
|
||||
widths[Number(match[1])] = Number(match[2]);
|
||||
}
|
||||
return widths;
|
||||
}
|
||||
|
||||
function buildMetrics() {
|
||||
const afmDir = path.join(root, 'node_modules', 'pdfkit', 'js', 'data');
|
||||
const regular = parseAfm(path.join(afmDir, 'Helvetica.afm'));
|
||||
const bold = parseAfm(path.join(afmDir, 'Helvetica-Bold.afm'));
|
||||
const pick = function (widths) {
|
||||
const out = {};
|
||||
for (let code = 32; code <= 126; code++) {
|
||||
out[code] = widths[code] !== undefined ? widths[code] : 556;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const regularTable = pick(regular);
|
||||
const boldTable = pick(bold);
|
||||
const serialise = function (table) {
|
||||
return Object.keys(table).map(function (code) { return code + ':' + table[code]; }).join(',');
|
||||
};
|
||||
|
||||
const banner = '/* Metrik lebar glif Helvetica & Helvetica-Bold (dari AFM PDFKit) - untuk pengukuran teks di browser. */';
|
||||
const body = [
|
||||
'(function (root) {',
|
||||
' "use strict";',
|
||||
' var REGULAR = {' + serialise(regularTable) + '};',
|
||||
' var BOLD = {' + serialise(boldTable) + '};',
|
||||
' var FALLBACK = 556;',
|
||||
' function widthOf(code, weight) {',
|
||||
' var table = weight === "bold" ? BOLD : REGULAR;',
|
||||
' var value = table[code];',
|
||||
' return value === undefined ? FALLBACK : value;',
|
||||
' }',
|
||||
' function measure(text, sizeMm, weight) {',
|
||||
' var str = String(text === undefined || text === null ? "" : text);',
|
||||
' var total = 0;',
|
||||
' for (var i = 0; i < str.length; i++) {',
|
||||
' total += widthOf(str.charCodeAt(i), weight);',
|
||||
' }',
|
||||
' return total / 1000 * sizeMm;',
|
||||
' }',
|
||||
' root.HelveticaMetrics = { measure: measure, widthOf: widthOf, CAP_HEIGHT: 0.717 };',
|
||||
'})(typeof self !== "undefined" ? self : this);'
|
||||
].join('\n');
|
||||
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
fs.writeFileSync(metricsOutfile, banner + '\n' + body + '\n', 'utf8');
|
||||
return metricsOutfile;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [require.resolve('qrcode/lib/core/qrcode.js')],
|
||||
bundle: true,
|
||||
format: 'iife',
|
||||
globalName: 'QRCodeCore',
|
||||
platform: 'browser',
|
||||
target: ['es2017'],
|
||||
legalComments: 'none',
|
||||
outfile: qrOutfile,
|
||||
banner: {
|
||||
js: '/* QR Code core - bundel dari paket npm "qrcode" untuk pemakaian offline di browser. */'
|
||||
}
|
||||
});
|
||||
|
||||
buildMetrics();
|
||||
|
||||
process.stdout.write(
|
||||
'assets/qrcode-core.js ' + Math.round(fs.statSync(qrOutfile).size / 1024) + ' KB\n' +
|
||||
'assets/helvetica-metrics.js ' + Math.round(fs.statSync(metricsOutfile).size / 1024) + ' KB\n'
|
||||
);
|
||||
}
|
||||
|
||||
main().catch(function (err) {
|
||||
process.stderr.write('Gagal membuat bundel browser: ' + err.message + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Menyiapkan folder dist/ untuk deploy statis (Vercel).
|
||||
*
|
||||
* Aplikasi browser hanya membutuhkan:
|
||||
* - index.html dari template utama
|
||||
* - src/data.js, src/layout.js, src/svg.js
|
||||
* - assets/qrcode-core.js, assets/helvetica-metrics.js
|
||||
*
|
||||
* Jalankan: node scripts/build-static.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const outDir = path.join(root, 'dist');
|
||||
const template = path.join(root, 'template_label_qr_eppos_rp4610b_100mm_3kolom.html');
|
||||
|
||||
const browserFiles = [
|
||||
'src/data.js',
|
||||
'src/layout.js',
|
||||
'src/svg.js',
|
||||
'assets/qrcode-core.js',
|
||||
'assets/helvetica-metrics.js'
|
||||
];
|
||||
|
||||
if (!fs.existsSync(template)) {
|
||||
throw new Error('Template HTML tidak ditemukan: ' + template);
|
||||
}
|
||||
|
||||
fs.rmSync(outDir, { recursive: true, force: true });
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.copyFileSync(template, path.join(outDir, 'index.html'));
|
||||
|
||||
browserFiles.forEach(function (relativePath) {
|
||||
const source = path.join(root, relativePath);
|
||||
if (!fs.existsSync(source)) {
|
||||
throw new Error('Aset browser tidak ditemukan: ' + source);
|
||||
}
|
||||
const target = path.join(outDir, relativePath);
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.copyFileSync(source, target);
|
||||
});
|
||||
|
||||
process.stdout.write('dist/ siap dideploy:\n');
|
||||
process.stdout.write(' index.html\n');
|
||||
browserFiles.forEach(function (relativePath) {
|
||||
process.stdout.write(' ' + relativePath + '\n');
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Membuat beberapa PDF contoh untuk validasi:
|
||||
* output/labels-01.pdf - 1 label (1 halaman)
|
||||
* output/labels-10.pdf - 10 label (1 halaman)
|
||||
* output/labels-13.pdf - 13 label (1 halaman)
|
||||
* output/labels-18.pdf - 18 label (1 halaman penuh, 3 x 6)
|
||||
* output/labels-25.pdf - 25 label (2 halaman)
|
||||
*
|
||||
* Jalankan: node scripts/generate-samples.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const LabelData = require('../src/data');
|
||||
const { writePdfFile } = require('../src/pdf');
|
||||
|
||||
function makeItems(count) {
|
||||
const lines = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const unique = '26-' + i.toString(16).toUpperCase().padStart(4, '0');
|
||||
lines.push('ONT-1910' + unique.replace('-', '') + ' | ' + (12345678 + i));
|
||||
}
|
||||
return LabelData.parseText(lines.join('\n'));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const outDir = path.resolve(__dirname, '..', 'output');
|
||||
const targets = [1, 10, 13, 18, 25];
|
||||
|
||||
for (const count of targets) {
|
||||
const items = makeItems(count);
|
||||
const name = 'labels-' + String(count).padStart(2, '0') + '.pdf';
|
||||
const out = path.join(outDir, name);
|
||||
const result = await writePdfFile({ items: items, out: out });
|
||||
process.stdout.write(
|
||||
name + ' ' +
|
||||
result.pageCount + ' halaman, ' + items.length + ' label, ' +
|
||||
'halaman ' + result.layout.page.widthMm + ' x ' + result.layout.page.heightMm + ' mm\n'
|
||||
);
|
||||
}
|
||||
|
||||
// Format 2 baris seperti pada gambar referensi (potongan roll 3 kolom x 2 baris).
|
||||
const stripItems = makeItems(8);
|
||||
const strip = await writePdfFile({
|
||||
items: stripItems,
|
||||
out: path.join(outDir, 'labels-strip-2-baris.pdf'),
|
||||
config: { pageHeightMm: 43.6, rows: 2, labelHeightMm: 0 }
|
||||
});
|
||||
process.stdout.write(
|
||||
'labels-strip-2-baris.pdf ' + strip.pageCount + ' halaman, ' + stripItems.length +
|
||||
' label, halaman ' + strip.layout.page.widthMm + ' x ' + strip.layout.page.heightMm + ' mm\n'
|
||||
);
|
||||
}
|
||||
|
||||
main().catch(function (err) {
|
||||
process.stderr.write('Error: ' + err.message + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Uji jalur cetak browser:
|
||||
* 1. buka file HTML di Edge/Chrome headless lewat DevTools Protocol
|
||||
* 2. cetak memakai Page.printToPDF (scale 1, ukuran kertas 100 x 150 mm)
|
||||
* 3. verifikasi ukuran halaman fisik hasil cetak dan pindai QR-nya
|
||||
*
|
||||
* Pemakaian: node scripts/verify-browser-print.js [path-file-html]
|
||||
*/
|
||||
'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 findBrowser() {
|
||||
for (const candidate of BROWSERS) {
|
||||
if (fs.existsSync(candidate)) { return candidate; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function wait(ms) {
|
||||
return new Promise(function (resolve) { setTimeout(resolve, ms); });
|
||||
}
|
||||
|
||||
class Cdp {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.id = 0;
|
||||
this.pending = new Map();
|
||||
this.listeners = new Map();
|
||||
}
|
||||
|
||||
connect() {
|
||||
const self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
self.ws = new WebSocket(self.url);
|
||||
self.ws.addEventListener('open', function () { resolve(); });
|
||||
self.ws.addEventListener('error', function (err) { reject(err); });
|
||||
self.ws.addEventListener('message', function (event) {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && self.pending.has(message.id)) {
|
||||
const entry = self.pending.get(message.id);
|
||||
self.pending.delete(message.id);
|
||||
if (message.error) { entry.reject(new Error(message.error.message)); }
|
||||
else { entry.resolve(message.result); }
|
||||
return;
|
||||
}
|
||||
const handlers = self.listeners.get(message.method) || [];
|
||||
handlers.forEach(function (handler) { handler(message.params, message.sessionId); });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
send(method, params, sessionId) {
|
||||
const self = this;
|
||||
const id = ++this.id;
|
||||
const payload = { id: id, method: method, params: params || {} };
|
||||
if (sessionId) { payload.sessionId = sessionId; }
|
||||
return new Promise(function (resolve, reject) {
|
||||
self.pending.set(id, { resolve: resolve, reject: reject });
|
||||
self.ws.send(JSON.stringify(payload));
|
||||
});
|
||||
}
|
||||
|
||||
on(method, handler) {
|
||||
if (!this.listeners.has(method)) { this.listeners.set(method, []); }
|
||||
this.listeners.get(method).push(handler);
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.ws) { this.ws.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const browser = findBrowser();
|
||||
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 = 9400 + Math.floor(Math.random() * 400);
|
||||
const userDataDir = path.join(os.tmpdir(), 'label-edge-' + Date.now());
|
||||
const proc = spawn(browser, [
|
||||
'--headless=new',
|
||||
'--disable-gpu',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--user-data-dir=' + userDataDir,
|
||||
'--remote-debugging-port=' + port,
|
||||
'about:blank'
|
||||
], { stdio: 'ignore' });
|
||||
|
||||
let cdp = null;
|
||||
try {
|
||||
let version = null;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
try {
|
||||
const res = await fetch('http://127.0.0.1:' + port + '/json/version');
|
||||
version = await res.json();
|
||||
break;
|
||||
} catch (err) {
|
||||
await wait(250);
|
||||
}
|
||||
}
|
||||
if (!version) { throw new Error('DevTools tidak dapat dihubungi'); }
|
||||
|
||||
cdp = new Cdp(version.webSocketDebuggerUrl);
|
||||
await cdp.connect();
|
||||
|
||||
const target = await cdp.send('Target.createTarget', { url: 'about:blank' });
|
||||
const attached = await cdp.send('Target.attachToTarget', { targetId: target.targetId, flatten: true });
|
||||
const sessionId = attached.sessionId;
|
||||
|
||||
const loaded = new Promise(function (resolve) { cdp.on('Page.loadEventFired', resolve); });
|
||||
await cdp.send('Page.enable', {}, sessionId);
|
||||
await cdp.send('Page.navigate', { url: 'file:///' + htmlFile.replace(/\\/g, '/') }, sessionId);
|
||||
await loaded;
|
||||
await wait(700);
|
||||
|
||||
const dom = await cdp.send('Runtime.evaluate', {
|
||||
expression: 'JSON.stringify({pages:document.querySelectorAll(".page").length,' +
|
||||
'labels:document.querySelectorAll(".label").length,' +
|
||||
'qr:document.querySelectorAll(".qr svg").length,' +
|
||||
'status:(document.getElementById("status")||{}).textContent||""})',
|
||||
returnByValue: true
|
||||
}, sessionId);
|
||||
const summary = JSON.parse(dom.result.value);
|
||||
|
||||
const print = await cdp.send('Page.printToPDF', {
|
||||
printBackground: true,
|
||||
preferCSSPageSize: true,
|
||||
scale: 1,
|
||||
paperWidth: 100 / 25.4,
|
||||
paperHeight: 150 / 25.4,
|
||||
marginTop: 0,
|
||||
marginBottom: 0,
|
||||
marginLeft: 0,
|
||||
marginRight: 0
|
||||
}, sessionId);
|
||||
|
||||
const outFile = path.resolve('output', 'browser-print.pdf');
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
fs.writeFileSync(outFile, Buffer.from(print.data, '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));
|
||||
|
||||
// QR label pertama: kotak QR dihitung dari layout yang sama
|
||||
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);
|
||||
|
||||
process.stdout.write(JSON.stringify({
|
||||
browser: path.basename(browser),
|
||||
dom: summary,
|
||||
pdfFile: outFile,
|
||||
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.message + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Verifikasi PDF hasil generate:
|
||||
* 1. membaca ukuran halaman fisik (MediaBox) memakai pdf-lib
|
||||
* 2. merender tiap halaman menjadi raster memakai mupdf
|
||||
* 3. memindai QR Code tiap label memakai jsQR
|
||||
*
|
||||
* Pemakaian: node scripts/verify-pdf.js output/labels-sample.pdf [dpi]
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { PNG } = require('pngjs');
|
||||
const jsQR = require('jsqr');
|
||||
|
||||
const MM_PER_INCH = 25.4;
|
||||
|
||||
async function main() {
|
||||
const file = process.argv[2];
|
||||
const dpi = Number(process.argv[3] || 300);
|
||||
if (!file) {
|
||||
process.stderr.write('Pakai: node scripts/verify-pdf.js <file.pdf> [dpi]\n');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const mupdf = await import('mupdf');
|
||||
const { PDFDocument } = require('pdf-lib');
|
||||
const LabelLayout = require('../src/layout');
|
||||
|
||||
const bytes = fs.readFileSync(file);
|
||||
const pdf = await PDFDocument.load(bytes);
|
||||
const pageSizes = 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 * MM_PER_INCH).toFixed(3)), Number((size.height / 72 * MM_PER_INCH).toFixed(3))]
|
||||
};
|
||||
});
|
||||
|
||||
const layout = LabelLayout.create();
|
||||
const perPage = layout.perPage;
|
||||
const ppm = dpi / MM_PER_INCH;
|
||||
|
||||
function decodeQrAt(png, boxMm) {
|
||||
const margin = 2;
|
||||
const x = Math.round((boxMm.xMm - margin) * ppm);
|
||||
const y = Math.round((boxMm.yMm - margin) * ppm);
|
||||
const w = Math.round((boxMm.widthMm + margin * 2) * ppm);
|
||||
const h = Math.round((boxMm.heightMm + margin * 2) * ppm);
|
||||
if (x < 0 || y < 0 || x + w > png.width || y + h > png.height) { return null; }
|
||||
const data = 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;
|
||||
data[di] = png.data[si];
|
||||
data[di + 1] = png.data[si + 1];
|
||||
data[di + 2] = png.data[si + 2];
|
||||
data[di + 3] = 255;
|
||||
}
|
||||
}
|
||||
const result = jsQR(data, w, h);
|
||||
return result ? result.data : null;
|
||||
}
|
||||
|
||||
const doc = mupdf.Document.openDocument(bytes, 'application/pdf');
|
||||
const matrix = mupdf.Matrix.scale(dpi / 72, dpi / 72);
|
||||
const pages = [];
|
||||
|
||||
for (let i = 0; i < doc.countPages(); i++) {
|
||||
const page = doc.loadPage(i);
|
||||
const pixmap = page.toPixmap(matrix, 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 structured = page.toStructuredText('preserve-whitespace');
|
||||
const decoded = [];
|
||||
for (let label = i * perPage; label < (i + 1) * perPage; label++) {
|
||||
const boxes = layout.contentBoxes(label);
|
||||
const value = decodeQrAt(png, boxes.qrBox);
|
||||
if (value) { decoded.push(value); }
|
||||
}
|
||||
pages.push({
|
||||
page: i + 1,
|
||||
raster: png.width + 'x' + png.height + ' px @' + dpi + ' dpi',
|
||||
qrTerbaca: decoded.length,
|
||||
contohPayload: decoded[0] || null,
|
||||
teks: String(structured.asText()).split('\n').filter(function (line) { return line.trim(); }).slice(0, 3)
|
||||
});
|
||||
pixmap.destroy();
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify({
|
||||
file: path.basename(file),
|
||||
jumlahHalaman: pdf.getPageCount(),
|
||||
pageSizes: pageSizes,
|
||||
pages: pages
|
||||
}, null, 2) + '\n');
|
||||
}
|
||||
|
||||
main().catch(function (err) {
|
||||
process.stderr.write('Error: ' + err.stack + '\n');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in New Issue
Block a user