返回 slidev
export.ts
根目录 / packages / slidev / node / commands / export.ts
1 import type { ExportArgs, ResolvedSlidevOptions, SlideInfo, SlidevConfig, TocItem } from '@slidev/types'
2 import { Buffer } from 'node:buffer'
3 import fs from 'node:fs/promises'
4 import process from 'node:process'
5 import { clearUndefined, ensureSuffix, slash } from '@antfu/utils'
6 import { outlinePdfFactory } from '@lillallol/outline-pdf'
7 import { parseRangeString } from '@slidev/parser/core'
8 import { blue, cyan, dim, green, yellow } from 'ansis'
9 import { Presets, SingleBar } from 'cli-progress'
10 import { resolve } from 'mlly'
11 import path, { dirname, relative } from 'pathe'
12 import * as pdfLib from 'pdf-lib'
13 import { PDFDocument } from 'pdf-lib'
14 import { getRoots } from '../resolver'
15
16 const RE_CLICKS_PARAM = /clicks=([1-9]\d*)/
17
18 export interface ExportOptions {
19 total: number
20 range?: string
21 slides: SlideInfo[]
22 port?: number
23 base?: string
24 format?: 'pdf' | 'png' | 'pptx' | 'pptx-editable' | 'md'
25 output?: string
26 timeout?: number
27 wait?: number
28 waitUntil: 'networkidle' | 'load' | 'domcontentloaded' | undefined
29 dark?: boolean
30 routerMode?: 'hash' | 'history'
31 width?: number
32 height?: number
33 withClicks?: boolean
34 executablePath?: string
35 withToc?: boolean
36 /**
37 * Render slides slide by slide. Works better with global components, but will break cross slide links and TOC in PDF.
38 * @default false
39 */
40 perSlide?: boolean
41 scale?: number
42 omitBackground?: boolean
43 }
44
45 export function resolveExportDarkMode(dark: boolean | undefined, colorSchema: SlidevConfig['colorSchema']) {
46 if (colorSchema === 'light dark' || colorSchema === 'dark light')
47 return dark ?? colorSchema === 'dark light'
48 return dark || colorSchema === 'dark'
49 }
50
51 interface ExportPngResult {
52 slideIndex: number
53 buffer: Buffer
54 filename: string
55 }
56
57 function addToTree(tree: TocItem[], info: SlideInfo, slideIndexes: Record<number, number>, level = 1) {
58 const titleLevel = info.level
59 if (titleLevel && titleLevel > level && tree.length > 0 && tree[tree.length - 1].titleLevel < titleLevel) {
60 addToTree(tree[tree.length - 1].children, info, slideIndexes, level + 1)
61 }
62 else {
63 tree.push({
64 no: info.index,
65 children: [],
66 level,
67 titleLevel: titleLevel ?? level,
68 path: String(slideIndexes[info.index + 1]),
69 hideInToc: Boolean(info.frontmatter?.hideInToc),
70 title: info.title,
71 })
72 }
73 }
74
75 function makeOutline(tree: TocItem[]): string {
76 return tree.map(({ title, path, level, children }) => {
77 const rootOutline = title
78 ? `${path}|${'-'.repeat(level - 1)}|${title}`
79 : null
80
81 const childrenOutline = makeOutline(children)
82
83 return childrenOutline.length > 0
84 ? `${rootOutline}\n${childrenOutline}`
85 : rootOutline
86 }).filter(outline => !!outline).join('\n')
87 }
88
89 export interface ExportNotesOptions {
90 port?: number
91 base?: string
92 output?: string
93 timeout?: number
94 wait?: number
95 }
96
97 function createSlidevProgress(indeterminate = false) {
98 function getSpinner(n = 0) {
99 return [
100 cyan('●'),
101 green('◆'),
102 blue('■'),
103 yellow('▲'),
104 ][n % 4]
105 }
106 let current = 0
107 let spinner = 0
108 let timer: any
109
110 const progress = new SingleBar({
111 clearOnComplete: true,
112 hideCursor: true,
113 format: ` {spin} ${yellow('rendering')}${indeterminate
114 ? dim(yellow('...'))
115 : ' {bar} {value}/{total}'}`,
116 linewrap: false,
117 barsize: 30,
118 }, Presets.shades_grey)
119
120 return {
121 bar: progress,
122 start(total: number) {
123 progress.start(total, 0, {
124 spin: getSpinner(spinner),
125 })
126 timer = setInterval(() => {
127 spinner += 1
128 progress.update(current, {
129 spin: getSpinner(spinner),
130 })
131 }, 200)
132 },
133 update(v: number) {
134 current = v
135 progress.update(v, {
136 spin: getSpinner(spinner),
137 })
138 },
139 stop() {
140 clearInterval(timer)
141 progress.stop()
142 },
143 }
144 }
145
146 export async function exportNotes({
147 port = 18724,
148 base = '/',
149 output = 'notes',
150 timeout = 30000,
151 wait = 0,
152 }: ExportNotesOptions): Promise<string> {
153 const { chromium } = await importPlaywright()
154 const browser = await chromium.launch()
155 const context = await browser.newContext()
156 const page = await context.newPage()
157
158 const progress = createSlidevProgress(true)
159
160 progress.start(1)
161
162 if (!output.endsWith('.pdf'))
163 output = `${output}.pdf`
164
165 try {
166 await page.goto(`http://localhost:${port}${base}presenter/print`, { waitUntil: 'networkidle', timeout })
167 await page.waitForLoadState('networkidle')
168 await page.emulateMedia({ media: 'screen' })
169
170 if (wait)
171 await page.waitForTimeout(wait)
172
173 await page.pdf({
174 path: output,
175 margin: {
176 left: 0,
177 top: 0,
178 right: 0,
179 bottom: 0,
180 },
181 printBackground: true,
182 preferCSSPageSize: true,
183 })
184 }
185 finally {
186 progress.stop()
187 await browser.close()
188 }
189
190 return output
191 }
192
193 export async function exportSlides({
194 port = 18724,
195 total = 0,
196 range,
197 format = 'pdf',
198 output = 'slides',
199 slides,
200 base = '/',
201 timeout = 30000,
202 wait = 0,
203 dark = false,
204 routerMode = 'history',
205 width = 1920,
206 height = 1080,
207 withClicks = false,
208 executablePath = undefined,
209 withToc = false,
210 perSlide = false,
211 scale = 1,
212 waitUntil,
213 omitBackground = false,
214 }: ExportOptions) {
215 const pages: number[] = parseRangeString(total, range)
216
217 // Writers disagree about who creates the parent directory of `--output`, so
218 // the ones calling `fs.writeFile` directly failed with ENOENT on a path like
219 // `dist/slides.pptx`. Create it here, before the browser starts. `png` gets
220 // only the parent: its `--output` is a directory that `genPagePng` creates.
221 await fs.mkdir(dirname(path.resolve(output)), { recursive: true })
222
223 const { chromium } = await importPlaywright()
224 const browser = await chromium.launch({
225 executablePath,
226 })
227 const context = await browser.newContext({
228 viewport: {
229 width,
230 // Calculate height for every slides to be in the viewport to trigger the rendering of iframes (twitter, youtube...)
231 height: perSlide
232 ? height
233 : height * pages.length,
234 },
235 deviceScaleFactor: scale,
236 })
237 const page = await context.newPage()
238 const progress = createSlidevProgress(!perSlide)
239 progress.start(pages.length)
240
241 try {
242 if (format === 'pdf') {
243 await genPagePdf()
244 }
245 else if (format === 'png') {
246 await genPagePng(output)
247 }
248 else if (format === 'md') {
249 await genPageMd()
250 }
251 else if (format === 'pptx') {
252 const buffers = await genPagePng(false)
253 await genPagePptx(buffers)
254 }
255 else if (format === 'pptx-editable') {
256 await genPagePptxEditable()
257 }
258 else {
259 throw new Error(`[slidev] Unsupported exporting format "${format}"`)
260 }
261 }
262 finally {
263 progress.stop()
264 await browser.close()
265 }
266
267 const relativeOutput = slash(relative('.', output))
268 return relativeOutput.startsWith('.')
269 ? relativeOutput
270 : `./${relativeOutput}`
271
272 async function go(no: number | string, clicks?: string) {
273 const query = new URLSearchParams()
274 if (withClicks)
275 query.set('print', 'clicks')
276 else
277 query.set('print', 'true')
278 if (range)
279 query.set('range', range)
280 if (clicks)
281 query.set('clicks', clicks)
282
283 const url = routerMode === 'hash'
284 ? `http://localhost:${port}${base}?${query}#${no}`
285 : `http://localhost:${port}${base}${no}?${query}`
286 await page.goto(url, {
287 waitUntil,
288 timeout,
289 })
290 if (waitUntil)
291 await page.waitForLoadState(waitUntil)
292 await page.emulateMedia({
293 colorScheme: dark ? 'dark' : 'light',
294 media: 'screen',
295 })
296 const slide = no === 'print'
297 ? page.locator('body')
298 : page.locator(`[data-slidev-no="${no}"]`)
299 await slide.waitFor()
300
301 // Wait for slides to be loaded
302 {
303 const elements = slide.locator('.slidev-slide-loading')
304 const count = await elements.count()
305 for (let index = 0; index < count; index++)
306 await elements.nth(index).waitFor({ state: 'detached' })
307 }
308 // Check for "data-waitfor" attribute and wait for given element to be loaded
309 {
310 const elements = slide.locator('[data-waitfor]')
311 const count = await elements.count()
312 for (let index = 0; index < count; index++) {
313 const element = elements.nth(index)
314 const attribute = await element.getAttribute('data-waitfor')
315 if (attribute) {
316 await element.locator(attribute).waitFor({ state: 'visible' }).catch((e) => {
317 console.error(e)
318 process.exitCode = 1
319 })
320 }
321 }
322 }
323 // Wait for frames to load
324 {
325 const frames = page.frames()
326 await Promise.all(frames.map(frame => frame.waitForLoadState(undefined, { timeout })))
327 }
328 // Wait for Mermaid graphs to be rendered
329 {
330 const container = slide.locator('#mermaid-rendering-container')
331 const count = await container.count()
332 if (count > 0) {
333 while (true) {
334 const element = container.locator('div').first()
335 if (await element.count() === 0)
336 break
337 await element.waitFor({ state: 'detached' })
338 }
339 await container.evaluate(node => node.style.display = 'none')
340 }
341 }
342 // Hide Monaco aria container
343 {
344 const elements = slide.locator('.monaco-aria-container')
345 const count = await elements.count()
346 for (let index = 0; index < count; index++) {
347 const element = elements.nth(index)
348 await element.evaluate(node => node.style.display = 'none')
349 }
350 }
351 // Wait for the given time
352 if (wait)
353 await page.waitForTimeout(wait)
354 }
355
356 async function getSlidesIndex() {
357 const clicksBySlide: Record<string, number> = {}
358 const slides = page.locator('.print-slide-container')
359 const count = await slides.count()
360 for (let i = 0; i < count; i++) {
361 const id = (await slides.nth(i).getAttribute('id')) || ''
362 const path = Number(id.split('-')[0])
363 clicksBySlide[path] = (clicksBySlide[path] || 0) + 1
364 }
365
366 const slideIndexes = Object.fromEntries(Object.entries(clicksBySlide)
367 .reduce<[string, number][]>((acc, [path, clicks], i) => {
368 acc.push([path, clicks + (acc[i - 1]?.[1] ?? 0)])
369 return acc
370 }, []))
371 return slideIndexes
372 }
373
374 function getClicksFromUrl(url: string) {
375 return url.match(RE_CLICKS_PARAM)?.[1]
376 }
377
378 async function genPageWithClicks(
379 fn: (no: number, clicks?: string) => Promise<any>,
380 no: number,
381 clicks?: string,
382 ) {
383 await fn(no, clicks)
384 if (withClicks) {
385 await page.keyboard.press('ArrowRight', { delay: 100 })
386 const _clicks = getClicksFromUrl(page.url())
387 if (_clicks && clicks !== _clicks)
388 await genPageWithClicks(fn, no, _clicks)
389 }
390 }
391
392 async function genPagePdfPerSlide() {
393 const buffers: Buffer[] = []
394 const genPdfBuffer = async (i: number, clicks?: string) => {
395 await go(i, clicks)
396 const pdf = await page.pdf({
397 width,
398 height,
399 margin: {
400 left: 0,
401 top: 0,
402 right: 0,
403 bottom: 0,
404 },
405 pageRanges: '1',
406 printBackground: true,
407 preferCSSPageSize: true,
408 })
409 buffers.push(pdf)
410 }
411 let idx = 0
412 for (const i of pages) {
413 await genPageWithClicks(genPdfBuffer, i)
414 progress.update(++idx)
415 }
416
417 let mergedPdf = await PDFDocument.create({})
418 for (const pdfBytes of buffers) {
419 const pdf = await PDFDocument.load(pdfBytes)
420 const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices())
421 copiedPages.forEach((page) => {
422 mergedPdf.addPage(page)
423 })
424 }
425
426 // Edit generated PDF: add metadata and (optionally) TOC
427 addPdfMetadata(mergedPdf)
428
429 if (withToc)
430 mergedPdf = await addTocToPdf(mergedPdf)
431
432 const buffer = await mergedPdf.save()
433 await fs.writeFile(output, buffer)
434 }
435
436 async function genPagePdfOnePiece() {
437 await go('print')
438 await page.pdf({
439 path: output,
440 width,
441 height,
442 margin: {
443 left: 0,
444 top: 0,
445 right: 0,
446 bottom: 0,
447 },
448 printBackground: true,
449 preferCSSPageSize: true,
450 })
451
452 // Edit generated PDF: add metadata and (optionally) TOC
453 let pdfData = await fs.readFile(output)
454 let pdf = await PDFDocument.load(pdfData)
455
456 addPdfMetadata(pdf)
457
458 if (withToc)
459 pdf = await addTocToPdf(pdf)
460
461 pdfData = Buffer.from(await pdf.save())
462 await fs.writeFile(output, pdfData)
463 }
464
465 async function genPagePngOnePiece(writeToDisk: string | false) {
466 const result: ExportPngResult[] = []
467 await go('print')
468 const slideContainers = page.locator('.print-slide-container')
469 const count = await slideContainers.count()
470
471 for (let i = 0; i < count; i++) {
472 const id = (await slideContainers.nth(i).getAttribute('id')) || ''
473 const slideNo = +id.split('-')[0]
474
475 // Only process slides that are in the specified range
476 if (!pages.includes(slideNo))
477 continue
478
479 progress.update(result.length + 1)
480
481 const buffer = await slideContainers.nth(i).screenshot({
482 omitBackground,
483 })
484 const filename = `${withClicks ? id : slideNo}.png`
485 result.push({ slideIndex: slideNo - 1, buffer, filename })
486 if (writeToDisk)
487 await fs.writeFile(path.join(writeToDisk, filename), buffer)
488 }
489 return result
490 }
491
492 async function genPagePngPerSlide(writeToDisk: string | false) {
493 const result: ExportPngResult[] = []
494 const genScreenshot = async (no: number, clicks?: string) => {
495 await go(no, clicks)
496 const buffer = await page.screenshot({
497 omitBackground,
498 })
499 const filename = `${no.toString().padStart(2, '0')}${clicks
500 ? `-${clicks}`
501 : ''}.png`
502 result.push({ slideIndex: no - 1, buffer, filename })
503 if (writeToDisk) {
504 await fs.writeFile(
505 path.join(writeToDisk, filename),
506 buffer,
507 )
508 }
509 }
510 for (const no of pages)
511 await genPageWithClicks(genScreenshot, no)
512 return result
513 }
514
515 function genPagePdf() {
516 if (!output.endsWith('.pdf'))
517 output = `${output}.pdf`
518 return perSlide
519 ? genPagePdfPerSlide()
520 : genPagePdfOnePiece()
521 }
522
523 async function genPagePng(writeToDisk: string | false, cleanOutput = true) {
524 if (writeToDisk) {
525 if (cleanOutput)
526 await fs.rm(writeToDisk, { force: true, recursive: true })
527 await fs.mkdir(writeToDisk, { recursive: true })
528 }
529 return perSlide
530 ? genPagePngPerSlide(writeToDisk)
531 : genPagePngOnePiece(writeToDisk)
532 }
533
534 async function genPageMd() {
535 const pngs = await genPagePng(dirname(output), false)
536 const content = slides
537 .filter(({ index }) => pages.includes(index + 1))
538 .map(({ title, index, note }) =>
539 pngs.filter(({ slideIndex }) => slideIndex === index)
540 .map(({ filename }) => `![${title || (index + 1)}](./${filename})\n\n`)
541 .join('')
542 + (note
543 ? `${note.trim()}\n\n`
544 : ''),
545 )
546 .join('---\n\n')
547 await fs.writeFile(ensureSuffix('.md', output), content)
548 }
549
550 // Ported from https://github.com/marp-team/marp-cli/blob/main/src/converter.ts
551 async function genPagePptx(pngs: ExportPngResult[]) {
552 const { default: PptxGenJS } = await import('pptxgenjs')
553 const pptx = new PptxGenJS()
554
555 const layoutName = `${width}x${height}`
556 pptx.defineLayout({
557 name: layoutName,
558 width: width / 96,
559 height: height / 96,
560 })
561 pptx.layout = layoutName
562
563 const titleSlide = slides[0]
564 pptx.author = titleSlide?.frontmatter?.author
565 pptx.company = 'Created using Slidev'
566 if (titleSlide?.title)
567 pptx.title = titleSlide?.title
568 if (titleSlide?.frontmatter?.info)
569 pptx.subject = titleSlide?.frontmatter?.info
570
571 pngs.forEach(({ slideIndex, buffer }) => {
572 const slide = pptx.addSlide()
573 slide.background = {
574 data: `data:image/png;base64,${buffer.toString('base64')}`,
575 }
576
577 const note = slides[slideIndex].note
578 if (note)
579 slide.addNotes(note)
580 })
581
582 const buffer = await pptx.write({
583 outputType: 'nodebuffer',
584 }) as Buffer
585 if (!output.endsWith('.pptx'))
586 output = `${output}.pptx`
587 await fs.writeFile(output, buffer)
588 }
589
590 // Native shapes and editable text, rather than one picture per slide. The
591 // walker, normalizer and builder live in ./pptx, so this is a delegation.
592 async function genPagePptxEditable() {
593 if (perSlide) {
594 // Per-slide mode never renders the print page the measurement depends
595 // on. Failing beats writing a deck missing every slide but the first.
596 throw new Error('[slidev] `--per-slide` is not supported with `--format pptx-editable`')
597 }
598
599 const { exportPptxEditable, reportEditableExport } = await import('./pptx')
600 const result = await exportPptxEditable({
601 page,
602 slides,
603 width,
604 height,
605 pages,
606 go,
607 }, output)
608 // So the "exported to ..." line names the file that was actually written.
609 output = result.output
610
611 // The progress bar repaints on a timer with the cursor hidden, so anything
612 // written while it runs is interleaved with it or overwritten.
613 progress.stop()
614 reportEditableExport(result)
615 }
616
617 // Adds metadata (title, author, keywords) to PDF document, mutating it
618 function addPdfMetadata(pdf: PDFDocument): void {
619 const titleSlide = slides[0]
620 if (titleSlide?.title)
621 pdf.setTitle(titleSlide.title)
622 if (titleSlide?.frontmatter?.info)
623 pdf.setSubject(titleSlide.frontmatter.info)
624 if (titleSlide?.frontmatter?.author)
625 pdf.setAuthor(titleSlide.frontmatter.author)
626 if (titleSlide?.frontmatter?.keywords) {
627 if (Array.isArray(titleSlide?.frontmatter?.keywords))
628 pdf.setKeywords(titleSlide?.frontmatter?.keywords)
629 else
630 pdf.setKeywords(titleSlide?.frontmatter?.keywords.split(','))
631 }
632 }
633
634 async function addTocToPdf(pdf: PDFDocument): Promise<PDFDocument> {
635 const outlinePdf = outlinePdfFactory(pdfLib)
636 const slideIndexes = await getSlidesIndex()
637
638 const tocTree = slides.filter(slide => slide.title)
639 .reduce((acc: TocItem[], slide) => {
640 addToTree(acc, slide, slideIndexes)
641 return acc
642 }, [])
643
644 const outline = makeOutline(tocTree)
645
646 return await outlinePdf({ outline, pdf })
647 }
648 }
649
650 export function getExportOptions(args: ExportArgs, options: ResolvedSlidevOptions, outFilename?: string): Omit<ExportOptions, 'port' | 'base'> {
651 const config = {
652 ...options.data.config.export,
653 ...args,
654 ...clearUndefined({
655 waitUntil: args['wait-until'],
656 withClicks: args['with-clicks'],
657 executablePath: args['executable-path'],
658 withToc: args['with-toc'],
659 perSlide: args['per-slide'],
660 omitBackground: args['omit-background'],
661 }),
662 }
663 const {
664 entry,
665 output,
666 format,
667 timeout,
668 wait,
669 waitUntil,
670 range,
671 dark,
672 withClicks,
673 executablePath,
674 withToc,
675 perSlide,
676 scale,
677 omitBackground,
678 } = config
679 outFilename = output || outFilename || options.data.config.exportFilename || `${path.basename(entry, '.md')}-export`
680 return {
681 output: outFilename,
682 slides: options.data.slides,
683 total: options.data.slides.length,
684 range,
685 format: (format || 'pdf') as 'pdf' | 'png' | 'pptx' | 'pptx-editable' | 'md',
686 timeout: timeout ?? 30000,
687 wait: wait ?? 0,
688 waitUntil: waitUntil === 'none'
689 ? undefined
690 : (waitUntil ?? 'networkidle') as 'networkidle' | 'load' | 'domcontentloaded',
691 dark: resolveExportDarkMode(dark, options.data.config.colorSchema),
692 // Export navigates by URL; memory routing ignores the URL, so fall back to history.
693 routerMode: options.data.config.routerMode === 'memory'
694 ? 'history'
695 : options.data.config.routerMode,
696 width: options.data.config.canvasWidth,
697 height: Math.round(options.data.config.canvasWidth / options.data.config.aspectRatio),
698 // Both pptx formats default to one slide per click step. Testing the
699 // exact string here silently collapsed click steps for the editable one.
700 withClicks: withClicks ?? !!format?.startsWith('pptx'),
701 executablePath,
702 withToc: withToc || false,
703 perSlide: perSlide || false,
704 scale: scale || 2,
705 omitBackground: omitBackground ?? false,
706 }
707 }
708
709 async function importPlaywright(): Promise<typeof import('playwright-chromium')> {
710 const { userRoot, userWorkspaceRoot } = await getRoots()
711
712 // 1. resolve from user root
713 try {
714 return await import(await resolve('playwright-chromium', { url: userRoot }))
715 }
716 catch { }
717
718 // 2. resolve from user workspace root
719 if (userWorkspaceRoot !== userRoot) {
720 try {
721 return await import(await resolve('playwright-chromium', { url: userWorkspaceRoot }))
722 }
723 catch { }
724 }
725
726 // 3. resolve from global registry
727 const { resolveGlobal } = await import('resolve-global')
728 try {
729 const imported = await import(resolveGlobal('playwright-chromium'))
730 return imported.default ?? imported
731 }
732 catch { }
733
734 // 4. resolve from current @slidev/cli installation
735 try {
736 return await import('playwright-chromium')
737 }
738 catch { }
739
740 throw new Error('The exporting for Slidev is powered by Playwright, please install it via `npm i -D playwright-chromium`')
741 }
742
742 lines TYPESCRIPT