// ==UserScript==
// @name 学籍档案批量下载(ScriptCat)
// @namespace https://scriptcat.org/
// @version 1.0.0
// @description 按名单批量下载学籍档案证明,支持悬浮面板、并发、印章/签字和文件夹保存
// @author 文轩创造
// @match https://zxxs.moe.edu.cn/*
// @run-at document-idle
// @grant none
// @license MIT
// ==/UserScript==
(() => {
"use strict";
if (window.top !== window) return;
if (window.__XJDA_SC_LOADED__) return;
window.__XJDA_SC_LOADED__ = true;
const LIST_URL = "https://zxxs.moe.edu.cn/www/xsxj/xjda/xjda";
const A4_W = 210;
const A4_H = 297;
const NAMES_KEY = "xjdaScNames";
const WAIT_KEY = "xjdaScWait";
const CONC_KEY = "xjdaScConcurrency";
const OVERLAY_KEY = "xjdaScOverlay";
const AUTH_KEY = "xjdaScAuthorized";
const state = {
running: false,
stopRequested: false,
waitMs: 2000,
concurrency: 2,
total: 0,
done: 0,
frames: new Set(),
searchChain: Promise.resolve(),
dirHandle: null,
overlay: {
seal: defaultOverlay("seal"),
signature: defaultOverlay("signature"),
},
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function defaultOverlay(kind) {
return {
enabled: false,
dataUrl: "",
x: kind === "seal" ? 73 : 57,
y: kind === "seal" ? 85 : 88,
wMm: kind === "seal" ? 40 : 45,
hMm: kind === "seal" ? 40 : 15,
rotate: kind === "seal" ? -10 : 0,
opacity: 100,
circle: kind === "seal",
square: kind === "seal",
removeWhite: true,
cropTop: 0,
cropRight: 0,
cropBottom: 0,
cropLeft: 0,
srcW: 0,
srcH: 0,
};
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, Number(value)));
}
function normalizeOverlay(kind, raw) {
const base = { ...defaultOverlay(kind), ...(raw || {}) };
base.wMm = clamp(base.wMm || 40, 5, 150);
base.hMm = clamp(base.hMm || 40, 5, 150);
base.x = clamp(base.x, 0, 100);
base.y = clamp(base.y, 0, 100);
base.rotate = clamp(base.rotate, -180, 180);
base.opacity = clamp(base.opacity, 5, 100);
base.cropTop = clamp(base.cropTop, 0, 60);
base.cropRight = clamp(base.cropRight, 0, 60);
base.cropBottom = clamp(base.cropBottom, 0, 60);
base.cropLeft = clamp(base.cropLeft, 0, 60);
base.circle = Boolean(base.circle);
base.square = Boolean(base.square || base.circle);
if (base.circle) base.hMm = base.wMm;
base.removeWhite = base.removeWhite !== false;
base.enabled = Boolean(base.enabled && base.dataUrl);
base.dataUrl = String(base.dataUrl || "");
delete base.previewUrl;
return base;
}
function loadOverlay() {
try {
const raw = JSON.parse(localStorage.getItem(OVERLAY_KEY) || "{}");
state.overlay.seal = normalizeOverlay("seal", raw.seal);
state.overlay.signature = normalizeOverlay("signature", raw.signature);
} catch {
/* 使用默认值 */
}
}
function saveOverlay() {
try {
const clean = (config) => {
const { previewUrl, ...rest } = config;
return rest;
};
localStorage.setItem(
OVERLAY_KEY,
JSON.stringify({
seal: clean(state.overlay.seal),
signature: clean(state.overlay.signature),
})
);
return true;
} catch (error) {
addLog("保存印章/签字失败:" + (error.message || error), "err");
return false;
}
}
// ---------------------------------------------------------------------
// UI
// ---------------------------------------------------------------------
const host = document.createElement("div");
host.id = "xjda-sc-host";
document.documentElement.appendChild(host);
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = `
保存文件夹
未选择,将保存到浏览器默认下载目录
批量过程中不要关闭本页;首次使用建议先下载 1 人检查。
印章 / 签字
上传 → 裁剪 → 设置毫米尺寸 → 拖动位置
学籍档案证明
通用 A4 版式示意 · 实际以系统页面为准
盖章 / 签字区域
裁剪图片
拖动四条边包住印章/签字,完成后设置长宽。
`;
const $ = (id) => shadow.getElementById(id);
const ui = {
launcher: $("launcher"),
panel: $("panel"),
closePanel: $("closePanel"),
names: $("names"),
count: $("count"),
wait: $("wait"),
conc: $("conc"),
dirStatus: $("dirStatus"),
pickDir: $("pickDir"),
start: $("start"),
stop: $("stop"),
editorBtn: $("editorBtn"),
hint: $("hint"),
bar: $("bar"),
log: $("log"),
editorModal: $("editorModal"),
closeEditor: $("closeEditor"),
editPaper: $("editPaper"),
editSealWrap: $("editSealWrap"),
editSigWrap: $("editSigWrap"),
editSealImg: $("editSealImg"),
editSigImg: $("editSigImg"),
tabSeal: $("tabSeal"),
tabSig: $("tabSig"),
edUpload: $("edUpload"),
edClear: $("edClear"),
edWhiteNow: $("edWhiteNow"),
edFile: $("edFile"),
edRemoveWhite: $("edRemoveWhite"),
edEnabled: $("edEnabled"),
edW: $("edW"),
edH: $("edH"),
edSquare: $("edSquare"),
edCircle: $("edCircle"),
edRotate: $("edRotate"),
edRotateOut: $("edRotateOut"),
edOpacity: $("edOpacity"),
edOpacityOut: $("edOpacityOut"),
edX: $("edX"),
edXOut: $("edXOut"),
edY: $("edY"),
edYOut: $("edYOut"),
edCrop: $("edCrop"),
edSave: $("edSave"),
edAuth: $("edAuth"),
edStatus: $("edStatus"),
cropModal: $("cropModal"),
cropCanvas: $("cropCanvas"),
cropImg: $("cropImg"),
cropBox: $("cropBox"),
cropAuto: $("cropAuto"),
cropCancel: $("cropCancel"),
cropApply: $("cropApply"),
cropClose: $("cropClose"),
};
function addLog(text, kind = "") {
const line = document.createElement("div");
line.className = kind;
line.textContent = text;
ui.log.appendChild(line);
ui.log.scrollTop = ui.log.scrollHeight;
}
function setHint(text) {
ui.hint.textContent = text;
}
function setProgress(done, total) {
ui.bar.style.width = total ? Math.round((done / total) * 100) + "%" : "0";
}
function updateCount() {
const lines = parseNames(ui.names.value);
ui.count.textContent = lines.length + " 人";
}
function openPanel(open) {
ui.panel.hidden = !open;
}
ui.launcher.addEventListener("click", () => {
openPanel(ui.panel.hidden);
});
ui.closePanel.addEventListener("click", () => openPanel(false));
// ---------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------
function loadSettings() {
try {
const names = localStorage.getItem(NAMES_KEY) || "";
if (names) ui.names.value = names;
const rawWait = localStorage.getItem(WAIT_KEY);
if (rawWait !== null) {
const wait = Number(rawWait);
if (Number.isFinite(wait)) ui.wait.value = String(clamp(wait, 0, 15));
}
const rawConc = localStorage.getItem(CONC_KEY);
if (rawConc !== null) {
const conc = Number(rawConc);
if (Number.isFinite(conc)) ui.conc.value = String(clamp(conc, 1, 5));
}
ui.edAuth.checked = localStorage.getItem(AUTH_KEY) === "1";
} catch {
/* 忽略 */
}
updateCount();
}
function saveSettings() {
localStorage.setItem(NAMES_KEY, ui.names.value);
localStorage.setItem(WAIT_KEY, ui.wait.value);
localStorage.setItem(CONC_KEY, ui.conc.value);
}
function parseNames(text) {
const records = [];
for (const raw of String(text || "").split(/\r?\n/)) {
const line = raw.trim();
if (!line) continue;
const parts = line.split(/[\t,,]/).map((part) => part.trim());
if (!parts[0] || /^(姓名|学生姓名)$/.test(parts[0])) continue;
records.push({
name: parts[0],
className: parts[1] || "",
xjh: parts[2] || "",
});
}
return records;
}
// ---------------------------------------------------------------------
// Folder saving (File System Access API, fallback to default download)
// ---------------------------------------------------------------------
const DB_NAME = "xjda-scriptcat";
const DB_STORE = "handles";
function openDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => {
request.result.createObjectStore(DB_STORE);
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async function idbGet(key) {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(DB_STORE, "readonly");
const request = tx.objectStore(DB_STORE).get(key);
request.onsuccess = () => resolve(request.result || null);
request.onerror = () => reject(request.error);
});
}
async function idbSet(key, value) {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(DB_STORE, "readwrite");
tx.objectStore(DB_STORE).put(value, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function updateDirStatus() {
if (!state.dirHandle) {
ui.dirStatus.textContent = "未选择,将保存到浏览器默认下载目录";
return;
}
try {
const permission = await state.dirHandle.queryPermission({ mode: "readwrite" });
ui.dirStatus.textContent =
"当前:" +
state.dirHandle.name +
(permission === "granted" ? "(已授权)" : "(需在开始下载时授权)");
} catch {
ui.dirStatus.textContent = "当前:" + state.dirHandle.name;
}
}
async function restoreDirHandle() {
try {
state.dirHandle = await idbGet("saveDir");
if (state.dirHandle) await updateDirStatus();
} catch {
state.dirHandle = null;
}
}
ui.pickDir.addEventListener("click", async () => {
if (!window.showDirectoryPicker) {
ui.dirStatus.textContent = "此浏览器不支持文件夹选择,将使用默认下载目录";
return;
}
try {
const handle = await window.showDirectoryPicker({ mode: "readwrite" });
state.dirHandle = handle;
await idbSet("saveDir", handle);
await updateDirStatus();
addLog("已选择保存文件夹:" + handle.name);
} catch (error) {
if (error && error.name !== "AbortError") {
ui.dirStatus.textContent = "选择文件夹失败:" + error.message;
}
}
});
async function ensureDirPermission() {
if (!state.dirHandle) return false;
try {
let permission = await state.dirHandle.queryPermission({ mode: "readwrite" });
if (permission === "granted") return true;
permission = await state.dirHandle.requestPermission({ mode: "readwrite" });
return permission === "granted";
} catch {
return false;
}
}
function safeFilename(name) {
const base = String(name || "学籍档案证明.pdf")
.replace(/[\\/:*?"<>|]/g, "_")
.replace(/^\.+/, "");
return /\.pdf$/i.test(base) ? base : base + ".pdf";
}
async function saveBlob(blob, filename) {
const safe = safeFilename(filename);
if (state.dirHandle) {
const allowed = await ensureDirPermission();
if (allowed) {
const fileHandle = await state.dirHandle.getFileHandle(safe, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
return { kind: "folder", filename: safe };
}
}
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = safe;
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
return { kind: "download", filename: safe };
}
// ---------------------------------------------------------------------
// Image processing / overlay editor
// ---------------------------------------------------------------------
function loadImage(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => reject(new Error("图片加载失败"));
image.src = src;
});
}
function readFileAsDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error("读取图片失败"));
reader.readAsDataURL(file);
});
}
async function shrinkImage(file) {
const dataUrl = await readFileAsDataUrl(file);
const image = await loadImage(dataUrl);
const max = 1400;
const scale = Math.min(1, max / Math.max(image.width, image.height));
if (scale >= 1 && /image\/png/i.test(file.type)) return dataUrl;
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale));
canvas.height = Math.max(1, Math.round(image.height * scale));
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/png");
}
function clearWhitePixels(context, width, height, threshold = 242) {
const pixels = context.getImageData(0, 0, width, height);
const data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
if (
data[i + 3] > 0 &&
data[i] >= threshold &&
data[i + 1] >= threshold &&
data[i + 2] >= threshold
) {
data[i + 3] = 0;
}
}
context.putImageData(pixels, 0, 0);
}
function contentBounds(context, width, height) {
const data = context.getImageData(0, 0, width, height).data;
let left = width;
let right = -1;
let top = height;
let bottom = -1;
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
if (data[(y * width + x) * 4 + 3] <= 8) continue;
if (x < left) left = x;
if (x > right) right = x;
if (y < top) top = y;
if (y > bottom) bottom = y;
}
}
return right < left ? null : { left, right, top, bottom };
}
async function buildOverlay(config) {
if (!config || !config.dataUrl) return "";
const image = await loadImage(config.dataUrl);
const naturalWidth = image.naturalWidth || image.width;
const naturalHeight = image.naturalHeight || image.height;
const left = Math.min(config.cropLeft, 60);
const right = Math.min(config.cropRight, 60);
const top = Math.min(config.cropTop, 60);
const bottom = Math.min(config.cropBottom, 60);
const sourceWidth = naturalWidth * (1 - (left + right) / 100);
const sourceHeight = naturalHeight * (1 - (top + bottom) / 100);
if (sourceWidth < 2 || sourceHeight < 2) throw new Error("裁剪范围过大");
const cropped = document.createElement("canvas");
cropped.width = Math.max(1, Math.round(sourceWidth));
cropped.height = Math.max(1, Math.round(sourceHeight));
const cropContext = cropped.getContext("2d");
cropContext.drawImage(
image,
naturalWidth * (left / 100),
naturalHeight * (top / 100),
sourceWidth,
sourceHeight,
0,
0,
cropped.width,
cropped.height
);
if (config.removeWhite !== false) {
clearWhitePixels(cropContext, cropped.width, cropped.height);
}
const bounds = contentBounds(cropContext, cropped.width, cropped.height);
if (!bounds) return "";
const contentWidth = bounds.right - bounds.left + 1;
const contentHeight = bounds.bottom - bounds.top + 1;
const targetAspect = config.wMm / config.hMm || 1;
let canvasWidth = contentWidth;
let canvasHeight = Math.round(canvasWidth / targetAspect);
if (canvasHeight < contentHeight) {
canvasHeight = contentHeight;
canvasWidth = Math.round(canvasHeight * targetAspect);
}
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, canvasWidth);
canvas.height = Math.max(1, canvasHeight);
const context = canvas.getContext("2d");
if (config.circle) {
context.save();
context.beginPath();
context.ellipse(
canvas.width / 2,
canvas.height / 2,
canvas.width / 2,
canvas.height / 2,
0,
0,
Math.PI * 2
);
context.clip();
}
const scale = Math.min(canvas.width / contentWidth, canvas.height / contentHeight);
const drawWidth = contentWidth * scale;
const drawHeight = contentHeight * scale;
context.drawImage(
cropped,
bounds.left,
bounds.top,
contentWidth,
contentHeight,
(canvas.width - drawWidth) / 2,
(canvas.height - drawHeight) / 2,
drawWidth,
drawHeight
);
if (config.circle) context.restore();
return canvas.toDataURL("image/png");
}
let editorKind = "seal";
let cropState = null;
let previewToken = 0;
function currentEditConfig() {
return state.overlay[editorKind];
}
function setEdStatus(text) {
ui.edStatus.textContent = text || "";
}
function syncEditorControls() {
const config = currentEditConfig();
ui.edRemoveWhite.checked = config.removeWhite !== false;
ui.edEnabled.checked = config.enabled;
ui.edW.value = String(config.wMm);
ui.edH.value = String(config.hMm);
ui.edSquare.checked = config.square;
ui.edCircle.checked = config.circle;
ui.edSquare.disabled = config.circle;
ui.edH.disabled = config.square || config.circle;
ui.edRotate.value = String(config.rotate);
ui.edOpacity.value = String(config.opacity);
ui.edX.value = String(config.x);
ui.edY.value = String(config.y);
ui.edRotateOut.textContent = String(config.rotate);
ui.edOpacityOut.textContent = String(config.opacity);
ui.edXOut.textContent = String(config.x);
ui.edYOut.textContent = String(config.y);
ui.tabSeal.classList.toggle("active", editorKind === "seal");
ui.tabSig.classList.toggle("active", editorKind === "signature");
ui.edAuth.checked = localStorage.getItem(AUTH_KEY) === "1";
}
function applyEditorPreview(kind) {
const config = state.overlay[kind];
const wrap = kind === "seal" ? ui.editSealWrap : ui.editSigWrap;
const image = kind === "seal" ? ui.editSealImg : ui.editSigImg;
if (!config.dataUrl) {
wrap.hidden = true;
return;
}
wrap.hidden = false;
wrap.style.left = config.x + "%";
wrap.style.top = config.y + "%";
wrap.style.width = (config.wMm / A4_W) * 100 + "%";
wrap.style.height = (config.hMm / A4_H) * 100 + "%";
wrap.style.transform = "translate(-50%,-50%) rotate(" + config.rotate + "deg)";
wrap.style.opacity = String(config.opacity / 100);
if (config.previewUrl) {
if (image.getAttribute("data-src") !== config.previewUrl) {
image.src = config.previewUrl;
image.setAttribute("data-src", config.previewUrl);
}
}
}
async function refreshEditorPreview(kind) {
const config = state.overlay[kind];
if (!config.dataUrl) {
config.previewUrl = "";
applyEditorPreview(kind);
return;
}
const token = ++previewToken;
try {
const url = await buildOverlay(config);
if (token !== previewToken) return;
config.previewUrl = url;
applyEditorPreview(kind);
} catch (error) {
setEdStatus(error.message || String(error));
}
}
function renderEditor() {
syncEditorControls();
applyEditorPreview("seal");
applyEditorPreview("signature");
refreshEditorPreview(editorKind);
}
function openEditor() {
loadOverlay();
editorKind = "seal";
ui.editorModal.hidden = false;
renderEditor();
}
function closeEditor() {
ui.editorModal.hidden = true;
}
ui.editorBtn.addEventListener("click", openEditor);
ui.closeEditor.addEventListener("click", closeEditor);
ui.editorModal.addEventListener("click", (event) => {
if (event.target === ui.editorModal) closeEditor();
});
ui.tabSeal.addEventListener("click", () => {
editorKind = "seal";
renderEditor();
});
ui.tabSig.addEventListener("click", () => {
editorKind = "signature";
renderEditor();
});
ui.edUpload.addEventListener("click", () => ui.edFile.click());
ui.edFile.addEventListener("change", async () => {
const file = ui.edFile.files && ui.edFile.files[0];
ui.edFile.value = "";
if (!file) return;
setEdStatus("正在处理图片…");
try {
let dataUrl = await shrinkImage(file);
if (ui.edRemoveWhite.checked) {
const image = await loadImage(dataUrl);
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth || image.width;
canvas.height = image.naturalHeight || image.height;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
clearWhitePixels(context, canvas.width, canvas.height);
dataUrl = canvas.toDataURL("image/png");
}
const config = currentEditConfig();
config.dataUrl = dataUrl;
config.previewUrl = "";
config.enabled = true;
config.removeWhite = ui.edRemoveWhite.checked;
config.cropTop = 0;
config.cropRight = 0;
config.cropBottom = 0;
config.cropLeft = 0;
config.srcW = 0;
config.srcH = 0;
syncEditorControls();
applyEditorPreview(editorKind);
await openCrop(true);
setEdStatus("先拖动四边裁剪,完成后设置长宽。");
} catch (error) {
setEdStatus(error.message || String(error));
}
});
ui.edClear.addEventListener("click", () => {
const config = currentEditConfig();
config.dataUrl = "";
config.previewUrl = "";
config.enabled = false;
syncEditorControls();
applyEditorPreview(editorKind);
setEdStatus("已清除当前图片。");
});
ui.edWhiteNow.addEventListener("click", async () => {
const config = currentEditConfig();
if (!config.dataUrl) {
setEdStatus("请先上传图片。");
return;
}
setEdStatus("正在去除白底…");
try {
const image = await loadImage(config.dataUrl);
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth || image.width;
canvas.height = image.naturalHeight || image.height;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
clearWhitePixels(context, canvas.width, canvas.height);
config.dataUrl = canvas.toDataURL("image/png");
config.removeWhite = true;
ui.edRemoveWhite.checked = true;
await refreshEditorPreview(editorKind);
setEdStatus("白底已去除。");
} catch (error) {
setEdStatus(error.message || String(error));
}
});
ui.edRemoveWhite.addEventListener("change", () => {
currentEditConfig().removeWhite = ui.edRemoveWhite.checked;
});
ui.edEnabled.addEventListener("change", () => {
const config = currentEditConfig();
if (ui.edEnabled.checked && !config.dataUrl) {
ui.edEnabled.checked = false;
setEdStatus("请先上传图片。");
return;
}
config.enabled = ui.edEnabled.checked;
saveOverlay();
});
ui.edSquare.addEventListener("change", () => {
const config = currentEditConfig();
config.square = ui.edSquare.checked;
if (config.square) {
config.hMm = config.wMm;
ui.edH.value = String(config.hMm);
}
syncEditorControls();
applyEditorPreview(editorKind);
refreshEditorPreview(editorKind);
});
ui.edCircle.addEventListener("change", () => {
const config = currentEditConfig();
config.circle = ui.edCircle.checked;
if (config.circle) {
config.square = true;
config.hMm = config.wMm;
}
syncEditorControls();
applyEditorPreview(editorKind);
refreshEditorPreview(editorKind);
});
ui.edW.addEventListener("input", () => {
const config = currentEditConfig();
config.wMm = clamp(ui.edW.value, 5, 150);
if (config.square || config.circle) {
config.hMm = config.wMm;
ui.edH.value = String(config.hMm);
}
applyEditorPreview(editorKind);
});
ui.edW.addEventListener("change", () => refreshEditorPreview(editorKind));
ui.edH.addEventListener("input", () => {
const config = currentEditConfig();
if (config.square || config.circle) return;
config.hMm = clamp(ui.edH.value, 5, 150);
applyEditorPreview(editorKind);
});
ui.edH.addEventListener("change", () => refreshEditorPreview(editorKind));
[["edRotate", "rotate"], ["edOpacity", "opacity"], ["edX", "x"], ["edY", "y"]].forEach(
([id, key]) => {
const element = $(id);
element.addEventListener("input", () => {
const config = currentEditConfig();
config[key] = Number(element.value);
const output = $(
id === "edRotate"
? "edRotateOut"
: id === "edOpacity"
? "edOpacityOut"
: id === "edX"
? "edXOut"
: "edYOut"
);
if (output) output.textContent = String(config[key]);
applyEditorPreview(editorKind);
});
}
);
// Drag image in editor
function bindEditorDrag(kind) {
const image = kind === "seal" ? ui.editSealImg : ui.editSigImg;
image.addEventListener("pointerdown", (event) => {
event.preventDefault();
editorKind = kind;
syncEditorControls();
const rect = ui.editPaper.getBoundingClientRect();
const config = state.overlay[kind];
const move = (moveEvent) => {
config.x = clamp(((moveEvent.clientX - rect.left) / rect.width) * 100, 0, 100);
config.y = clamp(((moveEvent.clientY - rect.top) / rect.height) * 100, 0, 100);
ui.edX.value = String(config.x);
ui.edY.value = String(config.y);
ui.edXOut.textContent = String(Math.round(config.x * 10) / 10);
ui.edYOut.textContent = String(Math.round(config.y * 10) / 10);
applyEditorPreview(kind);
};
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
});
}
bindEditorDrag("seal");
bindEditorDrag("signature");
ui.edSave.addEventListener("click", () => {
if (!ui.edAuth.checked) {
setEdStatus("请先勾选授权确认。");
return;
}
localStorage.setItem(AUTH_KEY, "1");
if (!saveOverlay()) {
setEdStatus("保存失败:本地存储空间可能不足,请换一张更小的图片。");
return;
}
closeEditor();
addLog("印章/签字设置已保存。");
});
ui.edCrop.addEventListener("click", () => {
if (!currentEditConfig().dataUrl) {
setEdStatus("请先上传图片。");
return;
}
openCrop(false);
});
// ---------------------------------------------------------------------
// Crop modal
// ---------------------------------------------------------------------
function renderCrop() {
if (!cropState) return;
const crop = cropState.crop;
ui.cropBox.style.left = crop.cropLeft + "%";
ui.cropBox.style.top = crop.cropTop + "%";
ui.cropBox.style.width = 100 - crop.cropLeft - crop.cropRight + "%";
ui.cropBox.style.height = 100 - crop.cropTop - crop.cropBottom + "%";
const handles = ui.cropBox.querySelectorAll(".crop-handle");
handles.forEach((handle) => {
const edge = handle.dataset.edge;
if (edge === "top") { handle.style.left = "50%"; handle.style.top = crop.cropTop + "%"; }
if (edge === "bottom") { handle.style.left = "50%"; handle.style.top = 100 - crop.cropBottom + "%"; }
if (edge === "left") { handle.style.left = crop.cropLeft + "%"; handle.style.top = "50%"; }
if (edge === "right") { handle.style.left = 100 - crop.cropRight + "%"; handle.style.top = "50%"; }
});
}
function layoutCrop(width, height) {
const maxWidth = Math.min(window.innerWidth * 0.78, 800);
const maxHeight = window.innerHeight * 0.56;
const scale = Math.min(maxWidth / width, maxHeight / height);
ui.cropCanvas.style.width = Math.max(80, Math.round(width * scale)) + "px";
ui.cropCanvas.style.height = Math.max(80, Math.round(height * scale)) + "px";
renderCrop();
}
async function computeAutoCrop(dataUrl) {
const image = await loadImage(dataUrl);
const width = image.naturalWidth || image.width;
const height = image.naturalHeight || image.height;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
const bounds = contentBounds(context, width, height);
if (!bounds) throw new Error("没有找到有效图案");
return {
cropLeft: Math.min(60, (bounds.left / width) * 100),
cropRight: Math.min(60, ((width - 1 - bounds.right) / width) * 100),
cropTop: Math.min(60, (bounds.top / height) * 100),
cropBottom: Math.min(60, ((height - 1 - bounds.bottom) / height) * 100),
};
}
async function openCrop(autoFit) {
const config = currentEditConfig();
if (!config.dataUrl) return;
const image = await loadImage(config.dataUrl);
cropState = {
config,
width: image.naturalWidth || image.width,
height: image.naturalHeight || image.height,
crop: {
cropTop: config.cropTop,
cropRight: config.cropRight,
cropBottom: config.cropBottom,
cropLeft: config.cropLeft,
},
};
ui.cropImg.src = config.dataUrl;
ui.cropModal.hidden = false;
layoutCrop(cropState.width, cropState.height);
if (autoFit) {
try {
cropState.crop = await computeAutoCrop(config.dataUrl);
renderCrop();
} catch {
/* 保留原裁剪 */
}
}
}
function closeCrop() {
ui.cropModal.hidden = true;
cropState = null;
}
ui.cropClose.addEventListener("click", closeCrop);
ui.cropCancel.addEventListener("click", closeCrop);
ui.cropModal.addEventListener("click", (event) => {
if (event.target === ui.cropModal) closeCrop();
});
ui.cropAuto.addEventListener("click", async () => {
if (!cropState) return;
try {
cropState.crop = await computeAutoCrop(cropState.config.dataUrl);
renderCrop();
} catch (error) {
setEdStatus(error.message || String(error));
}
});
ui.cropApply.addEventListener("click", async () => {
if (!cropState) return;
const config = cropState.config;
config.cropTop = cropState.crop.cropTop;
config.cropRight = cropState.crop.cropRight;
config.cropBottom = cropState.crop.cropBottom;
config.cropLeft = cropState.crop.cropLeft;
config.srcW = cropState.width;
config.srcH = cropState.height;
if (config.square || config.circle) config.hMm = config.wMm;
closeCrop();
syncEditorControls();
applyEditorPreview(editorKind);
await refreshEditorPreview(editorKind);
setEdStatus("裁剪完成,设置长宽后保存。");
});
ui.cropBox.querySelectorAll(".crop-handle").forEach((handle) => {
handle.addEventListener("pointerdown", (event) => {
if (!cropState) return;
event.preventDefault();
event.stopPropagation();
const edge = handle.dataset.edge;
const startX = event.clientX;
const startY = event.clientY;
const start = { ...cropState.crop };
const width = ui.cropCanvas.offsetWidth || 1;
const height = ui.cropCanvas.offsetHeight || 1;
const move = (moveEvent) => {
const dx = ((moveEvent.clientX - startX) / width) * 100;
const dy = ((moveEvent.clientY - startY) / height) * 100;
const crop = cropState.crop;
if (edge === "top") crop.cropTop = clamp(start.cropTop + dy, 0, 60);
if (edge === "bottom") crop.cropBottom = clamp(start.cropBottom - dy, 0, 60);
if (edge === "left") crop.cropLeft = clamp(start.cropLeft + dx, 0, 60);
if (edge === "right") crop.cropRight = clamp(start.cropRight - dx, 0, 60);
if (crop.cropLeft + crop.cropRight > 88) {
if (edge === "left") crop.cropLeft = Math.max(0, 88 - crop.cropRight);
else crop.cropRight = Math.max(0, 88 - crop.cropLeft);
}
if (crop.cropTop + crop.cropBottom > 88) {
if (edge === "top") crop.cropTop = Math.max(0, 88 - crop.cropBottom);
else crop.cropBottom = Math.max(0, 88 - crop.cropTop);
}
renderCrop();
};
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
});
});
// ---------------------------------------------------------------------
// Search / batch
// ---------------------------------------------------------------------
function norm(value) {
return String(value == null ? "" : value).replace(/\s+/g, "").toLowerCase();
}
function findHome(vm) {
if (vm && vm.searchForm && typeof vm.loadTableListData === "function") return vm;
for (const child of (vm && vm.$children) || []) {
const found = findHome(child);
if (found) return found;
}
return null;
}
async function getHome() {
let home = findHome(window.vueInstance);
for (let i = 0; i < 20 && !home; i += 1) {
await sleep(250);
home = findHome(window.vueInstance);
}
return home;
}
function pickCandidate(rows, record) {
let candidates = (rows || []).filter((row) => norm(row.xm) === norm(record.name));
if (record.xjh) {
candidates = candidates.filter((row) => norm(row.xjh) === norm(record.xjh));
}
if (record.className && candidates.length > 1) {
const wanted = norm(record.className);
const filtered = candidates.filter((row) => {
const values = [row.bjmc, row.bjmcjc, row.njmc, row.xqmc].map(norm).filter(Boolean);
return values.some(
(value) => value === wanted || value.includes(wanted) || wanted.includes(value)
);
});
if (filtered.length > 0) candidates = filtered;
}
if (candidates.length === 0) return { error: "没有搜到该学生" };
if (candidates.length > 1) {
return { error: "搜到多个同名学生,请在名单里补班级或学籍号。" };
}
return { row: candidates[0] };
}
async function searchStudent(name) {
const home = await getHome();
if (!home) throw new Error("请先打开“学籍档案”列表页。");
home.searchForm.xm = name;
home.searchForm.xjh = "";
home.searchForm.sfzjhm = "";
if (home.tablePagination) {
home.tablePagination.currentPage = 1;
home.tablePagination.pageSize = 50;
}
home.tableListData = [];
await home.loadTableListData();
await sleep(300);
return (home.tableListData || []).map((row) => ({
xm: row.xm,
xjh: row.xjh,
xsdm: row.xsdm,
njmc: row.njmc,
bjmc: row.bjmc,
bjmcjc: row.bjmcjc,
xqmc: row.xqmc,
}));
}
function searchSerial(name) {
const run = state.searchChain.then(() => searchStudent(name));
state.searchChain = run.catch(() => {});
return run;
}
function waitFor(check, timeout, interval, label) {
return new Promise((resolve, reject) => {
const start = Date.now();
const tick = async () => {
if (state.stopRequested) {
reject(new Error("已停止"));
return;
}
try {
const value = await check();
if (value) {
resolve(value);
return;
}
} catch {
/* 继续等 */
}
if (Date.now() - start > timeout) {
reject(new Error(label + "超时"));
return;
}
setTimeout(tick, interval);
};
tick();
});
}
function findDownloadButton(doc) {
if (!doc) return null;
return (
Array.from(doc.querySelectorAll("button")).find(
(button) => button.textContent.replace(/\s+/g, "") === "下载学籍档案"
) || null
);
}
function findStudentPhoto(doc) {
if (!doc) return null;
return (
doc.getElementById("head-sculpture-img") ||
doc.querySelector('img[id*="head"],img[class*="head"],img[id*="photo"],img[class*="photo"],img[id*="avatar"],img[class*="avatar"]')
);
}
async function applyOverlays(frame, overlays) {
const doc = frame.contentDocument;
if (!doc) return;
const pages = doc.querySelectorAll(".page-auto");
const target = pages.length ? pages[pages.length - 1] : doc.querySelector(".page-auto-container");
if (!target) return;
try {
if (doc.defaultView.getComputedStyle(target).position === "static") {
target.style.position = "relative";
}
} catch {
target.style.position = "relative";
}
for (const kind of ["signature", "seal"]) {
const config = overlays[kind];
if (!config || !config.enabled || !config.dataUrl) continue;
const url = config.processedUrl || (await buildOverlay(config));
if (!url) continue;
const image = doc.createElement("img");
image.src = url;
image.setAttribute("data-xjda-overlay", kind);
image.style.cssText =
"position:absolute;left:" +
config.x +
"%;top:" +
config.y +
"%;width:" +
(config.wMm / A4_W) * 100 +
"%;height:" +
(config.hMm / A4_H) * 100 +
"%;transform:translate(-50%,-50%) rotate(" +
config.rotate +
"deg);opacity:" +
config.opacity / 100 +
";pointer-events:none;z-index:99999;object-fit:fill;";
target.appendChild(image);
try {
await image.decode();
} catch {
/* 图片解码失败不阻塞 */
}
}
}
function installPdfHook(win) {
if (!win || win.__xjdaPdfHooked) return;
win.__xjdaPdfHooked = true;
win.__xjdaPdfBlob = null;
win.__xjdaPdfName = "";
const originalCreate = win.URL.createObjectURL.bind(win.URL);
win.URL.createObjectURL = function (object) {
try {
const type = (object && object.type) || "";
if (/pdf/i.test(type) || (object && object.size > 50_000)) {
win.__xjdaPdfBlob = object;
}
} catch {
/* 忽略 */
}
return originalCreate(object);
};
const originalClick = win.HTMLAnchorElement.prototype.click;
win.HTMLAnchorElement.prototype.click = function () {
try {
const href = this.href || "";
const name = this.download || "";
if (/\.pdf$/i.test(name) || href.startsWith("blob:") || /\.pdf/i.test(href)) {
win.__xjdaPdfName = name;
if (!win.__xjdaPdfBlob && href.startsWith("blob:")) win.__xjdaPdfHref = href;
}
} catch {
/* 忽略 */
}
return originalClick.apply(this, arguments);
};
const originalDispatch = win.HTMLAnchorElement.prototype.dispatchEvent;
win.HTMLAnchorElement.prototype.dispatchEvent = function (event) {
try {
if (this.href && this.href.startsWith("blob:")) {
win.__xjdaPdfHref = this.href;
win.__xjdaPdfName = this.download || win.__xjdaPdfName;
}
} catch {
/* 忽略 */
}
return originalDispatch.apply(this, arguments);
};
}
async function waitPdf(win, fallbackName) {
await waitFor(
() => (win.__xjdaPdfBlob ? true : win.__xjdaPdfHref ? true : false),
120_000,
300,
"等待 PDF 生成"
);
if (win.__xjdaPdfBlob) {
return { blob: win.__xjdaPdfBlob, filename: win.__xjdaPdfName || fallbackName };
}
const response = await fetch(win.__xjdaPdfHref);
return { blob: await response.blob(), filename: win.__xjdaPdfName || fallbackName };
}
async function downloadOne(record, overlays) {
const row = record.row;
const detailUrl =
"/www/xsxj/xjda/xsxq?xjh=" +
encodeURIComponent(row.xjh) +
"&xsdm=" +
encodeURIComponent(row.xsdm) +
"&gdxjdacx=1";
const iframe = document.createElement("iframe");
iframe.setAttribute("aria-hidden", "true");
iframe.style.cssText =
"position:fixed;left:0;top:0;width:1280px;height:1000px;border:0;opacity:0.01;z-index:-2147483647;pointer-events:none;background:#fff;";
iframe.src = detailUrl;
(document.body || document.documentElement).appendChild(iframe);
state.frames.add(iframe);
try {
await waitFor(
() => {
const doc = iframe.contentDocument;
return doc && doc.body && doc.body.innerText.includes("学籍档案证明") ? doc : null;
},
45_000,
400,
"打开学生详情"
);
await waitFor(
() => {
const doc = iframe.contentDocument;
return doc && doc.body && doc.body.innerText.includes(record.name) ? doc : null;
},
30_000,
400,
"加载学生信息"
);
const photo = findStudentPhoto(iframe.contentDocument);
if (photo) {
photo.loading = "eager";
await waitFor(
() => {
const image = findStudentPhoto(iframe.contentDocument);
return Boolean(image && image.getAttribute("src") && image.complete && image.naturalWidth);
},
20_000,
300,
"等待学生照片"
).catch(() => addLog("提示:学生照片未加载完成", "err"));
} else {
await sleep(3000);
}
try {
await iframe.contentDocument.fonts.ready;
} catch {
/* 忽略 */
}
await waitFor(
() => Array.from(iframe.contentDocument.images).every((image) => image.complete),
15_000,
300,
"等待图片"
).catch(() => {});
installPdfHook(iframe.contentWindow);
await applyOverlays(iframe, overlays);
await sleep(state.waitMs);
if (state.stopRequested) throw new Error("已停止");
const button = await waitFor(
() => findDownloadButton(iframe.contentDocument),
30_000,
300,
"查找下载按钮"
);
if (button.disabled) {
await waitFor(() => !button.disabled, 15_000, 300, "等待下载按钮");
}
const fallback = `${row.njmc || ""}_${row.bjmc || ""}_${record.name}.pdf`;
button.click();
const result = await waitPdf(iframe.contentWindow, fallback);
const saved = await saveBlob(result.blob, result.filename || fallback);
addLog(
(saved.kind === "folder" ? "已保存:" : "已下载:") + saved.filename,
"ok"
);
} finally {
state.frames.delete(iframe);
iframe.remove();
}
}
async function runBatch(records) {
state.running = true;
state.stopRequested = false;
state.total = records.length;
state.done = 0;
ui.start.disabled = true;
ui.stop.disabled = false;
ui.log.textContent = "";
setProgress(0, records.length);
const waitSeconds = clamp(ui.wait.value, 0, 15);
const concurrency = clamp(ui.conc.value, 1, 5);
state.waitMs = waitSeconds * 1000;
state.concurrency = Math.max(1, Math.min(concurrency, records.length));
saveSettings();
const overlays = {
seal: normalizeOverlay("seal", state.overlay.seal),
signature: normalizeOverlay("signature", state.overlay.signature),
};
for (const kind of ["seal", "signature"]) {
if (!overlays[kind].enabled || !overlays[kind].dataUrl) continue;
try {
overlays[kind].processedUrl = await buildOverlay(overlays[kind]);
if (overlays[kind].processedUrl) addLog("已启用:" + (kind === "seal" ? "印章" : "签字"));
} catch (error) {
addLog("印章/签字处理失败:" + (error.message || error), "err");
}
}
addLog(
"开始处理 " + records.length + " 人(并发 " + state.concurrency + ",等待 " + waitSeconds + " 秒)"
);
if (!state.dirHandle) addLog("未选择文件夹,将保存到默认下载目录。");
let next = 0;
let done = 0;
let ok = 0;
let failed = 0;
const worker = async () => {
while (!state.stopRequested) {
const index = next;
next += 1;
if (index >= records.length) return;
const record = records[index];
try {
addLog("→ " + record.name);
const rows = await searchSerial(record.name);
const picked = pickCandidate(rows, record);
if (picked.error) throw new Error(picked.error);
await downloadOne({ ...record, row: picked.row }, overlays);
ok += 1;
} catch (error) {
failed += 1;
addLog("✗ " + record.name + ":" + (error.message || error), "err");
} finally {
done += 1;
state.done = done;
setProgress(done, records.length);
}
}
};
const workers = [];
for (let i = 0; i < state.concurrency; i += 1) workers.push(worker());
await Promise.all(workers);
state.running = false;
ui.start.disabled = false;
ui.stop.disabled = true;
addLog(
"全部结束:成功 " + ok + ",失败 " + failed + (state.stopRequested ? "(已停止)" : ""),
failed ? "err" : "ok"
);
setHint("保存位置:" + (state.dirHandle ? state.dirHandle.name : "默认下载目录"));
}
function stopBatch() {
state.stopRequested = true;
for (const frame of [...state.frames]) frame.remove();
state.frames.clear();
addLog("已请求停止。", "err");
}
ui.stop.addEventListener("click", stopBatch);
ui.names.addEventListener("input", updateCount);
ui.start.addEventListener("click", async () => {
if (state.running) return;
const records = parseNames(ui.names.value);
if (records.length === 0) {
setHint("请先填写学生名单。");
return;
}
saveSettings();
if (state.dirHandle) {
const allowed = await ensureDirPermission();
if (!allowed) addLog("文件夹未授权,本次使用默认下载目录。", "err");
}
loadOverlay();
const home = await getHome();
if (!home) {
setHint("当前不在“学籍档案”列表页,正在打开列表页…");
location.href = LIST_URL;
return;
}
await runBatch(records);
});
// ---------------------------------------------------------------------
// Init
// ---------------------------------------------------------------------
loadSettings();
loadOverlay();
restoreDirHandle().catch(() => {});
})();