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

+13
View File
@@ -4,6 +4,19 @@ All notable changes to this project will be documented in this file. See [standa
## Version 2026.10.12-it-tools-pro
### 📐 面单设计:导入 PDF 后条码 / 二维码 / 图片全部可修改
- 上传 PDF 现在会把 **条码、二维码、图片** 一并识别成可编辑元素,配合已有的文字层,**页面内容全都能改**(改内容、移动、缩放、删除)
- **条码 / 二维码**:用 `zxing-wasm`(WASM 本地加载,离线可用)在原图上解码,识别位置 + 读出内容 → 生成条码/二维码元素
- 内容**可直接改**(改完即重新渲染),格式自动映射到 bwipjs(Code128/Code39/EAN/UPC/QR 等)
- 原图上的条码同步擦除,**不会出现两份叠加**
- **图片**(logo、图标等):走 pdf.js 操作符列表取图 → 生成图片元素,原位擦除后放回同一张图,无重影
- 过滤规则:跳过覆盖整页的扫描底图、过小图片,以及与已识别条码重叠的图(避免重复元素)
- **文字**:跳过条码/图片所在区域,三类互不重叠
- 验证(两份实测 PDF):
- 条码 PDF → 提取 **2 个条码/二维码**(`JD008317895047`、`https://it.88531.cn`),坐标 X=17.6 / Y=49.6 与设计值一致,**未产生重复图片元素**
- 图片 PDF → 提取 **1 张图片 + 1 段文字**,图片坐标 21.2 / 35.3 / 35.3 / 35.3mm 与期望分毫不差
- 改条码内容为 `HELLO-2026` → 条码图即时重渲染 ✓;视觉复核**单份无重影、条码清晰** ✓
### 🩹 修复:导入 PDF 文字重影
- **根因**:文字层提取后,底图仍保留原字 → 原字 + 叠加字两层同位,出现"阴影/叠字"
- **修复**:提取时同步**把底图上对应文字擦白**(在 `toDataURL` 之前处理),底图只留版式、条码、logo 等非文字元素
+1 -1
View File
@@ -39,7 +39,7 @@ const groups: { title: string; items: Item[] }[] = [
{ name: '二维码条码识别', icon: '扫', desc: '上传/拖拽/粘贴图片一键识别,支持多码混合批量输出,本地 WASM 解码,图片不上传', tag: '全新' },
{ name: '在线翻译', icon: '译', desc: '中英日韩等 16 种语言互译,自动识别源语言,支持导入 Word/PDF/TXT 等文档整篇翻译、并发处理大文档、译文可下载 TXT/DOCX', tag: '全新' },
{ name: '图片OCR / PDF文字识别', icon: '识', desc: '本地 OCR 引擎,截图扫描件文字提取(准确率 99%+);PDF 逐页识别、预览、导出 TXT', tag: '全新' },
{ name: '面单设计', icon: '单', desc: '快递面单模板开箱即用;上传 PDF 自动把**文字层提取成可编辑元素**并**擦除底图原字**(可直接改字、不产生重影);新增**实线/虚线 × 横线/竖线**线条组件可调粗度长度;300dpi 高清导出', tag: '全新' },
{ name: '面单设计', icon: '单', desc: '快递面单模板开箱即用;上传 PDF 自动把**文字、条码、二维码、图片**全部提取成可编辑元素(可改内容、移动、删除)并**擦除底图原内容**,不产生重影;新增**实线/虚线 × 横线/竖线**线条组件可调粗度长度;300dpi 高清导出', tag: '全新' },
{ name: 'IT网站收藏', icon: '藏', desc: '内置 91 个精选开发站点(社区/文档/工具/AI/设计/视频/媒体平台),数据存用户本地,可自选目录', tag: '全新' },
{ name: '文档格式转换', icon: '转', desc: 'Word/PDF/TXT/RTF/ODT/EPUB/MOBI/AZW3/HTML 九格式互转,自建 calibre 引擎,批量打包下载', tag: '全新' },
{ name: '视频工具', icon: '视', desc: '格式转换、压缩、裁剪、旋转、变速、消音、提取音频、截图、GIF 互转、加水印/去水印等 13 个工具 + AI 字幕生成,服务端 ffmpeg 高速处理,最大 2GB', tag: '全新' },
+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 页作为底图`;