Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert slide deck into PDF with Puppeteer #2

Merged
merged 10 commits into from
Aug 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ jobs:
'8.11.4':
<<: *base
docker:
- image: circleci/node:8.11.4
- image: circleci/node:8.11.4-browsers

'6.14.2':
<<: *base
docker:
- image: circleci/node:6.14.2
- image: circleci/node:6.14.2-browsers

workflows:
version: 2
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

- Convert slide deck into PDF with Puppeteer ([#2](https://github.com/marp-team/marp-cli/pull/2))

## v0.0.3 - 2018-08-22

### Added
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

**A CLI interface, for [Marp](https://github.com/marp-team/marp)** (using [@marp-team/marp-core](https://github.com/marp-team/marp-core)) and any slide deck converter based on [Marpit](https://github.com/marp-team/marpit) framework.

It can convert Marp / Marpit Markdown files to static HTML (and CSS).
It can convert Marp / Marpit Markdown files into static HTML (and CSS).

### :warning: _marp-cli is under construction and not ready to use stable._

Expand All @@ -16,9 +16,17 @@ It can convert Marp / Marpit Markdown files to static HTML (and CSS).
[npx](https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner) is the best tool when you want to convert Markdown right now. Just run below if you are installed [Node.js](https://nodejs.org/) >= 8.2.0:

```bash
# Convert slide deck into HTML
npx @marp-team/marp-cli slide-deck.md
npx @marp-team/marp-cli slide-deck.md -o output.html

# Convert slide deck into PDF
npx @marp-team/marp-cli slide-deck.md --pdf
npx @marp-team/marp-cli slide-deck.md -o output.pdf
```

> :information_source: You have to install [Google Chrome](https://www.google.com/chrome/) (or [Chromium](https://www.chromium.org/)) to convert slide deck into PDF.

## Install

### Global install
Expand Down Expand Up @@ -57,7 +65,7 @@ Under construction.
- [x] HTML templates
- [ ] Template that has ready to actual presentation powered by [Bespoke](https://github.com/bespokejs/bespoke)
- [ ] Select engine to use any Marpit based module
- [ ] Export PDF directly by using [Puppetter](https://github.com/GoogleChrome/puppeteer)
- [x] Export PDF directly by using [Puppeteer](https://github.com/GoogleChrome/puppeteer)

## Author

Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"@types/jest": "^23.3.1",
"@types/node": "^10.7.1",
"@types/pug": "^2.0.4",
"@types/puppeteer": "^1.6.0",
"@types/yargs": "^11.1.1",
"autoprefixer": "^9.1.2",
"codecov": "^3.0.4",
Expand Down Expand Up @@ -82,7 +83,10 @@
"@marp-team/marp-core": "^0.0.3",
"@marp-team/marpit": "^0.0.12",
"chalk": "^2.4.1",
"chrome-launcher": "^0.10.2",
"globby": "^8.0.1",
"is-wsl": "^1.1.0",
"puppeteer-core": "^1.7.0",
"yargs": "^12.0.1"
}
}
8 changes: 7 additions & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ import { dependencies } from './package.json'

export default [
{
external: [...Object.keys(dependencies), 'fs', 'path', 'yargs/yargs'],
external: [
...Object.keys(dependencies),
'fs',
'path',
'chrome-launcher/dist/chrome-finder',
'yargs/yargs',
],
input: 'src/marp-cli.ts',
output: {
exports: 'named',
Expand Down
80 changes: 59 additions & 21 deletions src/converter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { Marpit, MarpitRenderResult, MarpitOptions } from '@marp-team/marpit'
import { Marpit, MarpitOptions } from '@marp-team/marpit'
import * as chromeFinder from 'chrome-launcher/dist/chrome-finder'
import fs from 'fs'
import path from 'path'
import puppeteer, { PDFOptions } from 'puppeteer-core'
import { error } from './error'
import templates from './templates'
import templates, { TemplateResult } from './templates'

export enum ConvertType {
html = 'html',
pdf = 'pdf',
}

export interface ConverterOption {
engine: typeof Marpit
Expand All @@ -11,20 +18,24 @@ export interface ConverterOption {
readyScript?: string
template: string
theme?: string
type: ConvertType
}

export interface ConvertResult {
output: string
path: string
rendered: MarpitRenderResult
result: string
rendered: TemplateResult['rendered']
result: Buffer | TemplateResult['result']
}

export class Converter {
readonly options: ConverterOption

constructor(opts: ConverterOption) {
this.options = opts

if (opts.type === ConvertType.pdf && opts.output === '-')
error('PDF cannot output to stdout.')
}

get template() {
Expand All @@ -34,7 +45,7 @@ export class Converter {
return template
}

convert(markdown: string) {
convert(markdown: string): TemplateResult {
let additionals = ''

if (this.options.theme)
Expand All @@ -53,27 +64,44 @@ export class Converter {
)

const converted = this.convert(buffer.toString())
const output = this.outputPath(path)

if (output !== '-') {
const output = this.outputPath(path, this.options.type)
const result = await (async () => {
if (this.options.type === ConvertType.pdf) {
const browser = await Converter.runBrowser()

try {
const page = await browser.newPage()
await page.goto(`data:text/html,${converted.result}`, {
waitUntil: ['domcontentloaded', 'networkidle0'],
})

return await page.pdf(<PDFOptions>{
printBackground: true,
preferCSSPageSize: true,
})
} finally {
await browser.close()
}
}
return converted.result
})()

if (output !== '-')
await new Promise<void>((resolve, reject) =>
fs.writeFile(output, converted.result, e => (e ? reject(e) : resolve()))
fs.writeFile(output, result, e => (e ? reject(e) : resolve()))
)
}

return {
output,
path,
rendered: converted.rendered,
result: converted.result,
}

return { output, path, result, rendered: converted.rendered }
}

convertFiles(...files: string[]) {
async convertFiles(
files: string[],
onConverted: (result: ConvertResult) => void = () => {}
): Promise<void> {
if (this.options.output && this.options.output !== '-' && files.length > 1)
error('Output path cannot specify with processing multiple files')
error('Output path cannot specify with processing multiple files.')

return Promise.all(files.map(fn => this.convertFile(fn)))
for (const file of files) onConverted(await this.convertFile(file))
}

private generateEngine(mergeOptions: MarpitOptions) {
Expand All @@ -88,12 +116,22 @@ export class Converter {
return engine
}

private outputPath(from: string, extension = 'html'): string {
private outputPath(from: string, extension: string): string {
if (this.options.output) return this.options.output

return path.join(
path.dirname(from),
`${path.basename(from, path.extname(from))}.${extension}`
)
}

private static runBrowser() {
const finder: () => string[] = require('is-wsl')
? chromeFinder.wsl
: chromeFinder[process.platform]

return puppeteer.launch({
executablePath: finder ? finder()[0] : undefined,
})
}
}
9 changes: 7 additions & 2 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
export class CLIError implements Error {
name = 'CLIError'
readonly errorCode: number
readonly message: string
readonly name = 'CLIError'

constructor(public message: string, public errorCode: number = 1) {}
constructor(message: string, errorCode: number = 1) {
this.message = message
this.errorCode = errorCode
}

toString() {
return this.message
Expand Down
27 changes: 17 additions & 10 deletions src/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import globby from 'globby'
import { Argv } from 'yargs'
import yargs from 'yargs/yargs'
import * as cli from './cli'
import { Converter } from './converter'
import { Converter, ConvertType } from './converter'
import { CLIError, error } from './error'
import { MarpReadyScript } from './ready'
import templates from './templates'
Expand Down Expand Up @@ -47,6 +47,12 @@ export default async function(argv: string[] = []): Promise<number> {
group: OptionGroup.Basic,
type: 'string',
},
pdf: {
default: false,
describe: 'Convert slide deck into PDF',
group: OptionGroup.Converter,
type: 'boolean',
},
template: {
describe: 'Template name',
group: OptionGroup.Converter,
Expand Down Expand Up @@ -75,6 +81,10 @@ export default async function(argv: string[] = []): Promise<number> {
readyScript: await MarpReadyScript.bundled(),
template: args.template || 'bare',
theme: args.theme,
type:
args.pdf || `${args.output}`.toLowerCase().endsWith('.pdf')
? ConvertType.pdf
: ConvertType.html,
})

// Find target markdown files
Expand All @@ -96,9 +106,7 @@ export default async function(argv: string[] = []): Promise<number> {

// Convert markdown into HTML
try {
const processed = await converter.convertFiles(...files)

processed.forEach(ret => {
await converter.convertFiles(files, ret => {
const from = path.relative(process.cwd(), ret.path)
const output =
ret.output === '-'
Expand All @@ -109,15 +117,14 @@ export default async function(argv: string[] = []): Promise<number> {
if (ret.output === '-') console.log(ret.result)
})
} catch (e) {
error(`Failed converting Markdown. (${e.message})`)
error(`Failed converting Markdown. (${e.message})`, e.errorCode)
}

return 0
} catch (e) {
if (e instanceof CLIError) {
cli.error(e.message)
return e.errorCode
}
throw e
if (!(e instanceof CLIError)) throw e

cli.error(e.message)
return e.errorCode
}
}
16 changes: 8 additions & 8 deletions src/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export interface TemplateOptions {
}

export interface TemplateResult {
options: TemplateOptions
rendered: MarpitRenderResult
result: string
}
Expand All @@ -23,13 +22,14 @@ export const bare: Template = opts => {
slideContainer: [],
})

const result = barePug({
...opts,
...rendered,
bare: { css: bareScss },
})

return { rendered, result, options: opts }
return {
rendered,
result: barePug({
...opts,
...rendered,
bare: { css: bareScss },
}),
}
}

const templates: { [name: string]: Template } = { bare }
Expand Down
2 changes: 1 addition & 1 deletion src/templates/bare.pug
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
doctype
html(lang="en")
head
meta(charset="UTF-8")
Expand Down
5 changes: 5 additions & 0 deletions src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@ declare module '*.scss' {
const scss: string
export default scss
}

declare module 'puppeteer-core' {
import * as puppeteer from 'puppeteer'
export = puppeteer
}
Loading