feat(label-designer): 导入PDF提取条码/二维码/图片为可编辑元素

- zxing-wasm 解码条码二维码(位置+内容), 原图擦除无重影
- pdf.js 操作符列表提取嵌入图片为图片元素(兼容 pdf.js 的 bitmap 字段)
- 文字层跳过条码/图片区域, 三类互不重叠
- CHANGELOG + About 更新
This commit is contained in:
personal82555 committed 2026-10-14 16:22:26 +08:00
1 parent ea6acf3f5f
commit aacdd0e560
3 files changed
+224 -8

No files matched your search

+210 -7
View File
@@ -6,9 +6,32 @@ import { useGenHistory } from '@/tools/gen-history/gen-history';
const genHist = useGenHistory('label-designer');
import bwipjs from 'bwip-js';
import { PDFDocument } from 'pdf-lib';
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
import { getDocument, GlobalWorkerOptions, OPS } from 'pdfjs-dist';
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
import { defaultDoc, newId, templates } from './templates';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import wasmUrl from 'zxing-wasm/reader/zxing_reader.wasm?url';
// wasm 从本地 bundle 加载(离线 / 国内可用)
prepareZXingModule({ overrides: { locateFile: () => wasmUrl }, fireImmediately: true });
// zxing 格式名 -> bwipjs bcid(本工具的条码渲染器)
function mapCodeFormat(fmt: string): string {
const f = (fmt || '').toLowerCase();
if (f.includes('qrcode') || f.includes('microqr') || f.includes('rmqr')) return 'qrcode';
if (f.includes('code128')) return 'code128';
if (f.includes('code39')) return 'code39';
if (f.includes('code93')) return 'code93';
if (f.includes('ean13')) return 'ean13';
if (f.includes('ean8')) return 'ean8';
if (f.includes('upc-a') || f === 'upca') return 'upca';
if (f.includes('upc-e') || f === 'upce') return 'upce';
if (f.includes('itf')) return 'itf';
if (f.includes('codabar')) return 'codabar';
if (f.includes('datamatrix')) return 'datamatrix';
if (f.includes('pdf417')) return 'pdf417';
return 'code128';
}
import type { LabelDoc, LabelElement } from './templates';
GlobalWorkerOptions.workerSrc = pdfWorkerUrl;
@@ -346,8 +369,169 @@ async function onPdfFile(e: Event) {
ctx.fillRect(0, 0, canvas.width, canvas.height);
await page.render({ canvasContext: ctx, viewport }).promise;
// 提取文字层:把 PDF 里的文字转成可编辑文本元素(按基线分行合并),
// 同时把底图上对应的文字擦掉,避免"原字 + 叠加字"形成重影
// 1) 条码 / 二维码:在原图上识别并解码 → 变成可编辑条码元素,同时擦除底图原图
const codeEls: LabelElement[] = [];
const codeBoxes: { x: number; y: number; w: number; h: number }[] = [];
try {
const px2mm = 25.4 / EXPORT_DPI;
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const syms = await readBarcodes(imgData, {
tryHarder: true,
tryRotate: true,
tryInvert: true,
maxNumberOfSymbols: 0,
});
for (const sym of syms as any[]) {
const p = sym?.position;
if (!p || !sym?.text) {
continue;
}
const xs = [p.topLeft.x, p.topRight.x, p.bottomLeft.x, p.bottomRight.x];
const ys = [p.topLeft.y, p.topRight.y, p.bottomLeft.y, p.bottomRight.y];
const x0 = Math.min(...xs);
const y0 = Math.min(...ys);
const x1 = Math.max(...xs);
const y1 = Math.max(...ys);
const wPx = x1 - x0;
const hPx = y1 - y0;
if (wPx < 4 || hPx < 4) {
continue;
}
// 擦除底图上的原条码(避免与新条码重影)
ctx.fillStyle = '#ffffff';
ctx.fillRect(Math.floor(x0), Math.floor(y0), Math.ceil(wPx), Math.ceil(hPx));
const isQR = /qr|aztec|datamatrix|pdf417/i.test(String(sym.format || ''));
const el = {
id: newId(),
type: isQR ? ('qr' as const) : ('barcode' as const),
x: Math.round(x0 * px2mm * 10) / 10,
y: Math.round(y0 * px2mm * 10) / 10,
w: Math.max(8, Math.round(wPx * px2mm * 10) / 10),
h: Math.max(8, Math.round(hPx * px2mm * 10) / 10),
text: String(sym.text),
...(isQR ? {} : { format: mapCodeFormat(String(sym.format || '')), showValue: true }),
} as LabelElement;
codeEls.push(el);
codeBoxes.push({ x: el.x, y: el.y, w: el.w, h: el.h });
}
}
catch { /* 无条码或识别失败:跳过 */ }
// 2) 嵌入图片(logo / 图标等):从 PDF 操作符列表取图 → 变成可编辑图片元素,同时擦除底图
try {
const PTa = 25.4 / 72;
const Hpt = v1.height; // 页面高度(pt,scale=1)
const mul = (a: number[], b: number[]) => [
a[0] * b[0] + a[2] * b[1],
a[1] * b[0] + a[3] * b[1],
a[0] * b[2] + a[2] * b[3],
a[1] * b[2] + a[3] * b[3],
a[0] * b[4] + a[2] * b[5] + a[4],
a[1] * b[4] + a[3] * b[5] + a[5],
];
const toDataUrl = (o: any): string | null => {
try {
const c = document.createElement('canvas');
// 新版 pdf.js 把解码结果放在 bitmap(ImageBitmap),data 为 null
const src = o?.bitmap || o;
if (typeof ImageBitmap !== 'undefined' && src instanceof ImageBitmap) {
c.width = src.width;
c.height = src.height;
c.getContext('2d')!.drawImage(src, 0, 0);
return c.toDataURL('image/png');
}
c.width = o.width;
c.height = o.height;
const cc = c.getContext('2d')!;
if (o.data && o.data.length === o.width * o.height * 4) {
cc.putImageData(new ImageData(o.data, o.width, o.height), 0, 0);
}
else if (o instanceof HTMLImageElement || o instanceof HTMLCanvasElement) {
cc.drawImage(o as any, 0, 0);
}
else {
return null;
}
return c.toDataURL('image/png');
}
catch {
return null;
}
};
const opList = await page.getOperatorList();
let ctm: number[] = [1, 0, 0, 1, 0, 0];
const stack: number[][] = [];
const pageArea = v1.width * v1.height;
for (let i = 0; i < opList.fnArray.length; i++) {
const fn = opList.fnArray[i];
const args = opList.argsArray[i] as any;
if (fn === OPS.save) {
stack.push(ctm.slice());
}
else if (fn === OPS.restore) {
ctm = stack.pop() || [1, 0, 0, 1, 0, 0];
}
else if (fn === OPS.transform) {
ctm = mul(ctm, args as number[]);
}
else if (fn === OPS.paintImageXObject || fn === OPS.paintImageMaskXObject || fn === OPS.paintInlineImageXObject) {
let obj: any = null;
if (fn === OPS.paintInlineImageXObject) {
obj = args[0];
}
else {
try {
obj = (page as any).objs.get(args[0]);
}
catch {
obj = null;
}
}
if (!obj || !obj.width || !obj.height) {
continue;
}
// 放置矩形:CTM 把单位正方形映射到目标位置
const elXpt = ctm[4];
const elWpt = Math.hypot(ctm[0], ctm[1]) || 0;
const elHpt = Math.hypot(ctm[2], ctm[3]) || 0;
const elYptTop = Hpt - (ctm[5] + elHpt);
// 过滤:覆盖整页的(扫描件底图)、过小的、与条码重叠的
if (elWpt * elHpt > pageArea * 0.6 || elWpt < 12 || elHpt < 12) {
continue;
}
const elX = elXpt * PTa;
const elY = elYptTop * PTa;
const elW = elWpt * PTa;
const elH = elHpt * PTa;
if (codeBoxes.some(b => elX < b.x + b.w && elX + elW > b.x && elY < b.y + b.h && elY + elH > b.y)) {
continue;
}
const url = toDataUrl(obj);
if (!url) {
continue;
}
// 图片框内就是图片本身(可能是彩色 logo),不适用"近白"判断;
// 擦除后会在同一位置放回同一张图,因此必然无重影
const kk = EXPORT_DPI / 25.4;
ctx.fillStyle = '#ffffff';
ctx.fillRect(Math.round(elX * kk), Math.round(elY * kk), Math.round(elW * kk), Math.round(elH * kk));
codeEls.push({
id: newId(),
type: 'image',
x: Math.round(elX * 10) / 10,
y: Math.round(elY * 10) / 10,
w: Math.round(elW * 10) / 10,
h: Math.round(elH * 10) / 10,
src: url,
});
codeBoxes.push({ x: elX, y: elY, w: elW, h: elH });
}
}
}
catch { /* 无嵌入图片或提取失败:跳过 */ }
// 3) 文字层提取(避开条码 / 图片区,避免重复/互相遮挡)
function boxBackground(xMm: number, yMm: number, wMm: number, hMm: number) {
const k = EXPORT_DPI / 25.4;
let x = Math.max(0, Math.round(xMm * k));
@@ -428,6 +612,12 @@ async function onPdfFile(e: Event) {
const elH = Math.max(3, fs * 1.4 * PT);
const elY = (g.y - fs * 0.9) * PT;
const elX = Math.max(0, x0 * PT);
// 已被条码占位的行跳过(条码区已擦除,不再重复成元素)
const overlapCode = codeBoxes.some(b =>
elX < b.x + b.w + 1 && elX + txtW > b.x - 1 && elY < b.y + b.h + 1 && elY + elH > b.y - 1);
if (overlapCode) {
continue;
}
// 只在「近白、低饱和」背景处擦除底图原字——彩色/深色区域保留原字且不叠加,避免白块与重影
const bg = boxBackground(elX, elY, txtW, elH);
if (bg.lum >= 205 && bg.spread <= 40) {
@@ -459,16 +649,29 @@ async function onPdfFile(e: Event) {
const src = canvas.toDataURL('image/png'); // 擦除原字后再生成底图
const allEls: LabelElement[] = [...codeEls, ...textEls];
doc.value = {
widthMM: wMM,
heightMM: hMM,
bg: { src, name: file.name, pages: pdf.numPages },
elements: textEls,
elements: allEls,
};
selectedId.value = textEls[0]?.id ?? null;
selectedId.value = allEls[0]?.id ?? null;
zoom.value = 1;
if (textEls.length) {
error.value = `已导入底图,并从 PDF 提取 ${textEls.length} 段文字为可编辑元素(可直接改字、移动)`;
const codeCnt = codeEls.filter(e => e.type === 'barcode' || e.type === 'qr').length;
const imgCnt = codeEls.filter(e => e.type === 'image').length;
if (allEls.length) {
const parts: string[] = [];
if (codeCnt) {
parts.push(`${codeCnt} 个条码/二维码`);
}
if (imgCnt) {
parts.push(`${imgCnt} 张图片`);
}
if (textEls.length) {
parts.push(`${textEls.length} 段文字`);
}
error.value = `已导入底图,并提取 ${parts.join(' + ')} 为可编辑元素(可改内容、移动、删除)`;
}
else if (pdf.numPages > 1) {
error.value = `提示:该 PDF 共 ${pdf.numPages} 页,已导入第 1 页作为底图`;