<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
<%
|
String path = request.getContextPath();
|
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
|
+ path + "/";
|
%>
|
|
<!DOCTYPE html>
|
<html dir="ltr" mozdisallowselectionprint>
|
<head>
|
<base href="<%=basePath%>">
|
<meta charset="utf-8">
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
<title>OFD 文件浏览</title>
|
|
<!-- 从 pdfjs-newest/web 复制而来的独立副本,避免升级 pdf.js 时影响 OFD 浏览页 -->
|
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/plugins/ofdjs/viewer/viewer.css">
|
|
<!-- ofd.js 纯开源版 (GitHub源码构建, Apache 2.0, 无授权检查) -->
|
<script src="${pageContext.request.contextPath}/static/plugins/ofdjs/ofd.umd.js"></script>
|
|
<script src="${pageContext.request.contextPath}/static/plugins/jquery/jquery.min.js"></script>
|
|
<style>
|
/* viewer.css 只设了 html/body 的宽高,没有清 margin */
|
body { margin: 0; }
|
|
/* viewer.css 已把 #viewerContainer 定为 absolute + top:32px + bottom:0,
|
这里不能再设 min-height,否则容器高度超出 body,会多出一条外层滚动条 */
|
#viewerContainer {
|
overflow: auto !important;
|
}
|
/* width:max-content + min-width:100%:放大到超出容器宽度时,
|
左侧内容不会因居中而滚不到 */
|
#viewer.ofdViewer {
|
display: flex;
|
flex-direction: column;
|
align-items: center;
|
padding: 10px 0;
|
width: max-content;
|
min-width: 100%;
|
}
|
/* position:relative 必须挂在 .ofd-page 本身:打印容器里的页面同样依赖它定位子元素 */
|
.ofd-page {
|
position: relative;
|
background: #fff;
|
}
|
#viewer.ofdViewer > .ofd-page {
|
margin-bottom: 10px;
|
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
|
}
|
|
/* 单页加载占位:页面按真实尺寸先占位,滚动到附近才渲染内容 */
|
.ofd-page-loading {
|
position: absolute;
|
top: 0; left: 0; right: 0; bottom: 0;
|
display: flex;
|
flex-direction: column;
|
align-items: center;
|
justify-content: center;
|
background: #fff;
|
color: #888;
|
font-size: 13px;
|
z-index: 2500000;
|
}
|
.ofd-page-spinner {
|
width: 28px;
|
height: 28px;
|
margin-bottom: 8px;
|
border: 3px solid #e0e0e0;
|
border-top-color: #0a84ff;
|
border-radius: 50%;
|
animation: ofd-spin 0.8s linear infinite;
|
}
|
@keyframes ofd-spin { to { transform: rotate(360deg); } }
|
.ofd-page-loading.failed .ofd-page-spinner {
|
animation: none;
|
border-top-color: #d9534f;
|
}
|
|
/* 每页独立水印层:随页面滚动,z-index 高于签章(2000000) */
|
.ofd-watermark {
|
position: absolute;
|
top: 0;
|
left: 0;
|
pointer-events: none;
|
z-index: 3000000;
|
}
|
|
/* 侧栏缩略图(其余样式复用 viewer.css 的 .thumbnail / .thumbnailSelectionRing / .thumbnailImage) */
|
.sidebarTitle {
|
padding: 0 10px;
|
line-height: 32px;
|
font-size: 12px;
|
color: var(--toolbar-icon-color, #666);
|
}
|
#thumbnailView a {
|
cursor: pointer;
|
text-decoration: none;
|
}
|
|
/* 打印:viewer.css 已负责隐藏 #outerContainer、显示 #printContainer、
|
并给 .printedPage 加分页符,这里只处理 OFD 页自身的外观 */
|
@media print {
|
/* flex:none 阻止 .printedPage 的 flex 布局压缩页面高度 */
|
#printContainer > .printedPage > .ofd-print-page {
|
flex: none;
|
overflow: hidden;
|
}
|
#printContainer .ofd-page {
|
box-shadow: none;
|
margin: 0;
|
}
|
.ofd-page-loading { display: none !important; }
|
}
|
</style>
|
|
<script>
|
// ── 后端传入参数 ──
|
var enableWatermark = ${enableWatermark};
|
var watermarkText = "${watermarkText}";
|
var watermarkTransparency = ${watermarkTransparency}/100;
|
var watermarkFontsize = ${watermarkFontsize};
|
var watermarkAngle = ${watermarkAngle};
|
var watermarkPosition = "${watermarkPosition}";
|
var attachViewUrl = "${attachViewUrl}";
|
// Spring 默认不识别 .ofd 后缀,将 getAttachStream.ofd? 改为 general/getAttachStream?
|
attachViewUrl = attachViewUrl.replace('getAttachStream.ofd?', 'general/getAttachStream?');
|
var attachId = "${attach.attachId}";
|
|
// ── 布局常量 ──
|
var VIEWER_HORIZONTAL_PADDING = 40; // 页面两侧留白,用于算可用宽度
|
var PAGE_PRELOAD_MARGIN = '400px 0px';// 距视口 400px 内的页面提前渲染
|
var RELAYOUT_DEBOUNCE_MS = 250; // 侧栏动画 / 窗口拖拽结束后再重排
|
var DEFAULT_SCREEN_WIDTH = 800; // 容器尚未布局时的兜底宽度
|
var CAL_PAGE_BOX_INSET = 10; // ofd.calPageBox 会从传入宽度里扣掉 10px
|
|
// ── 全局状态 ──
|
var ofdDoc = null; // ofd.js 解析结果
|
var totalPages = 0;
|
var currentPage = 1;
|
var currentScale = 1.0;
|
var currentRotation = 0;
|
|
// ── 逐页渲染状态 ──
|
var layoutScreenWidth = DEFAULT_SCREEN_WIDTH; // 本次布局使用的宽度,重新渲染单页时必须复用
|
var pageState = {}; // 页索引 -> 'pending' | 'done'
|
var pageObserver = null;
|
var renderQueue = [];
|
var renderScheduled = false;
|
|
// ── 权限控制(从后端传入) ──
|
var printPerm = ${printPermission};
|
var downloadPerm = ${downloadPermission};
|
|
// ── 初始化 ──
|
window.onload = function() {
|
bindToolbarEvents();
|
bindKeyboardEvents();
|
bindScrollTracking();
|
bindResize();
|
updateScaleSelect();
|
|
if (!printPerm) { $('#print').remove(); $('#secondaryPrint').remove(); }
|
if (!downloadPerm) { $('#download').remove(); $('#secondaryDownload').remove(); }
|
|
loadOfdDocument(attachViewUrl);
|
};
|
|
// ── 加载 OFD 文档 ──
|
function loadOfdDocument(url) {
|
showLoading(true);
|
hideError();
|
|
// XHR 手动加载为 ArrayBuffer,避免 JSZipUtils URL 加载的兼容问题
|
var xhr = new XMLHttpRequest();
|
xhr.open('GET', url, true);
|
xhr.responseType = 'arraybuffer';
|
xhr.onprogress = function(e) {
|
updateDownloadProgress(e.lengthComputable ? e.loaded / e.total : -1);
|
};
|
xhr.onload = function() {
|
if (xhr.status === 200) {
|
ofd.parseOfdDocument({
|
ofd: xhr.response, // ArrayBuffer 路径,不走 JSZipUtils
|
success: function(docs) {
|
if (docs && docs.length > 0) {
|
ofdDoc = docs[0];
|
totalPages = ofdDoc.pages ? ofdDoc.pages.length : 0;
|
}
|
layoutPages();
|
// 用户可能在文档加载完成前就打开了侧栏
|
if (document.getElementById('outerContainer').classList.contains('sidebarOpen')) {
|
buildThumbnails();
|
}
|
showLoading(false);
|
updateUI();
|
},
|
fail: function(err) {
|
console.error('parse fail:', err);
|
showLoading(false);
|
showError('OFD 解析失败:' + (err && err.message ? err.message : err));
|
}
|
});
|
} else {
|
showLoading(false);
|
showError('文件加载失败,HTTP ' + xhr.status);
|
}
|
};
|
xhr.onerror = function() {
|
showLoading(false);
|
showError('文件加载失败:网络错误');
|
};
|
xhr.send();
|
}
|
|
// ── 页面占位:按真实尺寸先铺出所有页,内容留到滚动到附近再渲染 ──
|
function layoutPages() {
|
var viewer = document.getElementById('viewer');
|
if (!viewer || !ofdDoc || !ofdDoc.pages) return;
|
|
if (pageObserver) { pageObserver.disconnect(); pageObserver = null; }
|
renderQueue = [];
|
pageState = {};
|
viewer.innerHTML = '';
|
|
// 缩放通过"按更大的宽度重新排版"实现,而不是 CSS transform ——
|
// transform 不参与布局,放大后超出的部分滚不到
|
layoutScreenWidth = screenPageWidthAt100() * currentScale;
|
totalPages = ofdDoc.pages.length;
|
|
try {
|
ofdDoc.pages.forEach(function(page, i) {
|
var box = ofd.calPageBox(layoutScreenWidth, ofdDoc.document, page);
|
var div = document.createElement('div');
|
div.className = 'ofd-page';
|
div.id = Object.keys(page)[0];
|
div.setAttribute('data-page', i + 1);
|
div.style.width = box.w + 'px';
|
div.style.height = box.h + 'px';
|
div.appendChild(buildLoadingNode('正在加载第 ' + (i + 1) + ' 页'));
|
viewer.appendChild(div);
|
});
|
} catch(e) {
|
showError('OFD 渲染失败:' + e.message);
|
console.error(e);
|
return;
|
}
|
|
observePages();
|
updateUI();
|
}
|
|
function buildLoadingNode(text) {
|
var box = document.createElement('div');
|
box.className = 'ofd-page-loading';
|
var spinner = document.createElement('div');
|
spinner.className = 'ofd-page-spinner';
|
var label = document.createElement('span');
|
label.textContent = text;
|
box.appendChild(spinner);
|
box.appendChild(label);
|
return box;
|
}
|
|
// ── 懒渲染调度 ──
|
function observePages() {
|
var viewer = document.getElementById('viewer');
|
var container = document.getElementById('viewerContainer');
|
|
if (typeof IntersectionObserver === 'undefined') {
|
// 老浏览器没有 IntersectionObserver,退回一次性全渲染
|
for (var i = 0; i < totalPages; i++) enqueuePage(i);
|
return;
|
}
|
|
pageObserver = new IntersectionObserver(function(entries) {
|
entries.forEach(function(entry) {
|
if (!entry.isIntersecting) return;
|
enqueuePage(parseInt(entry.target.getAttribute('data-page'), 10) - 1);
|
});
|
}, { root: container, rootMargin: PAGE_PRELOAD_MARGIN });
|
|
Array.prototype.forEach.call(viewer.children, function(div) {
|
pageObserver.observe(div);
|
});
|
}
|
|
function enqueuePage(index) {
|
if (pageState[index]) return;
|
pageState[index] = 'pending';
|
enqueueRender(function() { renderPageAt(index); });
|
}
|
|
function enqueueRender(task) {
|
renderQueue.push(task);
|
scheduleRender();
|
}
|
|
// 每帧只渲染一项(正文页或缩略图),避免多页文档一次性阻塞主线程、loading 转不起来
|
function scheduleRender() {
|
if (renderScheduled) return;
|
renderScheduled = true;
|
requestAnimationFrame(function() {
|
renderScheduled = false;
|
var task = renderQueue.shift();
|
if (task) task();
|
if (renderQueue.length > 0) scheduleRender();
|
});
|
}
|
|
function renderPageAt(index) {
|
var div = document.querySelector('#viewer > [data-page="' + (index + 1) + '"]');
|
var page = ofdDoc && ofdDoc.pages ? ofdDoc.pages[index] : null;
|
if (!div || !page) return;
|
|
try {
|
// calPageBox 会重置 ofd.js 内部的全局缩放,renderPage 前必须按同一宽度再调一次
|
ofd.calPageBox(layoutScreenWidth, ofdDoc.document, page);
|
ofd.renderPage(div, page, ofdDoc.tpls, ofdDoc.fontResObj, ofdDoc.drawParamResObj, ofdDoc.multiMediaResObj);
|
} catch(e) {
|
console.error('第 ' + (index + 1) + ' 页渲染失败:', e);
|
markPageFailed(div, index);
|
return;
|
}
|
|
addWatermarkTo(div, currentScale);
|
removeLoadingNode(div);
|
pageState[index] = 'done';
|
if (pageObserver) pageObserver.unobserve(div);
|
}
|
|
function removeLoadingNode(div) {
|
var loading = div.querySelector('.ofd-page-loading');
|
if (loading) div.removeChild(loading);
|
}
|
|
function markPageFailed(div, index) {
|
delete pageState[index]; // 允许下次滚动到时重试
|
var loading = div.querySelector('.ofd-page-loading');
|
if (!loading) return;
|
loading.className = 'ofd-page-loading failed';
|
loading.lastChild.textContent = '第 ' + (index + 1) + ' 页渲染失败';
|
}
|
|
// ── 侧栏缩略图:结构沿用 pdf.js(a > .thumbnail > .thumbnailSelectionRing > .thumbnailImage)──
|
var THUMBNAIL_WIDTH = 98;
|
var THUMBNAIL_PRELOAD_MARGIN = '200px 0px';
|
// calPageBox 的缩放只精确到 0.1;扫描件坐标单位达 2322,缩略图所需的 0.04 会被舍入成 0,
|
// 页面塌成 0x0。故渲染不低于 0.1,再用 CSS transform 缩到目标宽度。
|
var MIN_THUMBNAIL_RENDER_SCALE = 0.1;
|
var thumbnailsBuilt = false;
|
var thumbnailObserver = null;
|
var thumbnailState = {};
|
|
// 页面在 OFD 自身坐标系中的宽度(单位随生成器而异,只用于反推缩放)
|
function pageUnitWidth(page) {
|
var box = ofd.calPageBox(DEFAULT_SCREEN_WIDTH, ofdDoc.document, page);
|
return box.w / parseFloat(ofd.getPageScale());
|
}
|
|
function thumbnailBoxOf(page) {
|
var units = pageUnitWidth(page);
|
var scale = Math.max(THUMBNAIL_WIDTH / units, MIN_THUMBNAIL_RENDER_SCALE);
|
return ofd.calPageBox(units * scale + CAL_PAGE_BOX_INSET, ofdDoc.document, page);
|
}
|
|
function buildThumbnails() {
|
if (thumbnailsBuilt || !ofdDoc || !ofdDoc.pages) return;
|
var view = document.getElementById('thumbnailView');
|
view.innerHTML = '';
|
thumbnailState = {};
|
|
ofdDoc.pages.forEach(function(page, index) {
|
var box = thumbnailBoxOf(page);
|
var fit = THUMBNAIL_WIDTH / box.w;
|
|
var pageDiv = document.createElement('div');
|
pageDiv.className = 'ofd-page';
|
pageDiv.style.width = box.w + 'px';
|
pageDiv.style.height = box.h + 'px';
|
pageDiv.style.transform = 'scale(' + fit + ')';
|
pageDiv.style.transformOrigin = 'top left';
|
|
var image = document.createElement('div');
|
image.className = 'thumbnailImage';
|
image.style.width = THUMBNAIL_WIDTH + 'px';
|
image.style.height = Math.round(box.h * fit) + 'px';
|
image.style.overflow = 'hidden';
|
image.appendChild(pageDiv);
|
|
var ring = document.createElement('div');
|
ring.className = 'thumbnailSelectionRing';
|
ring.appendChild(image);
|
|
var thumb = document.createElement('div');
|
thumb.className = 'thumbnail';
|
thumb.setAttribute('data-page-number', index + 1);
|
thumb.appendChild(ring);
|
|
var link = document.createElement('a');
|
link.setAttribute('role', 'button');
|
link.setAttribute('tabindex', '0');
|
link.title = '第 ' + (index + 1) + ' 页';
|
link.appendChild(thumb);
|
link.addEventListener('click', function() { goToPage(index + 1); });
|
view.appendChild(link);
|
});
|
|
thumbnailsBuilt = true;
|
observeThumbnails();
|
setActiveThumbnail(currentPage);
|
}
|
|
function observeThumbnails() {
|
var view = document.getElementById('thumbnailView');
|
var thumbs = view.querySelectorAll('.thumbnail');
|
|
if (typeof IntersectionObserver === 'undefined') {
|
for (var i = 0; i < thumbs.length; i++) enqueueThumbnail(i);
|
return;
|
}
|
|
thumbnailObserver = new IntersectionObserver(function(entries) {
|
entries.forEach(function(entry) {
|
if (!entry.isIntersecting) return;
|
enqueueThumbnail(parseInt(entry.target.getAttribute('data-page-number'), 10) - 1);
|
});
|
}, { root: view, rootMargin: THUMBNAIL_PRELOAD_MARGIN });
|
|
Array.prototype.forEach.call(thumbs, function(thumb) {
|
thumbnailObserver.observe(thumb);
|
});
|
}
|
|
function enqueueThumbnail(index) {
|
if (thumbnailState[index]) return;
|
thumbnailState[index] = 'pending';
|
enqueueRender(function() { renderThumbnailAt(index); });
|
}
|
|
function renderThumbnailAt(index) {
|
var thumb = document.querySelector('#thumbnailView .thumbnail[data-page-number="' + (index + 1) + '"]');
|
var page = ofdDoc && ofdDoc.pages ? ofdDoc.pages[index] : null;
|
if (!thumb || !page) return;
|
|
var pageDiv = thumb.querySelector('.ofd-page');
|
pageDiv.innerHTML = ''; // renderPage 是追加式的,重试时先清空避免元素叠加
|
try {
|
// 与占位时相同的缩放;calPageBox 同时重置库内部的全局缩放,必须在 renderPage 前调用
|
thumbnailBoxOf(page);
|
ofd.renderPage(pageDiv, page, ofdDoc.tpls,
|
ofdDoc.fontResObj, ofdDoc.drawParamResObj, ofdDoc.multiMediaResObj);
|
} catch(e) {
|
delete thumbnailState[index]; // 允许下次滚到时重试
|
console.error('第 ' + (index + 1) + ' 页缩略图渲染失败:', e);
|
return;
|
}
|
|
thumbnailState[index] = 'done';
|
thumb.setAttribute('data-loaded', 'true'); // 去掉 viewer.css 的虚线占位边框
|
if (thumbnailObserver) thumbnailObserver.unobserve(thumb);
|
}
|
|
function setActiveThumbnail(pageNumber) {
|
var view = document.getElementById('thumbnailView');
|
if (!view) return;
|
var previous = view.querySelector('.thumbnail.selected');
|
if (previous) previous.classList.remove('selected');
|
var target = view.querySelector('.thumbnail[data-page-number="' + pageNumber + '"]');
|
if (!target) return;
|
target.classList.add('selected');
|
|
var viewRect = view.getBoundingClientRect();
|
var thumbRect = target.getBoundingClientRect();
|
if (thumbRect.top < viewRect.top || thumbRect.bottom > viewRect.bottom) {
|
target.scrollIntoView({ block: 'nearest' });
|
}
|
}
|
|
// ── 重排(侧栏开合 / 窗口缩放会改变可用宽度) ──
|
var relayoutTimer = null;
|
function relayout() {
|
if (!ofdDoc) return;
|
clearTimeout(relayoutTimer);
|
relayoutTimer = setTimeout(function() {
|
var keep = currentPage;
|
layoutPages();
|
goToPage(keep, false);
|
}, RELAYOUT_DEBOUNCE_MS);
|
}
|
|
function bindResize() {
|
window.addEventListener('resize', relayout);
|
}
|
|
// ── 页面导航 ──
|
function goToPage(n, smooth) {
|
if (n < 1 || n > totalPages) return;
|
currentPage = n;
|
updateUI();
|
|
var target = document.querySelector('#viewer > [data-page="' + n + '"]');
|
if (target) {
|
target.scrollIntoView({ behavior: smooth === false ? 'auto' : 'smooth', block: 'start' });
|
}
|
}
|
|
function nextPage() { goToPage(currentPage + 1); }
|
function prevPage() { goToPage(currentPage - 1); }
|
function firstPage() { goToPage(1); }
|
function lastPage() { goToPage(totalPages); }
|
|
// ── 滚动时同步页码(页顶最贴近容器顶部的那页即当前页) ──
|
function bindScrollTracking() {
|
var container = document.getElementById('viewerContainer');
|
var ticking = false;
|
container.addEventListener('scroll', function() {
|
if (ticking) return;
|
ticking = true;
|
requestAnimationFrame(function() {
|
ticking = false;
|
syncCurrentPageFromScroll();
|
});
|
});
|
}
|
|
function syncCurrentPageFromScroll() {
|
var container = document.getElementById('viewerContainer');
|
var pages = document.getElementById('viewer').children;
|
if (!pages.length) return;
|
|
var containerTop = container.getBoundingClientRect().top;
|
var best = currentPage;
|
var bestDistance = Infinity;
|
for (var i = 0; i < pages.length; i++) {
|
var rect = pages[i].getBoundingClientRect();
|
if (rect.bottom <= containerTop) continue; // 已滚过
|
var distance = Math.abs(rect.top - containerTop);
|
if (distance < bestDistance) {
|
bestDistance = distance;
|
best = i + 1;
|
}
|
}
|
if (best !== currentPage) {
|
currentPage = best;
|
updateUI();
|
}
|
}
|
|
// ── 缩放 ──
|
function zoomIn() { setScale(Math.min(4.0, currentScale + 0.1)); }
|
function zoomOut() { setScale(Math.max(0.25, currentScale - 0.1)); }
|
|
function setScale(scale) {
|
scale = Math.round(scale * 100) / 100;
|
if (scale < 0.25) scale = 0.25;
|
if (scale > 4.0) scale = 4.0;
|
if (Math.abs(currentScale - scale) < 0.01) return;
|
currentScale = scale;
|
updateScaleSelect();
|
relayout();
|
}
|
|
function setScaleFromSelect() {
|
var val = document.getElementById('scaleSelect').value;
|
if (val === 'auto' || val === 'page-actual' || val === 'page-fit' || val === 'page-width') {
|
setScale(1.0);
|
} else {
|
setScale(parseFloat(val));
|
}
|
}
|
|
function updateScaleSelect() {
|
var sel = document.getElementById('scaleSelect');
|
var val = '' + currentScale;
|
var found = false;
|
for (var i = 0; i < sel.options.length; i++) {
|
if (sel.options[i].value === val) { sel.selectedIndex = i; found = true; break; }
|
}
|
if (!found) {
|
var customOpt = document.getElementById('customScaleOption');
|
if (customOpt) {
|
customOpt.value = val;
|
customOpt.textContent = Math.round(currentScale * 100) + '%';
|
customOpt.removeAttribute('hidden');
|
customOpt.removeAttribute('disabled');
|
sel.selectedIndex = Array.prototype.indexOf.call(sel.options, customOpt);
|
}
|
}
|
}
|
|
// ── 旋转 ──
|
function rotateCw() {
|
currentRotation = (currentRotation + 90) % 360;
|
applyRotation();
|
}
|
function rotateCcw() {
|
currentRotation = (currentRotation - 90) % 360;
|
if (currentRotation < 0) currentRotation += 360;
|
applyRotation();
|
}
|
function applyRotation() {
|
var viewer = document.getElementById('viewer');
|
var firstChild = viewer.firstElementChild;
|
if (firstChild) {
|
firstChild.style.transform = currentRotation !== 0 ? 'rotate(' + currentRotation + 'deg)' : '';
|
firstChild.style.transformOrigin = 'center center';
|
}
|
}
|
|
// ── 侧栏切换 ──
|
// viewer.css 用 `#outerContainer.sidebarOpen #sidebarContainer` 控制可见性,
|
// 只改 #sidebarContainer 自身的 class 不会让它显示出来
|
function toggleSidebar() {
|
var outer = document.getElementById('outerContainer');
|
var toggleBtn = document.getElementById('sidebarToggle');
|
var opened = outer.classList.toggle('sidebarOpen');
|
if (toggleBtn) {
|
toggleBtn.classList.toggle('toggled', opened);
|
toggleBtn.setAttribute('aria-expanded', String(opened));
|
}
|
if (opened) buildThumbnails(); // 从未打开过侧栏就不付缩略图的渲染成本
|
relayout(); // 侧栏占用 200px,页面宽度需重算
|
}
|
|
// ── UI 更新 ──
|
function updateUI() {
|
document.getElementById('pageNumber').value = currentPage;
|
document.getElementById('numPages').textContent = '/ ' + totalPages;
|
document.getElementById('pageNumber').max = totalPages;
|
setActiveThumbnail(currentPage);
|
}
|
|
// ── 加载状态 ──
|
function showLoading(show) {
|
var bar = document.getElementById('loadingBar');
|
if (!bar) return;
|
bar.style.display = show ? '' : 'none';
|
if (show) bar.classList.add('indeterminate');
|
}
|
|
// ratio < 0 表示服务端未给 Content-Length,退化为不确定进度条
|
function updateDownloadProgress(ratio) {
|
var bar = document.getElementById('loadingBar');
|
if (!bar) return;
|
if (ratio < 0) {
|
bar.classList.add('indeterminate');
|
return;
|
}
|
bar.classList.remove('indeterminate');
|
bar.style.setProperty('--progressBar-percent', Math.round(ratio * 100) + '%');
|
}
|
|
// ── 错误显示 ──
|
function showError(msg) {
|
var wrapper = document.getElementById('errorWrapper');
|
var message = document.getElementById('errorMessage');
|
if (wrapper && message) {
|
wrapper.removeAttribute('hidden');
|
wrapper.style.display = '';
|
message.textContent = msg;
|
}
|
}
|
function hideError() {
|
var wrapper = document.getElementById('errorWrapper');
|
if (wrapper) {
|
wrapper.setAttribute('hidden', 'true');
|
wrapper.style.display = 'none';
|
}
|
}
|
|
// ── 工具栏事件绑定 ──
|
function bindToolbarEvents() {
|
document.getElementById('previous').addEventListener('click', prevPage);
|
document.getElementById('next').addEventListener('click', nextPage);
|
document.getElementById('firstPage').addEventListener('click', firstPage);
|
document.getElementById('lastPage').addEventListener('click', lastPage);
|
document.getElementById('pageNumber').addEventListener('change', function() {
|
var n = parseInt(this.value);
|
if (n >= 1 && n <= totalPages) goToPage(n);
|
else this.value = currentPage;
|
});
|
|
document.getElementById('zoomIn').addEventListener('click', zoomIn);
|
document.getElementById('zoomOut').addEventListener('click', zoomOut);
|
document.getElementById('scaleSelect').addEventListener('change', setScaleFromSelect);
|
|
document.getElementById('sidebarToggle').addEventListener('click', toggleSidebar);
|
document.getElementById('pageRotateCw').addEventListener('click', rotateCw);
|
document.getElementById('pageRotateCcw').addEventListener('click', rotateCcw);
|
|
var secondaryToolbar = document.getElementById('secondaryToolbar');
|
document.getElementById('secondaryToolbarToggle').addEventListener('click', function() {
|
secondaryToolbar.classList.toggle('hidden');
|
this.classList.toggle('toggled');
|
});
|
|
document.getElementById('print').addEventListener('click', function() { window.print(); });
|
document.getElementById('secondaryPrint').addEventListener('click', function() { window.print(); });
|
document.getElementById('download').addEventListener('click', downloadAttach);
|
document.getElementById('secondaryDownload').addEventListener('click', downloadAttach);
|
document.getElementById('errorClose').addEventListener('click', hideError);
|
}
|
|
// ── 键盘快捷键 ──
|
function bindKeyboardEvents() {
|
document.addEventListener('keydown', function(e) {
|
// Ctrl+P 不经过 window.print(),浏览器会直接打印当前 DOM,必须接管
|
if ((e.ctrlKey || e.metaKey) && (e.key === 'p' || e.key === 'P')) {
|
e.preventDefault();
|
if (printPerm) window.print();
|
return;
|
}
|
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
|
switch(e.key) {
|
case 'ArrowRight': case 'ArrowDown': case 'PageDown': nextPage(); e.preventDefault(); break;
|
case 'ArrowLeft': case 'ArrowUp': case 'PageUp': prevPage(); e.preventDefault(); break;
|
case 'Home': firstPage(); e.preventDefault(); break;
|
case 'End': lastPage(); e.preventDefault(); break;
|
case '+': case '=': zoomIn(); e.preventDefault(); break;
|
case '-': zoomOut(); e.preventDefault(); break;
|
case '0': setScale(1.0); e.preventDefault(); break;
|
}
|
});
|
}
|
|
// ── 下载附件 ──
|
function downloadAttach() {
|
var form = document.createElement('form');
|
form.method = 'post';
|
form.action = 'general/downLoadAttach?attachId=' + attachId;
|
form.style.display = 'none';
|
document.body.appendChild(form);
|
form.submit();
|
document.body.removeChild(form);
|
}
|
|
// ── 打印:结构参照 pdfjs-newest/web/viewer.js 的 PDFPrintService ──
|
// 屏幕上的 #viewer 是懒渲染的(多数页还是 loading 占位),且被 overflow:auto 裁剪,
|
// 直接打印只会得到当前可见的那一页。所以另建一个 #printContainer,把每一页
|
// 按纸张物理尺寸重新渲染进去,viewer.css 的 @media print 负责隐藏正文、逐页分页。
|
// OFD 的 PhysicalBox 单位不可靠:扫描件写像素(2322x3454),发票写点(595.2x396.6),
|
// ofd.js 自身也只用它算相对缩放。因此推不出真实纸张尺寸,统一打到 A4,按宽高比选方向、
|
// 内容等比缩放居中(即通用的"适应页面"行为)。
|
var PRINT_DPI = 96; // 浏览器按 96dpi 把 CSS px 映射到物理长度
|
var MM_PER_INCH = 25.4;
|
var A4_SHORT_SIDE_MM = 210;
|
var A4_LONG_SIDE_MM = 297;
|
var nativePrint = window.print;
|
var printing = false;
|
var printPageStyle = null;
|
|
function millimetersToPrintPx(mm) {
|
return mm * PRINT_DPI / MM_PER_INCH;
|
}
|
|
// 容器隐藏时 clientWidth 为 0,减去留白会得到负数(且非零,|| 兜不住),必须显式判断
|
function screenPageWidthAt100() {
|
var container = document.getElementById('viewerContainer');
|
var width = container.clientWidth - VIEWER_HORIZONTAL_PADDING;
|
return width > 0 ? width : DEFAULT_SCREEN_WIDTH;
|
}
|
|
function buildPrintPages() {
|
var container = document.getElementById('printContainer');
|
container.textContent = '';
|
var baselineWidth = screenPageWidthAt100();
|
|
var firstBox = ofd.calPageBox(DEFAULT_SCREEN_WIDTH, ofdDoc.document, ofdDoc.pages[0]);
|
var landscape = firstBox.w > firstBox.h;
|
var sheetWidthMm = landscape ? A4_LONG_SIDE_MM : A4_SHORT_SIDE_MM;
|
var sheetHeightMm = landscape ? A4_SHORT_SIDE_MM : A4_LONG_SIDE_MM;
|
var sheetWidth = millimetersToPrintPx(sheetWidthMm);
|
var sheetHeight = millimetersToPrintPx(sheetHeightMm);
|
|
ofdDoc.pages.forEach(function(page, index) {
|
var box = ofd.calPageBox(sheetWidth + CAL_PAGE_BOX_INSET, ofdDoc.document, page);
|
var pageDiv = document.createElement('div');
|
pageDiv.className = 'ofd-page';
|
pageDiv.setAttribute('data-page', index + 1);
|
pageDiv.style.width = box.w + 'px';
|
pageDiv.style.height = box.h + 'px';
|
ofd.renderPage(pageDiv, page, ofdDoc.tpls, ofdDoc.fontResObj, ofdDoc.drawParamResObj, ofdDoc.multiMediaResObj);
|
|
var fit = Math.min(sheetWidth / box.w, sheetHeight / box.h);
|
addWatermarkTo(pageDiv, box.w * fit / baselineWidth);
|
|
// 外框承担布局尺寸(缩放后的大小),内部页面用 transform 缩放。
|
// 若让页面自身超出纸张再 transform,未缩放的布局盒会溢出、多打出空白页。
|
pageDiv.style.transform = 'scale(' + fit + ')';
|
pageDiv.style.transformOrigin = 'top left';
|
var frame = document.createElement('div');
|
frame.className = 'ofd-print-page';
|
frame.style.width = (box.w * fit) + 'px';
|
frame.style.height = (box.h * fit) + 'px';
|
frame.appendChild(pageDiv);
|
|
var wrapper = document.createElement('div');
|
wrapper.className = 'printedPage';
|
wrapper.appendChild(frame);
|
container.appendChild(wrapper);
|
});
|
|
applyPrintPageSize(sheetWidthMm, sheetHeightMm);
|
}
|
|
function applyPrintPageSize(widthMm, heightMm) {
|
removePrintPageSize();
|
printPageStyle = document.createElement('style');
|
printPageStyle.textContent = '@page { size: ' + widthMm + 'mm ' + heightMm + 'mm; margin: 0; }';
|
document.head.appendChild(printPageStyle);
|
}
|
|
function removePrintPageSize() {
|
if (printPageStyle && printPageStyle.parentNode) {
|
printPageStyle.parentNode.removeChild(printPageStyle);
|
}
|
printPageStyle = null;
|
}
|
|
// 图片是 Blob 异步解码的,必须等全部就绪才能交给浏览器打印,否则打出空白图
|
function waitForPrintImages() {
|
var images = document.querySelectorAll('#printContainer img');
|
var pending = [];
|
Array.prototype.forEach.call(images, function(img) {
|
if (img.complete && img.naturalWidth > 0) return;
|
pending.push(new Promise(function(resolve) {
|
img.onload = resolve;
|
img.onerror = resolve; // 单张图失败不应阻塞整份打印
|
}));
|
});
|
return Promise.all(pending);
|
}
|
|
function teardownPrint() {
|
if (!printing) return;
|
document.body.removeAttribute('data-pdfjsprinting');
|
document.getElementById('printContainer').textContent = '';
|
removePrintPageSize();
|
printing = false;
|
}
|
|
window.print = function() {
|
if (printing) {
|
console.warn('打印任务进行中,忽略重复请求');
|
return;
|
}
|
if (!ofdDoc) {
|
nativePrint.call(window);
|
return;
|
}
|
printing = true;
|
showLoading(true);
|
|
var ready;
|
try {
|
buildPrintPages();
|
ready = waitForPrintImages();
|
} catch (e) {
|
console.error('构建打印页失败:', e);
|
showLoading(false);
|
teardownPrint();
|
showError('打印准备失败:' + e.message);
|
return;
|
}
|
|
ready.then(function() {
|
showLoading(false);
|
document.body.setAttribute('data-pdfjsprinting', 'true');
|
nativePrint.call(window);
|
teardownPrint(); // 部分浏览器不触发 afterprint,这里兜底
|
});
|
};
|
|
window.addEventListener('afterprint', teardownPrint);
|
|
// ── 水印:每页一张 canvas,算法与 pdfjs-newest/web/viewer.js 保持一致 ──
|
var WATERMARK_TILE_SPACING_X_RATIO = 1.2; // 横向间距 / 文字宽度
|
var WATERMARK_TILE_SPACING_Y_RATIO = 3; // 纵向间距 / 文字高度
|
var WATERMARK_EDGE_INSET_RATIO = 0.1; // 贴边位置距页边 10%
|
var WATERMARK_SAFE_MARGIN = 10; // 旋转后不被页边裁掉的额外留白
|
|
// scale:页面相对 100% 显示尺寸的倍率。屏幕上取 currentScale,打印时取打印分辨率下的倍率
|
function addWatermarkTo(pageDiv, scale) {
|
if (!enableWatermark || !watermarkText) return;
|
|
var width = parseFloat(pageDiv.style.width);
|
var height = parseFloat(pageDiv.style.height);
|
if (!width || !height) return;
|
|
var canvas = document.createElement('canvas');
|
canvas.className = 'ofd-watermark';
|
canvas.width = width;
|
canvas.height = height;
|
|
var ctx = canvas.getContext('2d');
|
ctx.globalAlpha = watermarkTransparency;
|
// 字号随显示比例缩放,否则放大后水印相对页面越来越小
|
var fontSize = watermarkFontsize * scale;
|
ctx.font = fontSize + 'px Microsoft YaHei';
|
ctx.fillStyle = 'black';
|
ctx.textAlign = 'center';
|
ctx.textBaseline = 'middle';
|
|
if (watermarkPosition === 'tile') {
|
drawTiledWatermark(ctx, width, height, fontSize);
|
} else {
|
drawSingleWatermark(ctx, width, height, fontSize);
|
}
|
pageDiv.appendChild(canvas);
|
}
|
|
function drawWatermarkText(ctx, x, y) {
|
ctx.save();
|
ctx.translate(x, y);
|
ctx.rotate(watermarkAngle * Math.PI / 180);
|
ctx.fillText(watermarkText, 0, 0);
|
ctx.restore();
|
}
|
|
function drawTiledWatermark(ctx, width, height, fontSize) {
|
var spacingX = ctx.measureText(watermarkText).width * WATERMARK_TILE_SPACING_X_RATIO;
|
var spacingY = fontSize * WATERMARK_TILE_SPACING_Y_RATIO;
|
for (var x = -spacingX; x < width + spacingX; x += spacingX) {
|
for (var y = -spacingY; y < height + spacingY; y += spacingY) {
|
drawWatermarkText(ctx, x, y);
|
}
|
}
|
}
|
|
// 九宫格定位,watermarkPosition 为空时居中(与 SystemConfig 默认值一致)
|
function drawSingleWatermark(ctx, width, height, fontSize) {
|
var radians = watermarkAngle * Math.PI / 180;
|
var textWidth = ctx.measureText(watermarkText).width;
|
var rotatedWidth = Math.abs(textWidth * Math.cos(radians)) + Math.abs(fontSize * Math.sin(radians));
|
var rotatedHeight = Math.abs(textWidth * Math.sin(radians)) + Math.abs(fontSize * Math.cos(radians));
|
var safeMarginX = rotatedWidth / 2 + WATERMARK_SAFE_MARGIN;
|
var safeMarginY = rotatedHeight / 2 + WATERMARK_SAFE_MARGIN;
|
|
var left = Math.max(safeMarginX, width * WATERMARK_EDGE_INSET_RATIO);
|
var right = Math.min(width - safeMarginX, width * (1 - WATERMARK_EDGE_INSET_RATIO));
|
var top = Math.max(safeMarginY, height * WATERMARK_EDGE_INSET_RATIO);
|
var bottom = Math.min(height - safeMarginY, height * (1 - WATERMARK_EDGE_INSET_RATIO));
|
var centerX = width / 2;
|
var centerY = height / 2;
|
|
var coords = {
|
topLeft: [left, top],
|
topCenter: [centerX, top],
|
topRight: [right, top],
|
middleLeft: [left, centerY],
|
center: [centerX, centerY],
|
middleRight: [right, centerY],
|
bottomLeft: [left, bottom],
|
bottomCenter: [centerX, bottom],
|
bottomRight: [right, bottom]
|
};
|
var point = coords[watermarkPosition] || coords.center;
|
drawWatermarkText(ctx, point[0], point[1]);
|
}
|
</script>
|
</head>
|
|
<body tabindex="1">
|
<div id="outerContainer">
|
|
<!-- ═══════════ 左侧边栏(显隐由 #outerContainer.sidebarOpen 控制,见 viewer.css) ═══════════ -->
|
<div id="sidebarContainer">
|
<div id="toolbarSidebar">
|
<div id="toolbarSidebarLeft">
|
<span class="sidebarTitle">页面缩略图</span>
|
</div>
|
</div>
|
<div id="sidebarContent">
|
<div id="thumbnailView"></div>
|
</div>
|
</div>
|
|
<!-- ═══════════ 主区域 ═══════════ -->
|
<div id="mainContainer">
|
|
<!-- ── 辅助工具栏(右侧弹出菜单) ── -->
|
<div id="secondaryToolbar" class="secondaryToolbar hidden doorHangerRight">
|
<div id="secondaryToolbarButtonContainer">
|
<button id="secondaryPrint" class="secondaryToolbarButton visibleMediumView" title="打印"
|
tabindex="53">
|
<span>打印</span>
|
</button>
|
<button id="secondaryDownload" class="secondaryToolbarButton visibleMediumView" title="下载"
|
tabindex="54">
|
<span>下载</span>
|
</button>
|
|
<div class="horizontalToolbarSeparator"></div>
|
|
<button id="firstPage" class="secondaryToolbarButton" title="首页" tabindex="56">
|
<span>首页</span>
|
</button>
|
<button id="lastPage" class="secondaryToolbarButton" title="末页" tabindex="57">
|
<span>末页</span>
|
</button>
|
|
<div class="horizontalToolbarSeparator"></div>
|
|
<button id="pageRotateCw" class="secondaryToolbarButton" title="顺时针旋转" tabindex="58">
|
<span>顺时针旋转</span>
|
</button>
|
<button id="pageRotateCcw" class="secondaryToolbarButton" title="逆时针旋转" tabindex="59">
|
<span>逆时针旋转</span>
|
</button>
|
</div>
|
</div>
|
|
<!-- ── 主工具栏 ── -->
|
<div class="toolbar">
|
<div id="toolbarContainer">
|
<div id="toolbarViewer">
|
<div id="toolbarViewerLeft">
|
<button id="sidebarToggle" class="toolbarButton" title="切换侧栏" tabindex="11"
|
aria-expanded="false" aria-controls="sidebarContainer">
|
<span>侧栏</span>
|
</button>
|
<div class="toolbarButtonSpacer"></div>
|
<div class="splitToolbarButton hiddenSmallView">
|
<button class="toolbarButton" title="上一页" id="previous" tabindex="13">
|
<span>◀</span>
|
</button>
|
<div class="splitToolbarButtonSeparator"></div>
|
<button class="toolbarButton" title="下一页" id="next" tabindex="14">
|
<span>▶</span>
|
</button>
|
</div>
|
<input type="number" id="pageNumber" class="toolbarField" title="页码" value="1"
|
size="4" min="1" tabindex="15" autocomplete="off">
|
<span id="numPages" class="toolbarLabel">/ --</span>
|
</div>
|
<div id="toolbarViewerRight">
|
<button id="print" class="toolbarButton hiddenMediumView" title="打印" tabindex="33">
|
<span>打印</span>
|
</button>
|
<button id="download" class="toolbarButton hiddenMediumView" title="下载" tabindex="34">
|
<span>下载</span>
|
</button>
|
|
<div class="verticalToolbarSeparator hiddenSmallView"></div>
|
|
<button id="secondaryToolbarToggle" class="toolbarButton" title="工具" tabindex="48"
|
aria-expanded="false" aria-controls="secondaryToolbar">
|
<span>工具</span>
|
</button>
|
</div>
|
<div id="toolbarViewerMiddle">
|
<div class="splitToolbarButton">
|
<button id="zoomOut" class="toolbarButton" title="缩小" tabindex="21">
|
<span>−</span>
|
</button>
|
<div class="splitToolbarButtonSeparator"></div>
|
<button id="zoomIn" class="toolbarButton" title="放大" tabindex="22">
|
<span>+</span>
|
</button>
|
</div>
|
<span id="scaleSelectContainer" class="dropdownToolbarButton">
|
<select id="scaleSelect" title="缩放" tabindex="23">
|
<option value="0.5">50%</option>
|
<option value="0.75">75%</option>
|
<option value="1" selected>100%</option>
|
<option value="1.25">125%</option>
|
<option value="1.5">150%</option>
|
<option value="2">200%</option>
|
<option value="3">300%</option>
|
<option value="4">400%</option>
|
<option id="customScaleOption" value="custom" disabled hidden></option>
|
</select>
|
</span>
|
</div>
|
</div>
|
<div id="loadingBar">
|
<div class="progress">
|
<div class="glimmer"></div>
|
</div>
|
</div>
|
</div>
|
</div>
|
|
<!-- ── 文档渲染区 ── -->
|
<div id="viewerContainer" tabindex="0">
|
<div id="viewer" class="ofdViewer"></div>
|
</div>
|
|
<!-- ── 错误提示 ── -->
|
<div id="errorWrapper" hidden='true' style="display:none;">
|
<div id="errorMessageLeft">
|
<span id="errorMessage"></span>
|
</div>
|
<div id="errorMessageRight">
|
<button id="errorClose">关闭</button>
|
</div>
|
<div id="errorSpacer"></div>
|
<textarea id="errorMoreInfo" hidden='true' readonly="readonly"></textarea>
|
</div>
|
</div>
|
</div>
|
|
<!-- 打印专用容器:屏幕上隐藏,打印时由 viewer.css 显示并逐页分页 -->
|
<div id="printContainer"></div>
|
</body>
|
</html>
|