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
| /**
* Pandoc Export Script for Zotero Better Notes
*
* 功能:将 Zotero 笔记导出为 Word (docx) 文档,支持图片和引用链接
*
* 作者:Stream-L
* 日期:2025-12-01
* 版本:2.0
*/
// ============================================================================
// 用户配置区域 (USER CONFIGURATION)
// ============================================================================
const USER_CONFIG = {
// Pandoc 可执行文件搜索路径列表
// 脚本会依次检查这些路径,直到找到可用的 Pandoc
pandocPaths: [
"C:\\Program Files\\Pandoc\\pandoc.exe",
"C:\\Program Files (x86)\\Pandoc\\pandoc.exe",
"pandoc", // 尝试系统 PATH
],
// Word 模板路径 (.docx) !!!【需要修改到自己的模板路径】
// 模板中的样式(字体、段落格式等)将被应用到输出文档
templatePath: "C:\\Users\\STREAM\\Documents\\template\\pandoc\\不编号templates_报告自用.docx",
// 导出选项
options: {
// 链接样式: "hyperlink" 或 "text"
// "hyperlink" - 生成可点击的超链接
// "text" - 仅保留文本,去除链接
linkStyle: "hyperlink",
// 是否处理图片(解析 Better Notes 的复杂图片格式)
processImages: true,
// 调试模式
debug: true
}
};
// ============================================================================
// 脚本主体 - 请勿修改以下代码
// ============================================================================
// 阻止脚本多次执行
if (typeof item !== "undefined" && item) return;
const Zotero = require("Zotero");
const window = require("window");
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
// 获取选中的条目
let selectedItems = [];
if (typeof items !== "undefined" && items.length > 0) {
selectedItems = items;
} else if (typeof item !== "undefined") {
selectedItems = [item];
} else {
window.alert("请先选择要处理的条目");
return;
}
const CONFIG = {
templatePath: USER_CONFIG.templatePath,
pandocPath: null,
...USER_CONFIG.options
};
// ============================================================================
// 核心函数
// ============================================================================
/**
* 查找 Pandoc 可执行文件
*/
async function findPandoc() {
const localAppData = Services.env.get("LOCALAPPDATA");
const searchPaths = [
...USER_CONFIG.pandocPaths,
`${localAppData}\\Pandoc\\pandoc.exe`
];
for (const path of searchPaths) {
if (!path) continue;
if (path === "pandoc") continue; // 跳过,最后尝试
if (await IOUtils.exists(path)) {
Zotero.debug(`[Pandoc Export] 找到 Pandoc: ${path}`);
return path;
}
}
if (USER_CONFIG.pandocPaths.includes("pandoc")) {
return "pandoc";
}
throw new Error(
"无法找到 Pandoc 可执行文件。\n\n" +
"请使用以下方法之一安装:\n" +
"1. Winget: winget install Pandoc.Pandoc\n" +
"2. Chocolatey: choco install pandoc\n" +
"3. 官网下载: https://pandoc.org/installing.html\n\n" +
"安装后请重新运行此脚本。"
);
}
/**
* 选择保存文件路径
*/
function pickSaveFile(defaultName) {
return new Promise((resolve) => {
const nsIFilePicker = Components.interfaces.nsIFilePicker;
const fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp.init(window, "保存 Word 文档", nsIFilePicker.modeSave);
fp.appendFilter("Word 文档 (*.docx)", "*.docx");
fp.defaultString = defaultName;
fp.defaultExtension = "docx";
fp.open((result) => {
if (result === nsIFilePicker.returnOK || result === nsIFilePicker.returnReplace) {
let path = fp.file.path;
if (!path.toLowerCase().endsWith(".docx")) {
path += ".docx";
}
resolve(path);
} else {
resolve(null);
}
});
});
}
/**
* 选择输出目录
*/
function pickDirectory() {
return new Promise((resolve) => {
const nsIFilePicker = Components.interfaces.nsIFilePicker;
const fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp.init(window, "选择输出目录", nsIFilePicker.modeGetFolder);
fp.open((result) => {
if (result === nsIFilePicker.returnOK) {
resolve(fp.file.path);
} else {
resolve(null);
}
});
});
}
/**
* 获取笔记标题
*/
function getNoteTitle(noteItem) {
const note = noteItem.getNote();
const parser = new DOMParser();
const doc = parser.parseFromString(note, "text/html");
const h1 = doc.querySelector("h1, h2, h3");
if (h1 && h1.textContent.trim()) {
return sanitizeFilename(h1.textContent.trim());
}
const text = doc.body.textContent.trim();
if (text) {
return sanitizeFilename(text.substring(0, 50));
}
return "untitled_note";
}
/**
* 清理文件名
*/
function sanitizeFilename(name) {
return name
.replace(/[<>:"/\\|?*]/g, "_")
.replace(/\s+/g, " ")
.trim()
.substring(0, 100);
}
/**
* 笔记转 Markdown
*/
async function noteToMarkdown(noteItem) {
const api = Zotero.BetterNotes?.api;
if (api && api.convert && api.convert.note2md) {
let markdown = await api.convert.note2md(noteItem, Zotero.getTempDirectory().path, {
keepNoteLink: true,
withYAMLHeader: false,
});
markdown = await processMarkdownContent(markdown);
return markdown;
}
return await processNoteHtml(noteItem);
}
/**
* 处理 Markdown 内容(图片和链接)
*/
async function processMarkdownContent(markdown) {
// 1. 递归移除 span 标签
let prev = "";
while (markdown !== prev) {
prev = markdown;
markdown = markdown.replace(/<span\s+[^>]*>([\s\S]*?)<\/span>/gi, "$1");
}
// 2. 处理链接
markdown = markdown.replace(/<a\s+(?:[^>]*?\s+)?href=["'"](zotero:\/\/[^"'"]+)["'"][^>]*>([\s\S]*?)<\/a>/gi, (match, url, text) => {
if (CONFIG.linkStyle === "text") {
return text;
}
return `[${text}](${url})`;
});
// 3. 处理图片
const replacements = [];
const storagePath = Zotero.getStorageDirectory().path;
// Markdown 图片语法
const mdImgRegex = /!$(.*?)$$(attachments\/([^)]+))$/g;
let match;
while ((match = mdImgRegex.exec(markdown)) !== null) {
const fullMatch = match[0];
const altText = match[1];
const filename = match[3];
let key = null;
const keyMatch = altText.match(/data-attachment-key=["'"]([^"'"]+)["'"]/);
if (keyMatch) {
key = keyMatch[1];
} else {
key = filename.split('.')[0];
}
if (key) {
replacements.push({ fullMatch, key, alt: "image" });
}
}
// HTML img 标签
const htmlImgRegex = /<img\s+[^>]*data-attachment-key=["'"]([^"'"]+)["'"][^>]*>/gi;
while ((match = htmlImgRegex.exec(markdown)) !== null) {
replacements.push({
fullMatch: match[0],
key: match[1],
alt: "image"
});
}
// 执行图片路径替换
for (const rep of replacements) {
let realPath = null;
const itemDir = PathUtils.join(storagePath, rep.key);
if (await IOUtils.exists(itemDir)) {
const children = await IOUtils.getChildren(itemDir);
for (const child of children) {
if (child.toLowerCase().match(/\.(png|jpg|jpeg|gif|bmp|webp|svg)$/)) {
realPath = child;
break;
}
}
}
if (realPath) {
realPath = realPath.replace(/\\/g, '/');
const newImage = ``;
markdown = markdown.replace(rep.fullMatch, newImage);
Zotero.debug(`[Pandoc] 图片替换: ${rep.key} -> ${realPath}`);
} else {
Zotero.debug(`[Pandoc] 未找到图片: ${rep.key}`);
}
}
return markdown;
}
/**
* 处理笔记 HTML(回退方案)
*/
async function processNoteHtml(noteItem) {
const note = noteItem.getNote();
const parser = new DOMParser();
const doc = parser.parseFromString(note, "text/html");
const images = doc.querySelectorAll('img[data-attachment-key]');
for (const img of images) {
const key = img.getAttribute('data-attachment-key');
if (key) {
const storagePath = Zotero.getStorageDirectory().path;
const exts = ['.png', '.jpg', '.jpeg', '.gif', '.webp'];
for (const ext of exts) {
const imagePath = PathUtils.join(storagePath, key, key + ext);
if (await IOUtils.exists(imagePath)) {
img.setAttribute('src', imagePath);
break;
}
}
}
}
return simpleHtmlToMarkdown(doc.body);
}
/**
* 简单的 HTML 转 Markdown
*/
function simpleHtmlToMarkdown(element) {
let result = "";
function process(node, depth = 0) {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return "";
}
const tag = node.tagName.toLowerCase();
let content = "";
for (const child of node.childNodes) {
content += process(child, depth + (tag === 'ul' || tag === 'ol' ? 1 : 0));
}
switch (tag) {
case "h1": return `# ${content.trim()}\n\n`;
case "h2": return `## ${content.trim()}\n\n`;
case "h3": return `### ${content.trim()}\n\n`;
case "p": return `${content.trim()}\n\n`;
case "strong":
case "b": return `**${content}**`;
case "em":
case "i": return `*${content}*`;
case "code": return `\`${content}\``;
case "a":
const href = node.getAttribute("href") || "";
const text = content.trim() || href;
if (CONFIG.linkStyle === "text") return text;
return `[${text}](${href})`;
case "li":
const indent = " ".repeat(Math.max(0, depth - 1));
return `${indent}- ${content.trim()}\n`;
case "br": return "\n";
default: return content;
}
}
result = process(element);
return result.replace(/\n{3,}/g, "\n\n");
}
/**
* 运行 Pandoc
*/
async function runPandoc(inputPath, outputPath) {
const tempDir = Zotero.getTempDirectory().path;
const errorLogPath = PathUtils.join(tempDir, `pandoc_error_${Zotero.Utilities.randomString(6)}.log`);
const batPath = PathUtils.join(tempDir, `pandoc_run_${Zotero.Utilities.randomString(6)}.bat`);
// 构建命令
let cmd = `"${CONFIG.pandocPath}" "${inputPath}" -o "${outputPath}" --wrap=none`;
if (CONFIG.templatePath && await IOUtils.exists(CONFIG.templatePath)) {
cmd += ` --reference-doc "${CONFIG.templatePath}"`;
}
cmd += ` 2>"${errorLogPath}"`;
// 创建批处理文件
const batContent = "@echo off\r\n" +
"chcp 65001 > nul\r\n" +
cmd + "\r\n" +
"exit /b %errorlevel%\r\n";
const encoder = new TextEncoder();
await IOUtils.write(batPath, encoder.encode(batContent));
Zotero.debug(`[Pandoc] 批处理: ${batPath}`);
Zotero.debug(`[Pandoc] 命令: ${cmd}`);
return new Promise(async (resolve, reject) => {
try {
const cmdFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsIFile);
cmdFile.initWithPath("C:\\Windows\\System32\\cmd.exe");
const process = Components.classes["@mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(cmdFile);
process.run(true, ["/c", batPath], 2);
const exitValue = process.exitValue;
Zotero.debug(`[Pandoc] 退出码: ${exitValue}`);
// 读取错误日志
let errorLog = "";
try {
if (await IOUtils.exists(errorLogPath)) {
const errorBytes = await IOUtils.read(errorLogPath);
const decoder = new TextDecoder("utf-8");
errorLog = decoder.decode(errorBytes);
}
} catch (e) {}
// 清理临时文件
try {
await IOUtils.remove(batPath, { ignoreAbsent: true });
await IOUtils.remove(errorLogPath, { ignoreAbsent: true });
} catch (e) {}
if (exitValue === 0) {
const outputExists = await IOUtils.exists(outputPath);
if (outputExists) {
resolve();
} else {
reject(new Error(`Pandoc 执行完成但输出文件未生成\n${errorLog || ''}`));
}
} else if (exitValue === 9009) {
reject(new Error(
"无法找到 Pandoc 可执行文件。\n\n" +
"安装方法:\n" +
"1. Winget: winget install Pandoc.Pandoc\n" +
"2. Chocolatey: choco install pandoc\n" +
"3. 官网: https://pandoc.org/installing.html\n\n" +
"安装后在脚本顶部配置路径。"
));
} else {
reject(new Error(`Pandoc 失败 (退出码: ${exitValue})\n\n${errorLog}`));
}
} catch (error) {
try {
await IOUtils.remove(batPath, { ignoreAbsent: true });
await IOUtils.remove(errorLogPath, { ignoreAbsent: true });
} catch (e) {}
reject(error);
}
});
}
/**
* 导出单个笔记(内部函数,不弹窗)
*/
async function exportNoteInternal(noteItem, outputPath) {
const tempDir = Zotero.getTempDirectory().path;
// 转换为 Markdown
const markdown = await noteToMarkdown(noteItem);
// 保存临时文件
const mdPath = PathUtils.join(tempDir, `${Zotero.Utilities.randomString(8)}.md`);
await Zotero.File.putContentsAsync(mdPath, markdown);
// 调用 Pandoc
await runPandoc(mdPath, outputPath);
// 清理
await IOUtils.remove(mdPath, { ignoreAbsent: true });
}
/**
* 显示成功提示
*/
function showSuccess(path) {
const result = window.confirm(
`笔记已成功导出到:\n${path}\n\n点击"确定"打开文件夹`
);
if (result) {
Zotero.File.reveal(path);
}
}
// ============================================================================
// 主入口
// ============================================================================
async function main() {
// 1. 查找 Pandoc
try {
CONFIG.pandocPath = await findPandoc();
} catch (e) {
window.alert(e.message);
return;
}
// 2. 收集笔记
const noteItems = [];
for (const selectedItem of selectedItems) {
if (selectedItem.itemType === "note") {
noteItems.push(selectedItem);
} else if (selectedItem.isRegularItem && selectedItem.isRegularItem()) {
const notes = selectedItem.getNotes();
for (const noteId of notes) {
noteItems.push(Zotero.Items.get(noteId));
}
}
}
if (noteItems.length === 0) {
window.alert("请先选择一个或多个笔记条目");
return;
}
// 3. 导出
if (noteItems.length === 1) {
// 单个笔记
const noteItem = noteItems[0];
const title = getNoteTitle(noteItem);
const outputPath = await pickSaveFile(`${title}.docx`);
if (!outputPath) return;
try {
await exportNoteInternal(noteItem, outputPath);
showSuccess(outputPath);
} catch (error) {
Zotero.logError(error);
window.alert(`导出失败: ${error.message}`);
}
} else {
// 批量导出
const outputDir = await pickDirectory();
if (!outputDir) return;
const results = [];
for (const noteItem of noteItems) {
try {
const title = getNoteTitle(noteItem);
const outputPath = PathUtils.join(outputDir, `${title}.docx`);
await exportNoteInternal(noteItem, outputPath);
results.push({ success: true, path: outputPath });
} catch (error) {
results.push({ success: false, error: error.message });
}
}
const successCount = results.filter(r => r.success).length;
const failCount = results.length - successCount;
if (successCount > 0) {
const firstSuccess = results.find(r => r.success);
const openFolder = window.confirm(
`批量导出完成\n成功: ${successCount} 个\n失败: ${failCount} 个\n\n点击"确定"打开文件夹`
);
if (openFolder && firstSuccess) {
Zotero.File.reveal(firstSuccess.path);
}
} else {
window.alert(`导出失败,所有 ${failCount} 个笔记均失败`);
}
}
}
// 运行
main().catch(error => {
Zotero.logError(error);
window.alert(`导出失败: ${error.message}`);
});
|