瑞利声电固定资产管理系统
py
2026-10-13 70a8fe4fe3bf983377cf14bff142d8bb436fa041
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
<%@ 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>