-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
1394 lines (1212 loc) · 41.6 KB
/
content.js
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
// 创建浮动按钮和菜单
function createFloatingButton() {
const button = document.createElement('button');
button.className = 'web2pdf-floating-button';
button.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
<path d="M0 0h24v24H0z" fill="none"/>
<path fill="currentColor" d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5v3zm4-3H19v1h1.5V11H19v2h-1.5V7h3v1.5zM9 9.5h1v-1H9v1zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm10 5.5h1v-3h-1v3z"/>
</svg>
`;
// 从存储中获取保存的位置
chrome.storage.local.get(['buttonPosition'], function(result) {
if (result.buttonPosition) {
button.style.left = result.buttonPosition.left;
button.style.top = result.buttonPosition.top;
} else {
// 默认位置在左下角
button.style.left = '20px';
button.style.bottom = '20px';
}
});
// 添加拖动功能
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
button.addEventListener('mousedown', function(e) {
if (e.target.closest('.web2pdf-menu')) return;
isDragging = true;
button.style.transition = 'none';
const rect = button.getBoundingClientRect();
initialX = e.clientX - rect.left;
initialY = e.clientY - rect.top;
button.classList.add('dragging');
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
const buttonRect = button.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// 优化边界处理逻辑
currentX = Math.max(0, Math.min(currentX, viewportWidth - buttonRect.width));
currentY = Math.max(0, Math.min(currentY, viewportHeight - buttonRect.height));
button.style.left = currentX + 'px';
button.style.top = currentY + 'px';
button.style.bottom = 'auto';
});
document.addEventListener('mouseup', function() {
if (!isDragging) return;
isDragging = false;
button.style.transition = 'background-color 0.2s';
button.classList.remove('dragging');
// 保存新位置到 storage,这样主页面的按钮也会使用这个位置
chrome.storage.local.set({
buttonPosition: {
left: button.style.left,
top: button.style.top
}
});
});
button.addEventListener('click', showMenu);
document.body.appendChild(button);
}
// 创建菜单
async function createMenu() {
const menu = document.createElement('div');
menu.className = 'web2pdf-menu';
menu.innerHTML = `
<div class="menu-item" id="readMode">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
</svg>
${await t('readMode')}
</div>
<div class="menu-item" id="printPDF">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/>
</svg>
${await t('printPDF')}
</div>
<div class="menu-item" id="switchLang">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
${await t('switchLang')}
</div>
`;
document.body.appendChild(menu);
// 添加事件监听
document.getElementById('readMode').addEventListener('click', toggleReadMode);
document.getElementById('printPDF').addEventListener('click', printToPDF);
document.getElementById('switchLang').addEventListener('click', async function() {
const currentLang = await getUserLanguage();
const newLang = currentLang === 'zh' ? 'en' : 'zh';
await setUserLanguage(newLang);
// 重新创建菜单以更新语言
const oldMenu = document.querySelector('.web2pdf-menu');
if (oldMenu) oldMenu.remove();
createMenu();
});
}
// 显示/隐藏菜单
function showMenu(event) {
event.stopPropagation();
const button = event.currentTarget;
const menu = document.querySelector('.web2pdf-menu');
const buttonRect = button.getBoundingClientRect();
// 根据按钮位置调整菜单位置
if (buttonRect.left < window.innerWidth / 2) {
// 按钮在左半边,菜单显示在按钮右边
menu.style.left = (buttonRect.right + 10) + 'px';
menu.style.right = 'auto';
} else {
// 按钮在右半边,菜单显示在按钮左边
menu.style.right = (window.innerWidth - buttonRect.left + 10) + 'px';
menu.style.left = 'auto';
}
// 垂直位置调整
const menuHeight = menu.offsetHeight || 100; // 预估高度
if (buttonRect.top + menuHeight > window.innerHeight) {
// 如果菜单会超出底部,就显示在按钮上方
menu.style.bottom = (window.innerHeight - buttonRect.top + 10) + 'px';
menu.style.top = 'auto';
} else {
// 否则显示在按钮下方
menu.style.top = buttonRect.top + 'px';
menu.style.bottom = 'auto';
}
menu.classList.toggle('show');
// 点击其他地方关闭菜单
document.addEventListener('click', function closeMenu(e) {
if (!menu.contains(e.target) && !e.target.closest('.web2pdf-floating-button')) {
menu.classList.remove('show');
document.removeEventListener('click', closeMenu);
}
});
}
// 切换阅读模式
async function toggleReadMode() {
const existingReader = document.querySelector('.web2pdf-reader-mode');
if (existingReader) {
existingReader.remove();
document.body.style.overflow = '';
return;
}
// 添加加载提示
const loadingTip = document.createElement('div');
loadingTip.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 20px;
border-radius: 10px;
z-index: 100000;
`;
loadingTip.textContent = t('loading');
document.body.appendChild(loadingTip);
try {
const content = extractMainContent();
const tempContainer = document.createElement('div');
tempContainer.innerHTML = content;
// 预加载图片,传入 loadingTip 参数
await preloadImages(tempContainer, loadingTip);
// 创建阅读模式容器
const readerMode = document.createElement('div');
readerMode.className = 'web2pdf-reader-mode';
readerMode.innerHTML = tempContainer.innerHTML;
// 添加关闭按钮
const closeButton = document.createElement('button');
closeButton.className = 'web2pdf-close-button';
closeButton.innerHTML = `
<svg viewBox="0 0 24 24" width="24" height="24">
<path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
</svg>
<span>${await t('close')}</span>
`;
closeButton.addEventListener('click', () => {
readerMode.remove();
document.body.style.overflow = '';
// 重新创建浮动按钮和菜单
createFloatingButton();
createMenu();
});
readerMode.appendChild(closeButton);
// 添加 ESC 快捷键支持
document.addEventListener('keydown', function escKeyHandler(e) {
if (e.key === 'Escape') {
readerMode.remove();
document.body.style.overflow = '';
// 重新创建浮动按钮和菜单
createFloatingButton();
createMenu();
document.removeEventListener('keydown', escKeyHandler);
}
});
document.body.appendChild(readerMode);
document.body.style.overflow = 'hidden';
document.querySelector('.web2pdf-menu')?.classList.remove('show');
// 获取原始按钮的位置
const originalButton = document.querySelector('.web2pdf-floating-button');
const originalMenu = document.querySelector('.web2pdf-menu');
const buttonPosition = originalButton ? {
left: originalButton.style.left,
top: originalButton.style.top,
bottom: originalButton.style.bottom
} : null;
if (originalButton) originalButton.remove();
if (originalMenu) originalMenu.remove();
// 在阅读模式中创建新的浮动按钮,使用相同的位置
const button = document.createElement('button');
button.className = 'web2pdf-floating-button';
button.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
<path d="M0 0h24v24H0z" fill="none"/>
<path fill="currentColor" d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5v3zm4-3H19v1h1.5V11H19v2h-1.5V7h3v1.5zM9 9.5h1v-1H9v1zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm10 5.5h1v-3h-1v3z"/>
</svg>
`;
// 应用保存的位置或使用默认位置
chrome.storage.local.get(['buttonPosition'], function(result) {
if (result.buttonPosition) {
button.style.left = result.buttonPosition.left;
button.style.top = result.buttonPosition.top;
} else if (buttonPosition) {
// 使用原始按钮的位置
button.style.left = buttonPosition.left;
button.style.top = buttonPosition.top;
button.style.bottom = buttonPosition.bottom;
} else {
// 默认位置在左下角
button.style.left = '20px';
button.style.bottom = '20px';
}
});
// 添加拖动功能
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
button.addEventListener('mousedown', function(e) {
if (e.target.closest('.web2pdf-menu')) return;
isDragging = true;
button.style.transition = 'none';
const rect = button.getBoundingClientRect();
initialX = e.clientX - rect.left;
initialY = e.clientY - rect.top;
button.classList.add('dragging');
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
const buttonRect = button.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
currentX = Math.max(0, Math.min(currentX, viewportWidth - buttonRect.width));
currentY = Math.max(0, Math.min(currentY, viewportHeight - buttonRect.height));
button.style.left = currentX + 'px';
button.style.top = currentY + 'px';
button.style.bottom = 'auto';
});
document.addEventListener('mouseup', function() {
if (!isDragging) return;
isDragging = false;
button.style.transition = 'background-color 0.2s';
button.classList.remove('dragging');
// 保存新位置到 storage,这样主页面的按钮也会使用这个位置
chrome.storage.local.set({
buttonPosition: {
left: button.style.left,
top: button.style.top
}
});
});
button.addEventListener('click', showMenu);
readerMode.appendChild(button);
// 在阅读模式中创建新的菜单
const menu = document.createElement('div');
menu.className = 'web2pdf-menu';
menu.innerHTML = `
<div class="menu-item" id="toggleEdit">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</svg>
${await t('editMode')}
</div>
<div class="menu-item" id="printPDF">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/>
</svg>
${await t('printPDF')}
</div>
<div class="menu-item" id="switchLang">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
${await t('switchLang')}
</div>
`;
readerMode.appendChild(menu);
// 为菜单项添加事件监听
menu.querySelector('#toggleEdit').addEventListener('click', () => {
toggleEditMode(readerMode);
menu.classList.remove('show');
});
menu.querySelector('#printPDF').addEventListener('click', () => {
printToPDF();
menu.classList.remove('show');
});
menu.querySelector('#switchLang').addEventListener('click', async function() {
const currentLang = await getUserLanguage();
const newLang = currentLang === 'zh' ? 'en' : 'zh';
await setUserLanguage(newLang);
// 重新创建菜单以更新语言
const oldMenu = readerMode.querySelector('.web2pdf-menu');
if (oldMenu) oldMenu.remove();
await createReaderModeMenu(readerMode);
});
// 显示成功提示
loadingTip.style.background = 'rgba(76, 175, 80, 0.9)';
loadingTip.textContent = await t('loadComplete');
setTimeout(() => {
loadingTip.remove();
// 自动开启编辑模式
toggleEditMode(readerMode);
}, 2000);
} catch (error) {
console.error('Error loading content:', error);
loadingTip.style.background = 'rgba(244, 67, 54, 0.9)';
loadingTip.textContent = t('loadFailed');
setTimeout(() => {
loadingTip.remove();
}, 2000);
}
}
// 添加一个新函数来创建阅读模式的菜单
async function createReaderModeMenu(readerMode) {
const menu = document.createElement('div');
menu.className = 'web2pdf-menu';
menu.innerHTML = `
<div class="menu-item" id="toggleEdit">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</svg>
${await t('editMode')}
</div>
<div class="menu-item" id="printPDF">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/>
</svg>
${await t('printPDF')}
</div>
<div class="menu-item" id="switchLang">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
${await t('switchLang')}
</div>
`;
readerMode.appendChild(menu);
// 添加事件监听
menu.querySelector('#toggleEdit').addEventListener('click', () => {
toggleEditMode(readerMode);
menu.classList.remove('show');
});
menu.querySelector('#printPDF').addEventListener('click', () => {
printToPDF();
menu.classList.remove('show');
});
menu.querySelector('#switchLang').addEventListener('click', async function() {
const currentLang = await getUserLanguage();
const newLang = currentLang === 'zh' ? 'en' : 'zh';
await setUserLanguage(newLang);
// 重新创建菜单以更新语言
const oldMenu = readerMode.querySelector('.web2pdf-menu');
if (oldMenu) oldMenu.remove();
await createReaderModeMenu(readerMode);
});
return menu;
}
// 添加预加载图片的函数
async function preloadImages(container, loadingTip) {
const images = container.getElementsByTagName('img');
const totalImages = images.length;
const imageLoadPromises = [];
let loadedCount = 0;
// 如果没有图片需要加载
if (totalImages === 0) {
if (loadingTip) {
loadingTip.innerHTML = '没有找到需要加载的图片';
await new Promise(resolve => setTimeout(resolve, 1000));
}
return;
}
// 创建进度条容器
if (loadingTip) {
loadingTip.innerHTML = `
<div style="text-align: center;">
<div>正在加载图片 (0/${totalImages})</div>
<div class="progress-bar" style="
width: 200px;
height: 6px;
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
margin: 10px auto;
overflow: hidden;
">
<div class="progress" style="
height: 100%;
width: 0%;
background: #4CAF50;
transition: width 0.3s ease;
"></div>
</div>
<div class="loading-details" style="
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
margin-top: 5px;
">准备加载...</div>
</div>
`;
}
// 处理所有图片
Array.from(images).forEach((img, index) => {
// 处理懒加载图片
const originalSrc = img.getAttribute('data-src') ||
img.getAttribute('data-original') ||
img.getAttribute('data-lazy-src') ||
img.getAttribute('data-lazy-loaded') ||
img.getAttribute('data-url') ||
img.src;
if (originalSrc) {
// 创建一个加载Promise
const loadPromise = new Promise((resolve) => {
const tempImg = new Image();
tempImg.onload = () => {
loadedCount++;
if (loadingTip) {
// 更新加载进度
const progress = Math.round((loadedCount / totalImages) * 100);
const progressBar = loadingTip.querySelector('.progress');
const loadingDetails = loadingTip.querySelector('.loading-details');
loadingTip.querySelector('div').textContent =
`正在加载图片 (${loadedCount}/${totalImages})`;
if (progressBar) {
progressBar.style.width = `${progress}%`;
}
if (loadingDetails) {
loadingDetails.textContent = `正在加载: ${originalSrc.substring(0, 50)}...`;
}
}
img.src = originalSrc; // 设置实际图片源
img.removeAttribute('data-src');
img.removeAttribute('data-original');
img.removeAttribute('data-lazy-src');
img.removeAttribute('data-lazy-loaded');
img.removeAttribute('data-url');
img.removeAttribute('loading'); // 移除懒加载属性
img.classList.remove('lazyload', 'lazy'); // 移除懒加载类
resolve();
};
tempImg.onerror = () => {
loadedCount++;
if (loadingTip) {
// 更新加载进度,即使加载失败
const progress = Math.round((loadedCount / totalImages) * 100);
const progressBar = loadingTip.querySelector('.progress');
const loadingDetails = loadingTip.querySelector('.loading-details');
loadingTip.querySelector('div').textContent =
`正在加载图片 (${loadedCount}/${totalImages})`;
if (progressBar) {
progressBar.style.width = `${progress}%`;
}
if (loadingDetails) {
loadingDetails.textContent = `加载失败: ${originalSrc.substring(0, 50)}...`;
}
}
console.warn('Failed to load image:', originalSrc);
resolve();
};
// 开始加载图片
tempImg.src = originalSrc;
});
imageLoadPromises.push(loadPromise);
}
});
// 等待所有图片加载完成
await Promise.all(imageLoadPromises);
// 显示加载完成信息
if (loadingTip) {
loadingTip.innerHTML = `
<div style="text-align: center;">
<div>图片加载完成 (${loadedCount}/${totalImages})</div>
<div class="progress-bar" style="
width: 200px;
height: 6px;
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
margin: 10px auto;
overflow: hidden;
">
<div class="progress" style="
height: 100%;
width: 100%;
background: #4CAF50;
"></div>
</div>
<div class="loading-details" style="
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
margin-top: 5px;
">所有图片加载完成</div>
</div>
`;
// 等待一会儿再消失,让用户看到完成状态
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
// 添加 A4 尺寸计算和内容分页函数
function calculateA4Pages(container) {
// A4 尺寸(以像素为单位,假设 96 DPI)
// A4 纸张尺寸为 210mm x 297mm
const A4_WIDTH_PX = 794; // 210mm = 794px
const A4_HEIGHT_PX = 1123; // 297mm = 1123px
const MARGIN = 40; // 页边距
const EFFECTIVE_HEIGHT = A4_HEIGHT_PX - (MARGIN * 2);
// 创建一个临时容器来计算布局
const tempDiv = document.createElement('div');
tempDiv.style.cssText = `
position: absolute;
top: -9999px;
left: -9999px;
width: ${A4_WIDTH_PX - (MARGIN * 2)}px;
visibility: hidden;
`;
document.body.appendChild(tempDiv);
// 克隆内容到临时容器
const contentClone = container.cloneNode(true);
tempDiv.appendChild(contentClone);
// 处理所有图片,使其等宽
const images = tempDiv.getElementsByTagName('img');
Array.from(images).forEach(img => {
img.style.width = '100%';
img.style.height = 'auto';
// 确保图片容器也是等宽的
if (img.parentElement.classList.contains('img-container')) {
img.parentElement.style.width = '100%';
}
});
// 存储分页后的内容
const pages = [];
let currentPage = document.createElement('div');
let currentHeight = 0;
// 遍历所有子元素
Array.from(contentClone.children).forEach(element => {
const elementHeight = element.offsetHeight;
const isImage = element.tagName.toLowerCase() === 'img' ||
element.querySelector('img') !== null;
// 如果当前元素是图片或包含图片,且会导致超出页面高度
if (isImage && currentHeight + elementHeight > EFFECTIVE_HEIGHT) {
// 将当前页添加到页面集合中
if (currentPage.children.length > 0) {
pages.push(currentPage);
}
// 创建新页面,并将图片放在新页面的开始
currentPage = document.createElement('div');
currentPage.appendChild(element.cloneNode(true));
currentHeight = elementHeight;
}
// 如果是普通元素,且会导致超出页面高度
else if (currentHeight + elementHeight > EFFECTIVE_HEIGHT) {
// 将当前页添加到页面集合中
pages.push(currentPage);
// 创建新页面
currentPage = document.createElement('div');
currentPage.appendChild(element.cloneNode(true));
currentHeight = elementHeight;
}
// 如果不会超出页面高度
else {
currentPage.appendChild(element.cloneNode(true));
currentHeight += elementHeight;
}
});
// 添加最后一页
if (currentPage.children.length > 0) {
pages.push(currentPage);
}
// 清理临时元素
document.body.removeChild(tempDiv);
return pages;
}
// 修改 printToPDF 函数
async function printToPDF() {
// 创建一个临时容器来存放打印内容
const tempContainer = document.createElement('div');
if (document.querySelector('.web2pdf-reader-mode')) {
// 如果在阅读模式下,复制阅读模式的内容
const readerContent = document.querySelector('.web2pdf-reader-mode').cloneNode(true);
// 清理所有UI元素
const elementsToRemove = [
'.web2pdf-floating-button',
'.web2pdf-menu',
'.reader-close-button',
'.editing-toolbar',
'.element-controls',
'.image-resizer',
'button'
];
elementsToRemove.forEach(selector => {
readerContent.querySelectorAll(selector).forEach(el => el.remove());
});
// 只保留主要内容
const mainContent = readerContent.querySelector('.web2pdf-content');
if (mainContent) {
// 移除所有编辑相关的属性和类
mainContent.querySelectorAll('*').forEach(el => {
el.removeAttribute('contenteditable');
el.classList.remove('editing');
if (el.style.position === 'relative') {
el.style.position = '';
}
});
// 处理图片包装器
mainContent.querySelectorAll('.image-wrapper').forEach(wrapper => {
const img = wrapper.querySelector('img');
if (img) {
const imgContainer = document.createElement('div');
imgContainer.className = 'img-container';
wrapper.parentNode.insertBefore(imgContainer, wrapper);
imgContainer.appendChild(img);
wrapper.remove();
}
});
tempContainer.appendChild(mainContent);
}
} else {
// 如果不在阅读模式下,使用提取的内容
tempContainer.innerHTML = extractMainContent();
// 为所有图片添加包装容器
tempContainer.querySelectorAll('img').forEach(img => {
const imgContainer = document.createElement('div');
imgContainer.className = 'img-container';
img.parentNode.insertBefore(imgContainer, img);
imgContainer.appendChild(img);
});
}
// 添加加载提示
const loadingTip = document.createElement('div');
loadingTip.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 20px;
border-radius: 10px;
z-index: 100000;
`;
loadingTip.textContent = '正在加载图片,请稍候...';
document.body.appendChild(loadingTip);
try {
// 预加载所有图片
await preloadImages(tempContainer);
// 计算分页
const pages = calculateA4Pages(tempContainer);
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<html>
<head>
<title>${document.title}</title>
<style>
@page {
size: A4;
margin: 40px;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
}
.page {
width: 21cm;
height: 29.7cm;
padding: 40px;
box-sizing: border-box;
margin: 0 auto;
background: white;
}
img {
max-width: 100%;
height: auto;
display: block;
margin: 10px auto;
}
.img-container {
width: 100%;
margin: 20px 0;
}
h1, h2, h3, h4, h5, h6 {
margin: 1em 0 0.5em;
}
p {
margin: 0.5em 0;
}
@media print {
.page {
page-break-after: always;
margin: 0;
height: auto;
}
.page:last-child {
page-break-after: avoid;
}
}
</style>
</head>
<body>
${pages.map(page => `
<div class="page">
${page.innerHTML}
</div>
`).join('')}
</body>
</html>
`);
printWindow.document.close();
// 等待一段时间确保图片完全加载和布局完成
setTimeout(() => {
printWindow.print();
loadingTip.remove();
}, 2000);
} catch (error) {
console.error('Error during PDF generation:', error);
alert('生成PDF时出错,请重试');
} finally {
loadingTip.remove();
}
}
// 添加清理打印内容的函数
function cleanupForPrint(element) {
// 移除所有UI相关元素
const removeSelectors = [
'.web2pdf-floating-button',
'.web2pdf-menu',
'.reader-close-button',
'.editing-toolbar',
'button',
'[contenteditable]'
];
removeSelectors.forEach(selector => {
element.querySelectorAll(selector).forEach(el => el.remove());
});
// 移除编辑相关的属性和类
element.querySelectorAll('*').forEach(el => {
el.removeAttribute('contenteditable');
el.classList.remove('editing');
});
// 返回清理后的HTML
return element.innerHTML;
}
// 添加样式
const style = document.createElement('style');
style.textContent = `
.web2pdf-floating-button {
position: fixed;
z-index: 10000;
width: 48px;
height: 48px;
border-radius: 24px;
background: white;
border: none;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
cursor: move;
display: flex;
align-items: center;
justify-content: center;
transition: background-color 0.2s;
user-select: none;
touch-action: none;
color: #333;
}
.web2pdf-floating-button:hover {
background: #f5f5f5;
}
.web2pdf-floating-button.dragging {
opacity: 0.8;
cursor: grabbing;
}
.web2pdf-floating-button svg {
pointer-events: none;
fill: currentColor;
}
.web2pdf-menu {
position: fixed;
background: white;
border-radius: 4px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: none;
z-index: 10001;
min-width: 180px;
max-width: 250px;
}
.web2pdf-menu.show {
display: block;
}
.menu-item {
padding: 10px 15px;
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
color: #333;
transition: background-color 0.2s;
white-space: nowrap;
}
.menu-item:hover {
background-color: #f5f5f5;
}
.menu-item svg {
flex-shrink: 0;
fill: currentColor;
}
.web2pdf-reader-mode {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: white;
z-index: 100000;
padding: 40px;
overflow-y: auto;
line-height: 1.6;
font-family: Arial, sans-serif;
}
.web2pdf-reader-mode .content {
max-width: 800px;
margin: 0 auto;
}
.reader-close-button {
position: fixed;
top: 20px;
right: 20px;
width: 40px;
height: 40px;
border-radius: 20px;
border: none;
background: #f0f0f0;
cursor: pointer;
font-size: 24px;
display: flex;
align-items: center;
justify-content: center;
z-index: 100001;
}
.reader-close-button:hover {
background: #e0e0e0;
}
.web2pdf-context-menu {
position: fixed;
background: white;
border-radius: 4px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: none;
z-index: 10000;
min-width: 150px;