// ==UserScript== // @name 文档免费下载 // @namespace https://github.com/wayner6/kill-doc // @version 9.1.0 // @description 基于 kill-doc 深度重构。单次点击一键全自动渲染并导出高清 1:1 原貌尺寸 PDF,智能裁切消除白边,支持随时中断下载。 // @author kill-doc-dev // @downloadURL https://raw.githubusercontent.com/wayner6/kill-doc/master/script/index.js // @updateURL https://raw.githubusercontent.com/wayner6/kill-doc/master/script/index.js // @match https://*.book118.com/* // @match https://*.renrendoc.com/* // @match https://*.docin.com/* // @match https://*.doc88.com/* // @match https://doc.mbalib.com/* // @match https://*.deliwenku.com/* // @match https://www.jinchutou.com/* // @match https://*.goldhoe.com/* // @match https://*.mayiwenku.com/* // @match https://*.dugen.com/* // @match https://*.7cxk.com/* // @match https://ishare.iask.com/* // @match https://swf.iask.com/* // @match https://*.down.sina.com.cn/* // @match https://wenku.baidu.com/* // @match https://wkbjcloudbos.bdimg.com/* // @match https://wkretype.bdimg.com/* // @match https://*.chochina.com/* // @match https://*.weizhuannet.com/* // @match https://www.taodocs.com/* // @match https://wenku.so.com/* // @match https://*.360tres.com/* // @match https://www.wenkub.com/* // @match http://c.gb688.cn/* // @match https://openstd.samr.gov.cn/bzgk/* // @match https://jjg.spc.org.cn/resmea/view/stdonline // @match https://pro-img-brtm.baijiayun.com/* // @match https://hbba.sacinfo.org.cn/attachment/onlineRead/* // @match https://www.qzoffice.com/* // @match http://www.nrsis.org.cn/mnr_kfs/file/read/* // @match https://*.feishu.cn/space/* // @match https://*.feishu.cn/file/* // @match https://*.larkoffice.com/space/api/box/stream/download/preview_tpl3/* // @match http://www.jtysbz.cn:8009/pdf/viewer/* // @match https://www.nssi.org.cn/cssn/js/pdfjs/web/preview.jsp* // @match https://online.71nc.cn/* // @match https://114.251.111.103:18080/kfs/file/read/* // @match https://bulletin.cebpubservice.com/resource/ceb/js/pdfjs-dist/web/viewer.html* // @match http://121.36.94.83:9008/jsp/yishenqing/appladd/biaozhunfile/flash/previewImg.jsp* // @match http://rbtest.cnca.cn/cnca_kfs/file/read/* // @match https://weboffice.qq.com/pdf/* // @match https://gbservice.cn/* // @match https://ecp.sgcc.com.cn/* // @match https://vt.quark.cn/blm/quark-doc-main-pc-966/** // @match https://wenku-img.docs.quark.cn/* // @match https://preview-wenku.quark.cn/* // @match https://jtst.mot.gov.cn/kfs/file/read/* // @require https://unpkg.com/jspdf@2.4.0/dist/jspdf.umd.min.js // @icon https://dtking.cn/favicon.ico // @run-at document-idle // @grant GM_download // @grant GM_notification // @grant GM_addStyle // @grant unsafeWindow // @license Apache-2.0 // ==/UserScript== (function() { 'use strict'; // ==================== 基础工具与 DOM 增强 ==================== function generateRandomString(len = 5) { let res = ''; const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; for (let i = 0; i < len; i++) { res += chars.charAt(Math.floor(Math.random() * chars.length)); } return res; } const prefix = generateRandomString() + "_"; const boxId = generateRandomString(); const styles = ` #${prefix}${boxId} { position: fixed; top: 50%; transform: translateY(-50%); right: 20px; gap: 12px; flex-direction: column; z-index: 2147483647; display: flex; user-select: none; } .${prefix}box { padding: 10px 14px; cursor: pointer; border: 1px solid #0066ff; border-radius: 6px; background-color: #ffffff; color: #0066ff; font-size: 13px; font-weight: bold; box-shadow: 0 2px 10px rgba(0,0,0,0.15); transition: all 0.2s; text-align: center; min-width: 96px; outline: none; } .${prefix}box:hover { background-color: #0066ff; color: #ffffff; } .${prefix}active { color: #28a745; border-color: #28a745; background-color: #f0fff4; cursor: default; } .${prefix}active:hover { background-color: #f0fff4; color: #28a745; } #${prefix}stop { border-color: #dc3545; color: #dc3545; } #${prefix}stop:hover { background-color: #dc3545; color: #ffffff; } @media print { html { height: auto !important; } body { display: block !important; } #${prefix}${boxId}, #mf-download-dialog, .menubar, .top-bar-right, .user-guide, .reader-thumb, .related-doc-list { display: none !important; } } `; // 阻止平台反外挂篡改 drawImage const canvasRenderingContext2DPrototype = CanvasRenderingContext2D.prototype; const originalDrawImage = canvasRenderingContext2DPrototype.drawImage; Object.defineProperty(canvasRenderingContext2DPrototype, 'drawImage', { value: originalDrawImage, writable: false, configurable: false }); // 重写 setTimeout,防止关键回调被平台干扰 const originalSetTimeout = unsafeWindow.setTimeout; unsafeWindow.setTimeout = function(callback, delay, ...args) { const toStr = callback?.toString(); if (toStr && toStr.includes('revokeObjectURL')) return true; const wrappedCallback = function() { if (callback instanceof Function) { callback(...args); } }; return originalSetTimeout(wrappedCallback, delay); }; class Utility { style(e, data) { Object.keys(data).forEach(key => { e.style[key] = data[key]; }); } appendStyle(css) { const style = document.createElement('style'); style.textContent = css; style.type = 'text/css'; (document.head || document.documentElement).appendChild(style); } createEl(id, elType, data) { const el = document.createElement(elType); el.id = id || ''; if (data) this.style(el, data); return el; } query(el) { return document.querySelector(el); } queryAll(el) { return document.querySelectorAll(el); } update(el, text) { const elNode = this.query(el); if (elNode) elNode.innerText = text; } sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } preview(current, total, content) { return new Promise(async (resolve) => { if (current === -1) { this.update('#' + prefix + 'text', content || "已完成"); } else { const p = (current / total) * 100; const ps = p.toFixed(0) > 100 ? 100 : p.toFixed(0); this.update('#' + prefix + 'text', content || `进度 ${ps}%`); await this.sleep(120); } resolve(); }); } preText(content) { this.update('#' + prefix + 'text', content); } gui(boxs) { const oldBox = document.getElementById(prefix + boxId); if (oldBox) oldBox.remove(); const box = this.createEl(prefix + boxId, 'div'); for (let x in boxs) { const item = boxs[x]; if (!item || !item.id) continue; const el = this.createEl(prefix + item.id, 'button'); el.textContent = item.label; if (x === '0' || item.id === 'text') { el.className = prefix + 'box ' + prefix + "active"; } else { el.className = prefix + "box"; } if (typeof item.action === 'function') { el.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); item.action(); }); } box.append(el); } document.body.append(box); } } class Box { constructor(id, label, action) { this.id = id; this.label = label; this.action = action; } } const u = new Utility(); // ==================== 站点定义与配置 ==================== const domain = { book118: 'book118.com', renrendoc: 'renrendoc.com', docin: 'docin.com', doc88: 'doc88.com', mbalib: 'doc.mbalib.com', deliwenku: 'deliwenku.com', jinchutou: 'jinchutou.com', goldhoe: 'goldhoe.com', mayiwenku: 'mayiwenku.com', dugen: 'dugen.com', cxk: '7cxk.com', ishare: 'ishare.iask.com', sina: 'down.sina.com.cn', wenku: 'wenku.baidu.com', chochina: 'chochina.com', weizhuannet: 'weizhuannet.com', taodocs: 'taodocs.com', so: 'wenku.so.com', tres: '360tres.com', wenkub: 'wenkub.com', gb688: 'c.gb688.cn', samr: 'openstd.samr.gov.cn', spc: 'jjg.spc.org.cn', baijiayun: 'pro-img-brtm.baijiayun.com', sacinfo: 'hbba.sacinfo.org.cn', qzoffice: 'qzoffice.com', nrsis: 'nrsis.org.cn', feishu: 'feishu.cn', larkoffice: 'larkoffice.com', jtysbz: 'jtysbz.cn', nssi: 'nssi.org.cn', online71nc: 'online.71nc.cn', kfs114: '114.251.111.103', cebpubservice: 'cebpubservice.com', flash: 'flash/previewImg.jsp', rbtest: 'rbtest.cnca.cn', qq: 'weboffice.qq.com', gbservice: 'gbservice.cn', sgcc: 'ecp.sgcc.com.cn', quark: 'quark.cn', jtst: 'jtst.mot.gov.cn' }; const { host, href } = window.location; const jsPDF = jspdf.jsPDF; let doc = null; let collectedImages = []; let title = document.title; let select = null; let dom = null; let beforeFun = null; let isRunning = false; let isAborted = false; // ==================== PDF 与图像处理核心引擎 ==================== const resetState = () => { doc = null; collectedImages = []; }; const cropCanvasWhiteBorders = (canvas) => { if (!canvas || !canvas.width || !canvas.height) return canvas; const width = canvas.width; const height = canvas.height; try { const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, width, height); const data = imgData.data; let top = 0; for (let y = 0; y < height; y++) { let hasContent = false; for (let x = 0; x < width; x += 4) { const idx = (y * width + x) * 4; const r = data[idx], g = data[idx + 1], b = data[idx + 2], a = data[idx + 3]; if (a > 20 && (r < 245 || g < 245 || b < 245)) { hasContent = true; break; } } if (hasContent) { top = Math.max(0, y - 2); break; } } let bottom = height; for (let y = height - 1; y >= 0; y--) { let hasContent = false; for (let x = 0; x < width; x += 4) { const idx = (y * width + x) * 4; const r = data[idx], g = data[idx + 1], b = data[idx + 2], a = data[idx + 3]; if (a > 20 && (r < 245 || g < 245 || b < 245)) { hasContent = true; break; } } if (hasContent) { bottom = Math.min(height, y + 3); break; } } const cropH = bottom - top; if ((top > 20 || bottom < height - 20) && cropH > 100) { const croppedCanvas = document.createElement('canvas'); croppedCanvas.width = width; croppedCanvas.height = cropH; const cCtx = croppedCanvas.getContext('2d'); cCtx.fillStyle = '#FFFFFF'; cCtx.fillRect(0, 0, width, cropH); cCtx.drawImage(canvas, 0, top, width, cropH, 0, 0, width, cropH); return croppedCanvas; } } catch (e) { console.warn('Canvas 边缘探测跳过:', e); } return canvas; }; const savePageToPDF = (canvasOrImg, i, width, height) => { const target_w = Math.round(width || (canvasOrImg && (canvasOrImg.naturalWidth || canvasOrImg.width)) || 595); const target_h = Math.round(height || (canvasOrImg && (canvasOrImg.naturalHeight || canvasOrImg.height)) || 842); const dir = target_w > target_h ? 'l' : 'p'; let dataUrl = ''; if (canvasOrImg && typeof canvasOrImg.toDataURL === 'function') { try { dataUrl = canvasOrImg.toDataURL('image/jpeg', 0.95); } catch (e) {} } if (dataUrl) { collectedImages.push({ src: dataUrl, width: target_w, height: target_h, orientation: dir }); } if (!doc || i === 0) { doc = new jsPDF({ orientation: dir, unit: 'pt', format: [target_w, target_h], compress: true }); } else { doc.addPage([target_w, target_h], dir); } const source = dataUrl || canvasOrImg; doc.addImage(source, 'JPEG', 0, 0, target_w, target_h, undefined, 'FAST'); // 严格约束总页数,剔除溢出空白页 while (doc.getNumberOfPages() > i + 1) { doc.deletePage(doc.getNumberOfPages()); } }; // ==================== 下载与打印调度 ==================== const MF_SafeDownload = (blob, filename) => { const safeName = (filename || 'document').replace(/[\\/:*?"<>|\r\n\t]/g, '_').trim(); const blobUrl = URL.createObjectURL(blob); if (typeof GM_download === 'function') { try { GM_download({ url: blobUrl, name: safeName, saveAs: false, onload: () => { setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); }, onerror: (err) => { console.warn('[GM_download 失败,回退标准下载]', err); triggerNativeDownload(blobUrl, safeName); } }); return; } catch (e) { console.warn('[GM_download 异常]', e); } } triggerNativeDownload(blobUrl, safeName); }; const triggerNativeDownload = (blobUrl, filename) => { const link = document.createElement('a'); link.href = blobUrl; link.download = filename; link.style.display = 'none'; document.body.appendChild(link); const evt = new MouseEvent('click', { bubbles: false, cancelable: true }); link.dispatchEvent(evt); setTimeout(() => { if (document.body.contains(link)) document.body.removeChild(link); URL.revokeObjectURL(blobUrl); }, 10000); }; const showDownloadDialog = (safeTitle, pdfBlob) => { const oldDialog = document.getElementById('mf-download-dialog'); if (oldDialog) oldDialog.remove(); const dialog = document.createElement('div'); dialog.id = 'mf-download-dialog'; dialog.style.cssText = 'position:fixed;top:30px;right:30px;z-index:2147483647;background:#ffffff;border:2px solid #0066ff;border-radius:10px;padding:18px 22px;box-shadow:0 8px 30px rgba(0,0,0,0.25);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;min-width:320px;max-width:420px;'; const blobUrl = pdfBlob ? URL.createObjectURL(pdfBlob) : null; const fileName = `${safeTitle}.pdf`; dialog.innerHTML = `