(items)
| 114 | with pikepdf.Pdf.open(pdf_path) as pdf: |
| 115 | # 创建书签结构 |
| 116 | def create_bookmark_tree(items): |
| 117 | current_l1 = None |
| 118 | current_l2 = None |
| 119 | current_l3 = None |
| 120 | bookmarks = [] |
| 121 | |
| 122 | for item in items: |
| 123 | try: |
| 124 | # 检查页码是否有效 |
| 125 | if item['number'] < 1 or item['number'] > len(pdf.pages): |
| 126 | print(f"警告:页码 {item['number']} 超出范围 (1-{len(pdf.pages)}),跳过条目 '{item['text']}'") |
| 127 | continue |
| 128 | |
| 129 | bookmark = pikepdf.OutlineItem(item['text'], item['number'] - 1, 'Fit') |
| 130 | |
| 131 | if item['level'] == 1: |
| 132 | current_l1 = bookmark |
| 133 | bookmarks.append(bookmark) |
| 134 | current_l1.children = [] |
| 135 | # 重置下级指针 |
| 136 | current_l2 = None |
| 137 | current_l3 = None |
| 138 | |
| 139 | elif item['level'] == 2: |
| 140 | if current_l1 is not None: |
| 141 | current_l1.children.append(bookmark) |
| 142 | current_l2 = bookmark |
| 143 | current_l2.children = [] |
| 144 | current_l3 = None |
| 145 | else: |
| 146 | # 降级处理:无 L1 时直接挂根 |
| 147 | bookmarks.append(bookmark) |
| 148 | current_l2 = bookmark |
| 149 | current_l2.children = [] |
| 150 | current_l3 = None |
| 151 | |
| 152 | elif item['level'] == 3: |
| 153 | if current_l2 and current_l1: |
| 154 | current_l2.children.append(bookmark) |
| 155 | current_l3 = bookmark |
| 156 | current_l3.children = [] |
| 157 | elif current_l1: |
| 158 | # 缺少 L2,降级挂到 L1 |
| 159 | current_l1.children.append(bookmark) |
| 160 | current_l3 = bookmark |
| 161 | current_l3.children = [] |
| 162 | else: |
| 163 | bookmarks.append(bookmark) |
| 164 | |
| 165 | elif item['level'] >= 4: |
| 166 | if current_l3 and current_l2 and current_l1: |
| 167 | current_l3.children.append(bookmark) |
| 168 | elif current_l2 and current_l1: |
| 169 | current_l2.children.append(bookmark) |
| 170 | elif current_l1: |
| 171 | current_l1.children.append(bookmark) |
| 172 | else: |
| 173 | bookmarks.append(bookmark) |
no outgoing calls
no test coverage detected