diff --git a/assets/pictures/26.11.0_pictures/06a24ac111044f6e56ebeb08-x476ox.jpg b/assets/pictures/26.11.0_pictures/06a24ac111044f6e56ebeb08-x476ox.jpg new file mode 100644 index 0000000..edaa4c1 Binary files /dev/null and b/assets/pictures/26.11.0_pictures/06a24ac111044f6e56ebeb08-x476ox.jpg differ diff --git a/assets/pictures/26.11.0_pictures/13badf221cfa0e2eb641e5c6-wc3irz.jpg b/assets/pictures/26.11.0_pictures/13badf221cfa0e2eb641e5c6-wc3irz.jpg new file mode 100644 index 0000000..6ea6f86 Binary files /dev/null and b/assets/pictures/26.11.0_pictures/13badf221cfa0e2eb641e5c6-wc3irz.jpg differ diff --git a/assets/pictures/26.11.0_pictures/17fdb896b39d4b14a45982e5-wd5mok.jpg b/assets/pictures/26.11.0_pictures/17fdb896b39d4b14a45982e5-wd5mok.jpg new file mode 100644 index 0000000..f770744 Binary files /dev/null and b/assets/pictures/26.11.0_pictures/17fdb896b39d4b14a45982e5-wd5mok.jpg differ diff --git a/assets/pictures/26.11.0_pictures/75aa5142c5fd3b94ec7613ab-x8zmr7.jpg b/assets/pictures/26.11.0_pictures/75aa5142c5fd3b94ec7613ab-x8zmr7.jpg new file mode 100644 index 0000000..1d3eb54 Binary files /dev/null and b/assets/pictures/26.11.0_pictures/75aa5142c5fd3b94ec7613ab-x8zmr7.jpg differ diff --git a/assets/pictures/26.11.0_pictures/ef1be4ca769fc52e513e69e1-129si8u.png b/assets/pictures/26.11.0_pictures/ef1be4ca769fc52e513e69e1-129si8u.png new file mode 100644 index 0000000..a7c9643 Binary files /dev/null and b/assets/pictures/26.11.0_pictures/ef1be4ca769fc52e513e69e1-129si8u.png differ diff --git a/publications/26.11.0/2::理论战线/2::从何出发?——今天中国共产主义运动中两条路线的斗争.md b/publications/26.11.0/2::理论战线/2::从何出发?——今天中国共产主义运动中两条路线的斗争.md index f5c739a..c74e07a 100644 --- a/publications/26.11.0/2::理论战线/2::从何出发?——今天中国共产主义运动中两条路线的斗争.md +++ b/publications/26.11.0/2::理论战线/2::从何出发?——今天中国共产主义运动中两条路线的斗争.md @@ -54,7 +54,7 @@ 而工革报之前联合自由派分子“九”搞出来的统战大纲也明确提到了等级制和经济刺激。 -![九的《统战大纲》](https://imgbed.cmlmuf.org/i/2026/06/06/129si8u.png) +![九的《统战大纲》](/../../../assets/pictures/26.11.0_pictures/ef1be4ca769fc52e513e69e1-129si8u.png) 重复一下我们之前的批判: diff --git a/publications/26.11.0/3::学生工作/4::长沙学生们的斗争.md b/publications/26.11.0/3::学生工作/4::长沙学生们的斗争.md index a5b65a7..8d30a5d 100644 --- a/publications/26.11.0/3::学生工作/4::长沙学生们的斗争.md +++ b/publications/26.11.0/3::学生工作/4::长沙学生们的斗争.md @@ -5,19 +5,19 @@ 12 月 27 日,长沙市某省级示范高中爆发了学生抗议活动。据悉,因校方将原定的三天元旦假期突然缩减为两天,引发了学生及部分老师的不满。当天,学生们开始在食堂、年级办公室张贴并传阅抗议檄文和大字报,并进而演变成自发聚集喊楼行动,喊出“誓死力争,还我三休”等口号。最终学生们抗议成功,校方恢复了三天假期。 **这是学生们打出的大字报**: -![Screenshot_20260831-003938~3](https://imgbed.cmlmuf.org/i/2026/08/31/wd5mok.jpg) +![](../../../assets/pictures/26.11.0_pictures/13badf221cfa0e2eb641e5c6-wc3irz.jpg) -![Screenshot_20260831-003938~2](https://imgbed.cmlmuf.org/i/2026/08/31/wc3irz.jpg) +![](../../../assets/pictures/26.11.0_pictures/17fdb896b39d4b14a45982e5-wd5mok.jpg) **据传,学校的官僚们也曾试图处理学生**: -![Screenshot_20260831-003945~2](https://imgbed.cmlmuf.org/i/2026/08/31/x476ox.jpg) +![](../../../assets/pictures/26.11.0_pictures/06a24ac111044f6e56ebeb08-x476ox.jpg) 但不管结局如何,学生聚集起来的力量最终还是让官僚们退步了。因为学生们的团结他们也 不敢处理学生,并且最终承认了学生们的合法三休权益。学生们事后总结了这场斗争: -![Screenshot\_20260831-003952~2](https://imgbed.cmlmuf.org/i/2026/08/31/x8zmr7.jpg) +![](../../../assets/pictures/26.11.0_pictures/75aa5142c5fd3b94ec7613ab-x8zmr7.jpg) 学生们意识到了团结和斗争的作用,他们用大字报等形式把学生的愤怒集中的表现了出来并凝聚为共同的行动。因此,这里的大字报完全起到了集中表述阶级情绪、阶级利益和集中阶级行动作用。同时,大字报等行为和运动本身也推动了整个学生的进步,使原本茫然服从学校秩序和服务官僚资产阶级利益的学生们开始明确的把自身和学校官僚们对立了起来,在自身集体利益和学校官僚利益之间选择了前者。 @@ -41,4 +41,4 @@ > > -- 革命社会主义阵地(RSF)第八期月刊《是斗争的胜利!论伟大的“九十学运”的意义》 -“九十学运”中所揭示和所预见的全部学生运动发展趋势在于:提高现有的学生运动的数量和规模,最终要把它发展到包含全国学生的广泛维护自身合法利益的程度;提高学生斗争的组织程度,像郑州一中学生所一开始要求的那样,要建立起包含最广泛的学生的组织,这种组织是主要用来进行阶级斗争的;在运动中逐步提高学生的政治性,使它开始和社会主义运动结合起来,这就要建立领导整个学生运动的学生政治组织。因此,长沙此校学生的斗争意义就在于证实了这些趋势和预见是完全正确的和完全可行的,我们今后的学生工作应该照着这样的方向稳步的前进。 \ No newline at end of file +“九十学运”中所揭示和所预见的全部学生运动发展趋势在于:提高现有的学生运动的数量和规模,最终要把它发展到包含全国学生的广泛维护自身合法利益的程度;提高学生斗争的组织程度,像郑州一中学生所一开始要求的那样,要建立起包含最广泛的学生的组织,这种组织是主要用来进行阶级斗争的;在运动中逐步提高学生的政治性,使它开始和社会主义运动结合起来,这就要建立领导整个学生运动的学生政治组织。因此,长沙此校学生的斗争意义就在于证实了这些趋势和预见是完全正确的和完全可行的,我们今后的学生工作应该照着这样的方向稳步的前进。 diff --git a/templates/computer_template/style.html b/templates/computer_template/style.html index 236915a..d9e8691 100644 --- a/templates/computer_template/style.html +++ b/templates/computer_template/style.html @@ -33,6 +33,8 @@ } .global h1 { + font-size: 3rem; + line-height: 1.5; } .global h2 { @@ -61,18 +63,39 @@ color: white; background-color: red; border: 0.18rem solid red; - display: inline-flex; + display: block; + break-before: page; + page-break-before: always; width: fit-content; line-height: 1.5; padding: 0.08em 0.24em; white-space: normal; word-break: break-all; font-family: "ZCOOL QingKe HuangYou", sans-serif; - margin: 1rem 1rem 0rem 2rem; + margin: 0 1rem 1.5rem 2rem; border-radius: 0.5rem; overflow-wrap: break-word; max-width: 21cm; } + + /* Keep the first article with its column title; separate later articles + while allowing their bodies to flow across pages. */ + .passages { + margin: 0 2rem; + padding: 0 0 1.5rem; + break-inside: auto; + page-break-inside: auto; + } + + .passages:not(.first-passage) { + break-before: page; + page-break-before: always; + } + + .passages.first-passage > :first-child { + margin-block-start: 1.5rem; + } + .index-column page_title { font-size: calc(var(--font-size) + 0.5rem); font-weight: bold; @@ -85,14 +108,95 @@ margin: 1rem 0; color: #666; } + + /* Material You-inspired surfaces for Markdown-generated tables. */ + .global table { + width: 100%; + margin: 1.5rem 0 2rem; + border: 1px solid #c4c7c5; + border-radius: 0.75rem; + border-spacing: 0; + border-collapse: separate; + background-color: #fdfbff; + color: #1a1b1f; + overflow: hidden; + break-inside: auto; + page-break-inside: auto; + line-height: 1.5; + } + + .global table caption { + margin-bottom: 0.75rem; + color: #454746; + font-size: 0.9em; + font-weight: 600; + text-align: left; + } + + .global table thead { + display: table-header-group; + background-color: #dcefeb; + color: #00201f; + } + + .global table th, + .global table td { + padding: 0.75rem 1rem; + border-right: 1px solid #c4c7c5; + border-bottom: 1px solid #c4c7c5; + text-align: left; + vertical-align: top; + overflow-wrap: anywhere; + } + + .global table th { + color: #00504f; + font-weight: 700; + } + + .global table tbody tr:nth-child(even) { + background-color: #f3f5f3; + } + + .global table tbody tr { + break-inside: avoid; + page-break-inside: avoid; + } + + .global table tr > :last-child { + border-right: 0; + } + + .global table tbody tr:last-child td { + border-bottom: 0; + } + + .global table thead tr:first-child th:first-child { + border-top-left-radius: 0.75rem; + } + + .global table thead tr:first-child th:last-child { + border-top-right-radius: 0.75rem; + } + + .global table tbody tr:last-child td:first-child { + border-bottom-left-radius: 0.75rem; + } + + .global table tbody tr:last-child td:last-child { + border-bottom-right-radius: 0.75rem; + } + .global img { - height: 100%; - object-fit: scale-down; + height: auto; max-width: 100%; - max-height: 25cm; - border-radius: 12px; - border: 4px solid linear-gradient(45deg, #e799b1, #44b144, #2f90ba); - box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); + max-height: 33vh; + object-fit: contain; + padding: 5px; + border: 1px solid #c9d9d5; + border-radius: 10px; + background: #fff; + box-shadow: 0 2px 8px rgba(24, 50, 46, 0.14); display: block; margin: 1rem auto; /* color: transparent; */ diff --git a/templates/mobile_template/style.html b/templates/mobile_template/style.html index 05b8f0b..25e29bc 100644 --- a/templates/mobile_template/style.html +++ b/templates/mobile_template/style.html @@ -49,11 +49,23 @@ /* Use padding instead of adjacent margins so the article separators remain visible when Chromium fragments the document for printing. */ .passages { - padding-block: 2.5rem; + margin: 0 2rem; + padding: 0 0 2.5rem; break-inside: auto; page-break-inside: auto; } + /* Keep the column title with its first article, but start later articles + on a fresh page while allowing each article body to fragment naturally. */ + .passages:not(.first-passage) { + break-before: page; + page-break-before: always; + } + + .passages.first-passage > :first-child { + margin-block-start: 1.5rem; + } + .global h1 { line-height: 4rem; font-family: "HongLei", sans-serif; @@ -84,14 +96,16 @@ color: white; background-color: red; border: 0.18rem solid red; - display: inline-flex; + display: block; + break-before: page; + page-break-before: always; width: fit-content; line-height: 1.5; padding: 0.08em 0.24em; white-space: normal; word-break: break-all; font-family: "ZCOOL QingKe HuangYou", sans-serif; - margin: 4rem 1rem 1rem 2rem; + margin: 0 1rem 1.5rem 2rem; border-radius: 0.5rem; overflow-wrap: break-word; max-width: 21cm; @@ -103,13 +117,100 @@ padding: 0.5rem 1rem; margin: 1rem 0; color: #666; + break-inside: auto; + page-break-inside: auto; + break-after: auto; + page-break-after: auto; } + + /* Material You-inspired table surfaces for Markdown-generated tables. */ + .global table { + width: 100%; + margin: 1.5rem 0 2rem; + border: 1px solid #c4c7c5; + border-radius: 0.75rem; + border-spacing: 0; + border-collapse: separate; + background-color: #fdfbff; + color: #1a1b1f; + overflow: hidden; + break-inside: auto; + page-break-inside: auto; + line-height: 1.5; + } + + .global table caption { + margin-bottom: 0.75rem; + color: #454746; + font-size: 0.9em; + font-weight: 600; + text-align: left; + } + + .global table thead { + display: table-header-group; + background-color: #dcefeb; + color: #00201f; + } + + .global table th, + .global table td { + padding: 0.75rem 1rem; + border-right: 1px solid #c4c7c5; + border-bottom: 1px solid #c4c7c5; + text-align: left; + vertical-align: top; + overflow-wrap: anywhere; + } + + .global table th { + color: #00504f; + font-weight: 700; + } + + .global table tbody tr:nth-child(even) { + background-color: #f3f5f3; + } + + .global table tbody tr { + break-inside: avoid; + page-break-inside: avoid; + } + + .global table tr > :last-child { + border-right: 0; + } + + .global table tbody tr:last-child td { + border-bottom: 0; + } + + .global table thead tr:first-child th:first-child { + border-top-left-radius: 0.75rem; + } + + .global table thead tr:first-child th:last-child { + border-top-right-radius: 0.75rem; + } + + .global table tbody tr:last-child td:first-child { + border-bottom-left-radius: 0.75rem; + } + + .global table tbody tr:last-child td:last-child { + border-bottom-right-radius: 0.75rem; + } + .global img { max-width: 100%; height: auto; - border-radius: 12px; - border: 4px solid linear-gradient(45deg, #e799b1, #44b144, #2f90ba); - box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); + max-height: 33vh; + object-fit: contain; + padding: 5px; + border: 1px solid #c9d9d5; + border-radius: 10px; + background: #fff; + box-shadow: 0 2px 8px rgba(24, 50, 46, 0.14); display: block; margin: 1rem auto; /* color: transparent; */ diff --git a/templates/printable_template/style.html b/templates/printable_template/style.html index 7cec149..f79ea26 100644 --- a/templates/printable_template/style.html +++ b/templates/printable_template/style.html @@ -93,6 +93,85 @@ border-radius: 22px; border-color: #666; } + + /* Material You-inspired surfaces for Markdown-generated tables. */ + .global table { + width: 100%; + margin: 1.5rem 0 2rem; + border: 1px solid #c4c7c5; + border-radius: 0.75rem; + border-spacing: 0; + border-collapse: separate; + background-color: #fdfbff; + color: #1a1b1f; + overflow: hidden; + break-inside: auto; + page-break-inside: auto; + line-height: 1.5; + } + + .global table caption { + margin-bottom: 0.75rem; + color: #454746; + font-size: 0.9em; + font-weight: 600; + text-align: left; + } + + .global table thead { + display: table-header-group; + background-color: #dcefeb; + color: #00201f; + } + + .global table th, + .global table td { + padding: 0.75rem 1rem; + border-right: 1px solid #c4c7c5; + border-bottom: 1px solid #c4c7c5; + text-align: left; + vertical-align: top; + overflow-wrap: anywhere; + } + + .global table th { + color: #00504f; + font-weight: 700; + } + + .global table tbody tr:nth-child(even) { + background-color: #f3f5f3; + } + + .global table tbody tr { + break-inside: avoid; + page-break-inside: avoid; + } + + .global table tr > :last-child { + border-right: 0; + } + + .global table tbody tr:last-child td { + border-bottom: 0; + } + + .global table thead tr:first-child th:first-child { + border-top-left-radius: 0.75rem; + } + + .global table thead tr:first-child th:last-child { + border-top-right-radius: 0.75rem; + } + + .global table tbody tr:last-child td:first-child { + border-bottom-left-radius: 0.75rem; + } + + .global table tbody tr:last-child td:last-child { + border-bottom-right-radius: 0.75rem; + } + .global img { height: auto; diff --git a/tools/gp/README.md b/tools/gp/README.md index 4fd207d..7834737 100644 --- a/tools/gp/README.md +++ b/tools/gp/README.md @@ -94,13 +94,19 @@ deno run -A main.ts --from 26.0.0 generate md # 将每个配置的文章合并导出为 Markdown deno run -A main.ts generate md +# 导出为 HTML(图片直接内嵌,路径从 md.path 派生) +deno run -A main.ts generate html + # 根据 md.path 导出为纯文本(输出文件名中的 md 会替换为 txt) deno run -A main.ts generate txt -# 按配置中的 publication 生成 EPUB 3,包含可点击目录 +# 按配置中的 publication 生成 EPUB 3,包含可点击目录和 EPUB 包内图片 deno run -A main.ts generate epub ``` +Markdown 和 HTML 导出会将本地图片嵌入为 Base64 data URL。EPUB 不使用 data URL, +而是将图片作为 EPUB 包内资源保存并从章节引用,兼容 EPUB 阅读器的资源模型。 + EPUB 默认使用 `md.path` 将扩展名替换为 `.epub`;也可在每个配置中设置 `[settings.epub]` 的 `path`、`title`、`author` 和 `language`。每篇文章会拆成独立章节, EPUB 导航目录按出版物排序链接到各章节。 diff --git a/tools/gp/cli/handlers.ts b/tools/gp/cli/handlers.ts index 41fc86d..f673c06 100644 --- a/tools/gp/cli/handlers.ts +++ b/tools/gp/cli/handlers.ts @@ -131,6 +131,25 @@ export async function generate_md() { } } +export async function generate_html() { + await cacheBeforeGeneration(); + for (const config of selectedConfigs()) { + const builder = new DocuBuilder( + config, + await createTemplateVariables(args, config, cfg.vars), + ); + builder.with_files_sync(config.journal.from_directory); + const html = await builder.as_html_page(); + const markdownPath = config.md?.path ?? config.markdown_output; + if (!markdownPath) { + throw new Error("Missing output path in config. Use md.path."); + } + const htmlPath = markdownPath.replace(/\.md$/i, ".html"); + await Deno.writeTextFile(htmlPath, html); + console.log(`Generated HTML: ${htmlPath}`); + } +} + export async function generate_txt() { await cacheBeforeGeneration(); try { diff --git a/tools/gp/cli/match.ts b/tools/gp/cli/match.ts index 855fa13..9b52f5f 100644 --- a/tools/gp/cli/match.ts +++ b/tools/gp/cli/match.ts @@ -1,5 +1,6 @@ import { generate_epub, + generate_html, generate_md, generate_pdf, generate_txt, @@ -35,6 +36,9 @@ export async function match_sub_command_to_function( case "md": await generate_md(); break; + case "html": + await generate_html(); + break; case "txt": await generate_txt(); break; diff --git a/tools/gp/epub_builder.ts b/tools/gp/epub_builder.ts index 89d9869..a198211 100644 --- a/tools/gp/epub_builder.ts +++ b/tools/gp/epub_builder.ts @@ -240,28 +240,34 @@ export class EpubBuilder { sourceDir, decodeURIComponent(sourceUrl.split(/[?#]/, 1)[0]), ); + const assetMarker = sourceUrl.match(/(?:^|\/)assets\/(.+)$/i); + const sharedAsset = assetMarker && this.config.asset_base + ? resolve(this.config.asset_base, assetMarker[1]) + : undefined; + const resolvedAsset = sharedAsset && await Deno.stat(sharedAsset) + .then((info) => info.isFile ? sharedAsset : undefined) + .catch(() => undefined) || sourceAsset; if (knownTargets.has(sourceAsset)) continue; - if ( - !sourceAsset.startsWith( - `${resolve(this.config.journal.from_directory)}${sep}`, - ) - ) continue; + const localAsset = resolvedAsset.startsWith( + `${resolve(this.config.journal.from_directory)}${sep}`, + ) || (sharedAsset != null && resolvedAsset === sharedAsset); + if (!localAsset) continue; try { - const info = await Deno.stat(sourceAsset); + const info = await Deno.stat(resolvedAsset); if (!info.isFile) continue; } catch { continue; } - const destination = mediaBySource.get(sourceAsset) ?? + const destination = mediaBySource.get(resolvedAsset) ?? `media/${index}/${media.length + 1}${ - extname(sourceAsset).toLowerCase() + extname(resolvedAsset).toLowerCase() }`; - if (!mediaBySource.has(sourceAsset)) { - mediaBySource.set(sourceAsset, destination); - const ext = extname(sourceAsset).toLowerCase(); + if (!mediaBySource.has(resolvedAsset)) { + mediaBySource.set(resolvedAsset, destination); + const ext = extname(resolvedAsset).toLowerCase(); media.push({ href: destination, - bytes: await Deno.readFile(sourceAsset), + bytes: await Deno.readFile(resolvedAsset), mime: mediaType(ext), }); } diff --git a/tools/gp/epub_builder_test.ts b/tools/gp/epub_builder_test.ts index f367bac..0a901ea 100644 --- a/tools/gp/epub_builder_test.ts +++ b/tools/gp/epub_builder_test.ts @@ -79,3 +79,87 @@ Deno.test("uses EPUB output path or a stable default", () => { }); assertEquals(builder.outputPath(), "./outputs/book.epub"); }); + +Deno.test("bundles shared assets referenced by publication articles", async () => { + const root = await Deno.makeTempDir(); + const publication = `${root}/publication`; + const templates = `${root}/templates`; + const assets = `${root}/assets`; + const output = `${root}/shared-assets.epub`; + await Deno.mkdir(`${publication}/1::专栏`, { recursive: true }); + await Deno.mkdir(templates, { recursive: true }); + await Deno.mkdir(`${assets}/pictures`, { recursive: true }); + await Deno.writeTextFile( + `${publication}/1::专栏/1::文章.md`, + "![共享图片](../../../assets/pictures/shared.png)", + ); + const imageBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + await Deno.writeFile(`${assets}/pictures/shared.png`, imageBytes); + const builder = new EpubBuilder({ + asset_base: assets, + journal: { + build_mode: "detached", + from_directory: publication, + template_directory: templates, + }, + epub: { path: output }, + }).with_files_sync(); + + try { + await builder.build(); + const archive = inspectEpub(await Deno.readFile(output)); + const chapter = new TextDecoder().decode( + archive["EPUB/text/0001-文章.xhtml"], + ); + assertStringIncludes(chapter, "../media/1/1.png"); + assertEquals( + [...archive["EPUB/media/1/1.png"]], + [...imageBytes], + ); + } finally { + await Deno.remove(root, { recursive: true }); + } +}); + +Deno.test("packages shared assets directory images as EPUB resources", async () => { + const root = await Deno.makeTempDir(); + const publication = `${root}/publication`; + const templates = `${root}/templates`; + const assets = `${root}/assets`; + const output = `${root}/shared-assets.epub`; + await Deno.mkdir(`${publication}/1::专栏`, { recursive: true }); + await Deno.mkdir(templates, { recursive: true }); + await Deno.mkdir(`${assets}/pictures`, { recursive: true }); + await Deno.writeTextFile( + `${publication}/1::专栏/1::文章.md`, + "![共享图片](../../../assets/pictures/shared.png)", + ); + const imageBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + await Deno.writeFile(`${assets}/pictures/shared.png`, imageBytes); + const builder = new EpubBuilder({ + asset_base: assets, + journal: { + build_mode: "detached", + from_directory: publication, + template_directory: templates, + identifier: "urn:test:shared-assets", + }, + epub: { path: output }, + }).with_files_sync(); + + try { + await builder.build(); + const zip = inspectEpub(await Deno.readFile(output)); + const chapter = new TextDecoder().decode( + zip["EPUB/text/0001-文章.xhtml"], + ); + assertStringIncludes(chapter, "../media/1/1.png"); + assertEquals(zip["EPUB/media/1/1.png"], imageBytes); + assertStringIncludes( + new TextDecoder().decode(zip["EPUB/content.opf"]), + 'media/1/1.png" media-type="image/png"', + ); + } finally { + await Deno.remove(root, { recursive: true }); + } +}); diff --git a/tools/gp/pdf_builder/asset_loading_test.ts b/tools/gp/pdf_builder/asset_loading_test.ts index a965778..0cb323a 100644 --- a/tools/gp/pdf_builder/asset_loading_test.ts +++ b/tools/gp/pdf_builder/asset_loading_test.ts @@ -1,5 +1,6 @@ import { assertEquals } from "@std/assert"; import { DocuBuilder } from "./docu_builder.ts"; +import { md } from "../mdit/md.ts"; Deno.test("PDF rendering loads relative assets from configured file base", async () => { const chromiumPath = Deno.env.get("CHROMIUM_PATH"); @@ -24,3 +25,65 @@ Deno.test("PDF rendering loads relative assets from configured file base", async assertEquals((await Deno.stat(pdfPath)).size > 0, true); await Deno.remove(pdfPath); }); + +Deno.test("PDF rendering waits for remote Markdown images", async () => { + if (!Deno.env.get("CHROMIUM_PATH")) return; + + const builder = new DocuBuilder({ + asset_base: "../../assets", + journal: { build_js_script: false }, + }); + const pdfPath = await Deno.makeTempFile({ suffix: ".pdf" }); + await builder.with_browser(); + try { + await builder.build_as_pdf({ path: pdfPath, format: "A4" }, [ + 'Remote asset', + ]); + } finally { + await builder.close_browser(); + } + assertEquals((await Deno.stat(pdfPath)).size > 0, true); + await Deno.remove(pdfPath); +}); + +Deno.test("PDF rendering embeds publication-relative asset images", async () => { + if (!Deno.env.get("CHROMIUM_PATH")) return; + + const builder = new DocuBuilder({ + asset_base: "../../assets", + journal: { build_js_script: false }, + }); + const resolvedHtml = (builder as any).resolveLocalAssetImages( + '' + + '', + ); + assertEquals( + resolvedHtml.includes('src="data:image/png;base64,'), + true, + ); + assertEquals( + resolvedHtml.includes('src="https://example.test/remote.png"'), + true, + ); + assertEquals(resolvedHtml.includes('loading="eager"'), false); + const markdownHtml = md.render( + "![Publication asset](../../../assets/pictures/rsf.png)", + ); + const eagerHtml = (builder as any).resolveLocalAssetImages(markdownHtml); + assertEquals(eagerHtml.includes('loading="lazy"'), false); + assertEquals(eagerHtml.includes('loading="eager"'), true); + const pdfPath = await Deno.makeTempFile({ suffix: ".pdf" }); + await builder.with_browser(); + try { + await builder.build_as_pdf({ path: pdfPath, format: "A4" }, [ + (builder as any).resolveLocalAssetImages( + 'Publication asset', + ), + ]); + } finally { + await builder.close_browser(); + } + const pdfText = new TextDecoder().decode(await Deno.readFile(pdfPath)); + assertEquals(pdfText.includes("/Subtype /Image"), true); + await Deno.remove(pdfPath); +}); diff --git a/tools/gp/pdf_builder/docu_builder.ts b/tools/gp/pdf_builder/docu_builder.ts index 7e3b583..98c55a4 100644 --- a/tools/gp/pdf_builder/docu_builder.ts +++ b/tools/gp/pdf_builder/docu_builder.ts @@ -81,6 +81,49 @@ export class DocuBuilder { .trim(); } + private resolveLocalAssetImages(html: string): string { + const eagerHtml = html.replace( + /(]*\sloading=["'])lazy(["'])/gi, + "$1eager$2", + ); + return eagerHtml.replace( + /(]*\bsrc=["'])([^"']+)(["'])/gi, + (_match, prefix: string, source: string, suffix: string) => { + const assetMarker = source.match(/(?:^|\/)assets\/(.+)$/i); + if (/^[a-z][a-z\d+.-]*:/i.test(source)) { + return `${prefix}${source}${suffix}`; + } + try { + const assetUrl = assetMarker + ? new URL(assetMarker[1], this.assetBaseHref) + : new URL(source, this.assetBaseHref); + const bytes = Deno.readFileSync(assetUrl); + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode( + ...bytes.subarray(offset, offset + 0x8000), + ); + } + const extension = assetUrl + .pathname.split(".").at(-1)?.toLowerCase(); + const mime = extension === "png" + ? "image/png" + : extension === "webp" + ? "image/webp" + : extension === "gif" + ? "image/gif" + : "image/jpeg"; + return `${prefix}data:${mime};base64,${btoa(binary)}${suffix}`; + } catch (error) { + console.warn(`Could not embed local image ${source}: ${error}`); + return `${prefix}${ + assetMarker ? `${this.assetBaseHref}${assetMarker[1]}` : source + }${suffix}`; + } + }, + ); + } + async as_markdown() { const turndownService = new TurndownService(); const html_page = await this.as_html_page(); @@ -125,17 +168,20 @@ export class DocuBuilder { ); colume.pfiles.forEach((pfile) => { const passageId = id++; - const html = md.render(this.render(pfile.content, { - document: { - title: pfile.meta.title, - index: pfile.meta.index, - file: pfile.full_name, - }, - column: { - name: colume.name, - index: colume.index, - }, - })); + const firstPassageClass = c_id === 1 ? " first-passage" : ""; + const html = this.resolveLocalAssetImages( + md.render(this.render(pfile.content, { + document: { + title: pfile.meta.title, + index: pfile.meta.index, + file: pfile.full_name, + }, + column: { + name: colume.name, + index: colume.index, + }, + })), + ); let foundHeading = false; const indexedHtml = html.replace( /]*)>([\s\S]*?)<\/h1>/i, @@ -151,7 +197,7 @@ export class DocuBuilder { ); const printableHtml = markedHtml; this.pages.push( - `
${printableHtml}
`, + `
${printableHtml}
`, ); }); }); @@ -266,7 +312,53 @@ return document?.documentElement?.outerHTML ?? html;`, const htmlPath = await Deno.makeTempFile({ suffix: ".html" }); try { await Deno.writeTextFile(htmlPath, htmlWithBase); - await page.goto(pathToFileURL(htmlPath).href, { timeout: 120000 }); + await page.goto(pathToFileURL(htmlPath).href, { + timeout: 120000, + waitUntil: "domcontentloaded", + }); + + // `page.goto(..., { waitUntil: "load" })` does not guarantee that + // every image has finished decoding before printing. Wait for each + // image explicitly so remote Markdown images are included in the PDF. + const failedImages = await page.evaluate(async () => { + // The project is type-checked without the DOM library; these values + // live in Chromium's page context, not in the Deno runtime. + const pageDocument = (globalThis as any).document; + const images = Array.from(pageDocument.images) as any[]; + const timedOutImages = await Promise.all(images.map((image) => { + if (image.complete) return Promise.resolve(false); + return new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(timeout); + resolve(false); + }; + const timeout = setTimeout(() => { + if (settled) return; + settled = true; + resolve(true); + }, 15000); + image.addEventListener("load", finish, { once: true }); + image.addEventListener("error", finish, { once: true }); + }); + })); + const failed = images + .filter((image) => !image.naturalWidth) + .map((image) => image.currentSrc || image.src); + return failed.length > 0 + ? failed + : images.filter((_image, index) => timedOutImages[index]) + .map((image) => image.currentSrc || image.src); + }); + if (failedImages.length > 0) { + console.warn( + `Continuing PDF generation with ${failedImages.length} image(s) not loaded within 15 seconds: ${ + failedImages.join(", ") + }`, + ); + } await page.pdf(pw_config); } finally {