-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2386 lines (2007 loc) · 90.8 KB
/
Copy pathapp.py
File metadata and controls
2386 lines (2007 loc) · 90.8 KB
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
#!/usr/bin/env pythonw
# -*- coding: utf-8 -*-
import sys
import os
import logging
import base64
import traceback
import ctypes
import tempfile
import subprocess
import re
import html
from pathlib import Path
from typing import Dict, List, Optional
import xml.etree.ElementTree as ET
# ======= 依赖(尽量最少) =======
try:
import win32com.client # type: ignore
import comtypes.client # type: ignore
COM_AVAILABLE = True
except Exception:
COM_AVAILABLE = False
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget,
QPushButton, QLabel, QTreeWidget, QTreeWidgetItem, QProgressBar,
QTextEdit, QGroupBox, QCheckBox, QFileDialog, QMessageBox, QSplitter,
QTreeWidgetItemIterator
)
from PyQt5.QtCore import Qt, QTimer, QDateTime, QThread, pyqtSignal, QCoreApplication
# Word/PDF 依赖
from docx import Document
from docx.shared import Inches, Cm, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.shared import OxmlElement, qn
from docx.opc.constants import RELATIONSHIP_TYPE as RT
from docx.enum.section import WD_ORIENT, WD_SECTION
from reportlab.lib.pagesizes import A4
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Image as RLImage,
Table, TableStyle, KeepInFrame, PageBreak
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
# ======= 工具函数 =======
def is_admin() -> bool:
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except Exception:
return False
def check_onenote_process() -> bool:
try:
r = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq ONENOTE.EXE'], capture_output=True, text=True)
return 'ONENOTE.EXE' in r.stdout
except Exception:
return False
# ======= 一些轻量 UI 组件 =======
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QPainter, QPen, QColor
class LoadingIndicator(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(26, 26)
self.angle = 0
self._timer = QTimer(self)
self._timer.timeout.connect(self._tick)
self._timer.setInterval(60)
self.hide()
def start(self, show_text=True):
self._timer.start()
self.show()
def stop(self):
self._timer.stop()
self.hide()
def _tick(self):
self.angle = (self.angle + 10) % 360
self.update()
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
pen = QPen(QColor(70, 130, 180))
pen.setWidth(3)
p.setPen(pen)
r = 10
p.translate(self.rect().center())
p.rotate(self.angle)
p.drawArc(-r, -r, 2*r, 2*r, 0, 120*16)
class StatusIndicator(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self._label = QLabel('', self)
self._spinner = LoadingIndicator(self)
layout = QHBoxLayout(self)
layout.setContentsMargins(6, 6, 6, 6)
layout.addWidget(self._spinner)
layout.addWidget(self._label)
self.hide()
def show_loading(self, text: str):
if self._label.text() != text: # 只在文本变化时更新
self._label.setText(text)
if not self._spinner._timer.isActive():
self._spinner.start()
if not self.isVisible():
self.show()
# 不调用processEvents,避免阻塞
def hide_loading(self):
self._spinner.stop()
self.hide()
# ======= OneNote API(COM优先,PowerShell回退) =======
class OneNoteAPI:
def __init__(self):
self.app = None
self.temp_dir = tempfile.mkdtemp(prefix='onenote_app_')
self.logger = logging.getLogger('OneNoteAPI')
def initialize(self) -> bool:
try:
if not COM_AVAILABLE:
raise RuntimeError('COM not available')
admin = is_admin(); running = check_onenote_process()
self.logger.info(f'权限: admin={admin}, running={running}')
# 尝试三种COM
try:
self.app = win32com.client.gencache.EnsureDispatch('OneNote.Application')
_ = self.app.GetHierarchy('', 1)
return True
except Exception as e:
self.logger.warning(f'gencache失败: {e}')
try:
self.app = win32com.client.Dispatch('OneNote.Application')
_ = self.app.GetHierarchy('', 1)
return True
except Exception as e:
self.logger.warning(f'Dispatch失败: {e}')
try:
self.app = comtypes.client.CreateObject('OneNote.Application')
_ = self.app.GetHierarchy('', 1)
return True
except Exception as e:
self.logger.warning(f'comtypes失败: {e}')
# 退到仅PS
self.app = None
return True
except Exception as e:
self.logger.error(f'初始化失败: {e}')
return False
def _ps(self, script: str) -> str:
f = Path(self.temp_dir) / 'tmp.ps1'
f.write_text(script, encoding='utf-8')
r = subprocess.run(['powershell', '-ExecutionPolicy', 'Bypass', '-File', str(f)], capture_output=True, text=True, encoding='utf-8', errors='replace')
return (r.stdout or '')
def _get_hierarchy_ps(self, obj_id: str, scope: int) -> str:
obj = obj_id.replace('"','""') if obj_id else ''
sc = scope
script = f"""
[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
try {{
$o=New-Object -ComObject OneNote.Application
$x=""
$o.GetHierarchy("{obj}",{sc},[ref]$x)
Write-Output "SUCCESS:$x"
}} catch {{ Write-Output "ERROR:$($_.Exception.Message)" }}
"""
out = self._ps(script).strip()
if out.startswith('SUCCESS:'): return out[8:]
return ''
def _get_page_ps(self, page_id: str) -> str:
pid = page_id.replace('"','""')
script = f"""
[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
try {{
$o=New-Object -ComObject OneNote.Application
$x=""
$o.GetPageContent("{pid}",[ref]$x,7)
Write-Output "SUCCESS:$x"
}} catch {{ Write-Output "ERROR:$($_.Exception.Message)" }}
"""
out = self._ps(script).strip()
if out.startswith('SUCCESS:'): return out[8:]
return ''
def get_notebooks(self) -> Dict:
"""获取笔记本列表,优化版本"""
xml = ''
try:
if self.app:
try:
# COM调用可能很慢,但在子线程中执行,不会阻塞UI
xml = self.app.GetHierarchy('', 4)
except Exception:
pass
if not xml:
xml = self._get_hierarchy_ps('', 4)
except Exception:
xml=''
if not xml:
return {}
# 解析XML - 优化版本
try:
root = ET.fromstring(xml)
except Exception:
return {}
def findall_local(p, name):
return [e for e in p.iter() if (isinstance(e.tag,str) and (e.tag.endswith('}'+name) or e.tag==name or e.tag.split('}')[-1]==name))]
notebooks={}
for nb in findall_local(root, 'Notebook'):
nb_id = nb.get('ID')
nb_name = nb.get('name')
if not nb_id or not nb_name:
continue
sections={}
for sec in findall_local(nb,'Section'):
sid = sec.get('ID')
sname = sec.get('name')
if not sid or not sname:
continue
pages={}
for pg in findall_local(sec,'Page'):
pid = pg.get('ID')
pname = pg.get('name')
if pid and pname:
pages[pid] = {'id':pid, 'name':pname}
sections[sid] = {'id':sid, 'name':sname, 'pages':pages}
notebooks[nb_id] = {'id':nb_id, 'name':nb_name, 'sections':sections}
return notebooks
def get_page_content(self, page_id: str) -> str:
if self.app:
try:
c = self.app.GetPageContent(page_id, 7)
if c and c.strip(): return c
except Exception:
pass
try:
x=''; self.app.GetPageContent(page_id, x, 7)
if x and x.strip(): return x
except Exception:
pass
return self._get_page_ps(page_id)
# ======= 解析器(Word / PDF) =======
class OneNoteContentParser:
def __init__(self):
self.logger = logging.getLogger('Parser')
self.temp_files: List[str] = []
self._setup_chinese_fonts()
def _setup_chinese_fonts(self):
"""设置中文字体支持"""
try:
# 尝试注册系统中文字体
chinese_fonts = [
('SimSun', 'C:/Windows/Fonts/simsun.ttc'),
('SimHei', 'C:/Windows/Fonts/simhei.ttf'),
('Microsoft YaHei', 'C:/Windows/Fonts/msyh.ttc'),
('PingFang SC', 'C:/Windows/Fonts/PingFang.ttc'),
]
self.chinese_font = None
for font_name, font_path in chinese_fonts:
if os.path.exists(font_path):
try:
pdfmetrics.registerFont(TTFont(font_name, font_path))
self.chinese_font = font_name
self.logger.info(f"成功注册中文字体: {font_name}")
break
except Exception as e:
self.logger.debug(f"注册字体{font_name}失败: {e}")
continue
if not self.chinese_font:
self.chinese_font = 'Helvetica' # 回退到默认字体
self.logger.warning("未找到中文字体,使用默认字体")
except Exception as e:
self.chinese_font = 'Helvetica'
self.logger.error(f"字体设置失败: {e}")
def cleanup_temp_files(self):
"""清理临时文件"""
for temp_file in self.temp_files:
try:
if os.path.exists(temp_file):
os.remove(temp_file)
except Exception as e:
self.logger.debug(f"清理临时文件失败: {e}")
self.temp_files.clear()
# --- 工具:命名空间无关查找 ---
def _findall_local(self, parent: ET.Element, local_name: str) -> List[ET.Element]:
out=[]
for el in parent.iter():
tag = el.tag
if isinstance(tag,str) and (tag.endswith('}'+local_name) or tag==local_name or tag.split('}')[-1]==local_name):
if el is not parent or tag.split('}')[-1] != local_name:
out.append(el)
return out
# --- Word ---
def parse_page_to_docx(self, xml: str, page_name: str, out_path: str,
include_images=True, include_attachments=True,
embed_attachments=False,
attachments_output_dir: Optional[Path]=None) -> bool:
try:
root = ET.fromstring(xml)
doc = Document()
doc.add_heading(page_name, level=1).alignment = WD_ALIGN_PARAGRAPH.CENTER
self._write_text_word(root, doc)
if include_images: self._images_word(root, doc)
if include_attachments and attachments_output_dir:
self._attachments_word(root, doc, attachments_output_dir, embed=embed_attachments)
self._tables_word(root, doc)
# 如检测到超宽表,额外加一页横向节重渲
try:
first = self._collect_first_table_rows(root)
if first and len(first[0])>10:
section = doc.add_section(WD_SECTION.NEW_PAGE)
section.orientation = WD_ORIENT.LANDSCAPE
w,h = section.page_height, section.page_width
section.page_width, section.page_height = w,h
self._tables_word(root, doc, wide_mode=True)
except Exception:
pass
doc.save(out_path)
return True
except Exception as e:
self.logger.error(f'DOCX失败: {e}')
return False
def _write_text_word(self, root: ET.Element, doc: Document):
"""改进的文本解析,保留OneNote格式"""
# 查找所有OE(Outline Element)元素,保持结构
outlines = self._findall_local(root, 'OE')
if outlines:
for oe in outlines:
self._process_outline_element(oe, doc)
else:
# 兼容旧格式
ts = self._findall_local(root,'T')
for t in ts:
if t.text:
txt = html.unescape(t.text)
txt = re.sub(r'<[^>]+>','',txt)
if txt.strip():
p = doc.add_paragraph()
# 检查格式
parent = t.getparent() if hasattr(t, 'getparent') else None
if parent is not None:
run = p.add_run(txt)
self._apply_formatting(parent, run)
else:
p.add_run(txt)
def _process_outline_element(self, oe: ET.Element, doc: Document):
"""处理OneNote的Outline元素,保留层级和格式"""
# 获取缩进级别
indent = 0
list_elem = self._findall_local(oe, 'List')
if list_elem:
for le in list_elem:
try:
indent = int(le.get('indent', '0'))
except:
indent = 0
# 处理文本
ts = self._findall_local(oe, 'T')
for t in ts:
if t.text:
txt = html.unescape(t.text)
txt = re.sub(r'<[^>]+>','',txt)
if txt.strip():
p = doc.add_paragraph()
# 应用缩进
if indent > 0:
p.paragraph_format.left_indent = Inches(indent * 0.5)
# 检查并应用样式
parent = t.getparent() if hasattr(t, 'getparent') else None
run = p.add_run(txt)
if parent is not None:
self._apply_formatting(parent, run)
def _apply_formatting(self, elem: ET.Element, run):
"""应用文本格式(粗体、斜体、下划线等)"""
try:
tag = elem.tag.lower() if isinstance(elem.tag, str) else ''
# 检查粗体
if 'bold' in tag or elem.get('bold') == 'true':
run.bold = True
# 检查斜体
if 'italic' in tag or elem.get('italic') == 'true':
run.italic = True
# 检查下划线
if 'underline' in tag or elem.get('underline') == 'true':
run.underline = True
# 检查字体大小
size = elem.get('fontSize')
if size:
try:
run.font.size = Pt(float(size))
except:
pass
except:
pass
def _images_word(self, root: ET.Element, doc: Document):
"""Word图片处理,智能调整图片大小"""
imgs = self._findall_local(root, 'Image')
for im in imgs:
# 提取图片数据
data = None
for attr in ('data', 'Data', 'binaryData'):
v = im.get(attr)
if v:
try:
data = base64.b64decode(v)
break
except Exception:
pass
if not data:
for c in im:
if isinstance(c.tag, str) and ('Data' in c.tag or c.tag.endswith('Data')) and c.text:
try:
data = base64.b64decode(c.text)
break
except Exception:
pass
if not data:
continue
# 创建临时图片文件
fd, fp = tempfile.mkstemp(suffix='.png')
os.close(fd)
Path(fp).write_bytes(data)
self.temp_files.append(fp)
try:
# 获取图片尺寸进行智能缩放
try:
from PIL import Image as PILImage
with PILImage.open(fp) as pil_img:
orig_width, orig_height = pil_img.size
aspect_ratio = orig_height / orig_width
except ImportError:
# 没有PIL时使用默认比例
aspect_ratio = 0.75
orig_width = 800
# Word页面可用宽度(约6.5英寸)
max_width = 6.5
min_width = 3.5
# 根据原始宽度智能选择显示宽度
if orig_width <= 600:
# 小图片,放大到合适大小
display_width = max(min_width, min(max_width, max_width * 0.8))
elif orig_width <= 1200:
# 中等图片,使用较大尺寸
display_width = max_width * 0.9
else:
# 大图片,使用最大宽度
display_width = max_width
# 如果图片很高,限制宽度以防止过高
if aspect_ratio > 1.5: # 高图片
display_width = min(display_width, max_width * 0.7)
doc.add_picture(fp, width=Inches(display_width))
doc.add_paragraph()
except Exception as e:
self.logger.warning(f"添加图片失败: {e}")
# 回退到默认处理
try:
doc.add_picture(fp, width=Inches(5))
doc.add_paragraph()
except Exception:
pass
def _attachments_word(self, root: ET.Element, doc: Document, out_dir: Path, embed=False):
"""处理Word附件,支持内嵌和外链两种模式"""
files = self._findall_local(root,'InsertedFile')
if not files:
return
if out_dir:
out_dir.mkdir(parents=True, exist_ok=True)
for a in files:
name = a.get('pathName','attachment')
data = self._extract_attachment(a)
if not data:
continue
para = doc.add_paragraph()
run = para.add_run('📎 ')
if embed:
# 内嵌模式:尝试将附件作为OLE对象嵌入
try:
# 先保存到临时文件
import tempfile
fd, temp_path = tempfile.mkstemp(suffix=Path(name).suffix)
os.close(fd)
Path(temp_path).write_bytes(data)
# 创建嵌入式链接文本
run2 = para.add_run(f'[内嵌附件] {name}')
run2.bold = True
run2.font.color.rgb = RGBColor(0, 0, 255)
# 同时保存到目录(作为备份)
if out_dir:
p = out_dir / name
p.write_bytes(data)
para.add_run(f' (已保存到: {name})')
os.unlink(temp_path)
except Exception as e:
# 如果内嵌失败,回退到外链模式
if out_dir:
p = out_dir / name
p.write_bytes(data)
run = para.add_run('附件:')
run.bold = True
self._add_hyperlink(para, p.resolve().as_uri(), name)
else:
# 外链模式:保存文件并创建超链接
if out_dir:
p = out_dir / name
try:
p.write_bytes(data)
run = para.add_run('附件:')
run.bold = True
self._add_hyperlink(para, p.resolve().as_uri(), name)
except Exception:
pass
def _add_hyperlink(self, para, url: str, text: str):
part = para.part
r_id = part.relate_to(url, RT.HYPERLINK, is_external=True)
link = OxmlElement('w:hyperlink'); link.set(qn('r:id'), r_id)
r = OxmlElement('w:r'); rPr = OxmlElement('w:rPr')
u = OxmlElement('w:u'); u.set(qn('w:val'),'single'); rPr.append(u); r.append(rPr)
t = OxmlElement('w:t'); t.text=text; r.append(t); link.append(r)
para._p.append(link)
def _extract_attachment(self, elem: ET.Element) -> Optional[bytes]:
d = elem.get('binaryData')
if d:
try: return base64.b64decode(d)
except Exception: pass
for c in elem:
if isinstance(c.tag,str) and ('Data' in c.tag or c.tag.endswith('Data')) and c.text:
try: return base64.b64decode(c.text)
except Exception: pass
return None
def _tables_word(self, root: ET.Element, doc: Document, wide_mode: bool=False):
"""修复Word表格处理,避免重复和格式问题"""
tables = self._findall_local(root, 'Table')
for tb in tables:
rows = self._parse_table_rows_clean(tb)
if not rows:
continue
# 去重:移除完全重复的行
unique_rows = []
seen_rows = set()
for row in rows:
row_key = '|'.join(row)
if row_key not in seen_rows:
seen_rows.add(row_key)
unique_rows.append(row)
if not unique_rows:
continue
max_cols = max(len(row) for row in unique_rows) if unique_rows else 1
max_rows = len(unique_rows)
# 处理宽表格
if max_cols > 12:
# 宽表格分两部分:正常表格 + 横向页面
if not wide_mode:
# 第一部分:显示前8列
cols_to_show = min(8, max_cols)
wt = doc.add_table(rows=max_rows, cols=cols_to_show)
self._fill_table_data(wt, unique_rows, cols_to_show)
# 添加提示
p = doc.add_paragraph()
p.add_run(f"注:表格共{max_cols}列,完整内容请查看横向页面").italic = True
else:
# 横向页面:显示所有列
wt = doc.add_table(rows=max_rows, cols=max_cols)
self._fill_table_data(wt, unique_rows, max_cols)
else:
# 普通表格直接显示
wt = doc.add_table(rows=max_rows, cols=max_cols)
self._fill_table_data(wt, unique_rows, max_cols)
doc.add_paragraph()
def _fill_table_data(self, table, rows, cols_limit):
"""填充表格数据的辅助函数"""
try:
table.style = 'Table Grid'
table.autofit = True
except:
pass
for i, row in enumerate(rows):
for j in range(min(cols_limit, len(row))):
if i < len(table.rows) and j < len(table.rows[i].cells):
cell_text = row[j] if j < len(row) else ''
cell = table.rows[i].cells[j]
# 清理文本
clean_text = self._clean_cell_text_for_word(cell_text)
cell.text = clean_text
# 设置单元格格式
for paragraph in cell.paragraphs:
paragraph.paragraph_format.word_wrap = True
paragraph.paragraph_format.keep_together = True
def _clean_cell_text_for_word(self, text: str) -> str:
"""清理Word单元格文本"""
if not text:
return ""
# 去除HTML标签和转义字符
text = html.unescape(text)
text = re.sub(r'<[^>]+>', '', text)
# 处理换行,避免单元格内换行
text = text.replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ')
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text
def _parse_table_rows_clean(self, table_elem: ET.Element) -> List[List[str]]:
"""清理版表格行解析,避免重复数据"""
rows = []
row_elements = self._findall_local(table_elem, 'Row')
for row_elem in row_elements:
cell_elements = self._findall_local(row_elem, 'Cell')
row_data = []
for cell_elem in cell_elements:
# 使用改进的文本提取
cell_text = self._extract_clean_cell_text(cell_elem)
row_data.append(cell_text)
# 只添加非空且有意义的行
if row_data and any(cell.strip() for cell in row_data):
rows.append(row_data)
return rows
def _extract_clean_cell_text(self, cell_elem: ET.Element) -> str:
"""提取单元格文本,避免重复内容"""
text_parts = []
seen_texts = set()
# 查找所有T元素
for t_elem in self._findall_local(cell_elem, 'T'):
if t_elem.text:
clean_text = html.unescape(t_elem.text).strip()
clean_text = re.sub(r'<[^>]+>', '', clean_text)
if clean_text and clean_text not in seen_texts:
seen_texts.add(clean_text)
text_parts.append(clean_text)
# 合并文本,用空格分隔
result = ' '.join(text_parts)
# 最终清理
result = re.sub(r'\s+', ' ', result).strip()
return result
def _parse_table_rows(self, table_elem: ET.Element) -> List[List[str]]:
"""解析表格行,改进文本提取避免换行乱格式"""
rows = []
for r in self._findall_local(table_elem, 'Row'):
row = []
for c in self._findall_local(r, 'Cell'):
# 更全面的文本提取
cell_text = self._extract_all_cell_text_word(c)
row.append(cell_text)
if row:
rows.append(row)
return rows
def _extract_all_cell_text_word(self, cell_elem: ET.Element) -> str:
"""为Word表格提取单元格文本,处理换行和格式"""
try:
text_parts = []
# 递归查找所有文本内容
def collect_text_recursive(elem):
if elem.text and elem.text.strip():
text_parts.append(elem.text.strip())
for child in elem:
collect_text_recursive(child)
if child.tail and child.tail.strip():
text_parts.append(child.tail.strip())
# 专门查找T元素(OneNote文本元素)
for t_elem in self._findall_local(cell_elem, 'T'):
if t_elem.text:
clean_text = html.unescape(t_elem.text)
clean_text = re.sub(r'<[^>]+>', '', clean_text)
clean_text = clean_text.strip()
if clean_text:
text_parts.append(clean_text)
# 如果T元素没找到,用递归方法
if not text_parts:
collect_text_recursive(cell_elem)
# 处理换行:将多个文本片段用空格连接,避免换行造成的格式问题
full_text = ' '.join([part for part in text_parts if part])
# 清理多余的空白字符
full_text = re.sub(r'\s+', ' ', full_text)
full_text = full_text.strip()
return full_text
except Exception as e:
self.logger.debug(f"Word单元格文本提取失败: {e}")
return ""
# --- PDF ---
def parse_page_to_pdf(self, xml: str, page_name: str, out_path: str,
include_images=True, include_attachments=True,
attachments_output_dir: Optional[Path]=None) -> bool:
try:
root = ET.fromstring(xml)
# 创建自定义样式,支持中文
styles = getSampleStyleSheet()
# 标题样式
title_style = ParagraphStyle(
'ChineseTitle',
parent=styles['Heading1'],
fontSize=18,
alignment=TA_CENTER,
fontName=self.chinese_font,
textColor=colors.black,
spaceAfter=12
)
# 正文样式
normal_style = ParagraphStyle(
'ChineseNormal',
parent=styles['Normal'],
fontSize=12,
fontName=self.chinese_font,
textColor=colors.black,
leftIndent=0,
rightIndent=0,
spaceAfter=6
)
# 创建文档,使用窄边距
doc = SimpleDocTemplate(
out_path,
pagesize=A4,
leftMargin=1.5*cm, # 窄边距
rightMargin=1.5*cm, # 窄边距
topMargin=2*cm,
bottomMargin=2*cm
)
story = []
# 添加标题
story.append(Paragraph(page_name, title_style))
story.append(Spacer(1, 12))
# 解析内容
self._write_text_pdf_enhanced(root, story, normal_style)
if include_images:
self._images_pdf_enhanced(root, story)
if include_attachments and attachments_output_dir:
self._attachments_pdf(root, story, normal_style, attachments_output_dir)
self._tables_pdf_enhanced(root, story, normal_style)
doc.build(story)
return True
except Exception as e:
self.logger.error(f'PDF生成失败: {e}')
return False
def _write_text_pdf_enhanced(self, root: ET.Element, story: List, normal_style: ParagraphStyle):
"""增强版PDF文本处理,更好地支持中文和格式"""
try:
# 查找所有文本元素,保持层次结构
outlines = self._findall_local(root, 'OE')
if outlines:
for oe in outlines:
self._process_outline_pdf(oe, story, normal_style)
else:
# 兼容模式
text_elements = self._findall_local(root, 'T')
for t in text_elements:
if t.text:
text = self._clean_text_for_pdf(t.text)
if text.strip():
story.append(Paragraph(text, normal_style))
story.append(Spacer(1, 4))
except Exception as e:
self.logger.error(f"PDF文本处理失败: {e}")
def _process_outline_pdf(self, oe: ET.Element, story: List, base_style: ParagraphStyle):
"""处理OneNote的大纲元素到PDF"""
try:
# 获取缩进级别
indent_level = 0
list_elems = self._findall_local(oe, 'List')
if list_elems:
try:
indent_level = int(list_elems[0].get('indent', '0'))
except:
indent_level = 0
# 处理文本
text_elems = self._findall_local(oe, 'T')
for t in text_elems:
if t.text:
text = self._clean_text_for_pdf(t.text)
if text.strip():
# 根据缩进创建样式
indent_style = ParagraphStyle(
f'Indent{indent_level}',
parent=base_style,
leftIndent=indent_level * 20, # 每级缩进20点
bulletIndent=indent_level * 15 if indent_level > 0 else 0
)
story.append(Paragraph(text, indent_style))
story.append(Spacer(1, 3))
except Exception as e:
self.logger.debug(f"大纲处理失败: {e}")
def _clean_text_for_pdf(self, text: str) -> str:
"""清理文本用于PDF显示"""
if not text:
return ""
# HTML解码
text = html.unescape(text)
# 移除HTML标签
text = re.sub(r'<[^>]+>', '', text)
# 处理换行和空白
text = text.replace('\r\n', '\n').replace('\r', '\n')
text = re.sub(r'[\t\x0b\x0c]+', ' ', text)
# 去除首尾空白但保留内部结构
text = text.strip()
return text
def _images_pdf_enhanced(self, root: ET.Element, story: List):
"""增强版图片处理,支持全屏显示"""
try:
imgs = self._findall_local(root, 'Image')
for im in imgs:
# 提取图片数据
data = None
for attr in ('data', 'Data', 'binaryData'):
v = im.get(attr)
if v:
try:
data = base64.b64decode(v)
break
except Exception:
pass
if not data:
for c in im:
if isinstance(c.tag, str) and ('Data' in c.tag or c.tag.endswith('Data')) and c.text:
try:
data = base64.b64decode(c.text)
break
except Exception:
pass
if not data:
continue
# 创建临时图片文件
fd, temp_img = tempfile.mkstemp(suffix='.png')
os.close(fd)
self.temp_files.append(temp_img)
try:
Path(temp_img).write_bytes(data)
# 获取图片尺寸
try:
from PIL import Image as PILImage
with PILImage.open(temp_img) as pil_img:
orig_width, orig_height = pil_img.size
except ImportError:
orig_width, orig_height = 600, 400
# 计算合适的显示尺寸
page_width = A4[0] - 3*cm # 窄边距
page_height = A4[1] - 4*cm
# 智能缩放
scale_w = page_width / orig_width
scale_h = page_height / orig_height
scale = min(scale_w, scale_h, 1.2) # 允许适当放大
final_width = orig_width * scale
final_height = orig_height * scale
# 确保图片至少占页面70%宽度
min_width = page_width * 0.7
if final_width < min_width:
scale = min_width / orig_width
final_width = min_width
final_height = orig_height * scale
img = RLImage(temp_img, width=final_width, height=final_height)
story.append(Spacer(1, 8))
story.append(img)
story.append(Spacer(1, 12))
except Exception as e:
self.logger.warning(f"处理图片失败: {e}")
# 使用固定大小作为回退
try:
img = RLImage(temp_img, width=5*inch, height=4*inch)
story.append(img)
story.append(Spacer(1, 12))
except Exception:
pass
except Exception as e:
self.logger.error(f"PDF图片处理失败: {e}")
def _attachments_pdf(self, root: ET.Element, story: List, normal_style: ParagraphStyle, out_dir: Path):
"""PDF附件处理:保存到目录并在文档中添加引用"""