Skip to content

Add the Ability to Keep Individual Files and Filter the Files List #7

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
61 changes: 58 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,32 @@ Vuepress plugin for exporting site as PDF
- Designed to work well in headless environments like CI runners

## Config options
- `filter` - function for filtering pages (default `false`)
- `individualPdfFolder` - string (default temp dir), if supplied will save the individual PDFs and a `files.json` file
with the title, url, location, path, key, and frontmatter for each PDF to allow later combining/mapping
- `theme` - theme name (default `@vuepress/default`)
- `sorter` - function for changing pages order (default `false`)
- `outputFileName` - name of output file (default `site.pdf`)
- `outputFileName` - name of output file (default `site.pdf`, or null to skip creating a combined file (useful if saving individual PDFs))
- `puppeteerLaunchOptions` - [Puppeteer launch options object](https://github.com/puppeteer/puppeteer/blob/v2.1.1/docs/api.md#puppeteerlaunchoptions) (default `{}`)
- `pageOptions` - [Puppeteer page formatting options object](https://github.com/puppeteer/puppeteer/blob/v2.1.1/docs/api.md#pagepdfoptions) (default `{format: 'A4'}`)
- `sorter` - function for changing pages order (default `false`)

### Sort/Filter Functions

The input to each is page object(s) from Vuepress context:
[https://vuepress.vuejs.org/plugin/context-api.html#ctx-pages](https://vuepress.vuejs.org/plugin/context-api.html#ctx-pages)

There is better documenation about the properties of a page object currently available at:
[https://vuepress.vuejs.org/plugin/option-api.html#extendpagedata](https://vuepress.vuejs.org/plugin/option-api.html#extendpagedata)

At the time of writing all the keys available were:
`title`, `_meta`, `_filePath`, `_content`, `_permalink`, `frontmatter`, `_permalinkPattern`, `_extractHeaders`,
`_context`, `regularPath`, `relativePath`, `key`, `path`, `_strippedContent`, `headers`, `_computed`, `_localePath`

Sort will receive `(a, b)` where `a` and `b` are page objects and should return an integer.

### Usage
Filter will receive a page object and the index and should return `true`/`false`.

## Usage

Using this plugin:

Expand All @@ -25,6 +44,42 @@ module.exports = {
}
```

Using the plugin with options:

```js
// in .vuepress/config.js
module.exports = {
// ...
plugins: [
// ...
[
require("../../vuepress-plugin-pdf-export"),
{
// options to override
outputFileName: null,
pageOptions: {
format: 'Letter',
printBackground: true,
displayHeaderFooter: false,
headerTemplate: "",
footerTemplate: "",
margin: {
top: "1in",
left: "1in",
right: "1in",
bottom: "1in",
}
},
individualPdfFolder: 'build/pdf',
filter: (a) => !a?.frontmatter?.home,
sorter: (a, b) => a.path < b.path ? -1 : 1,
}
]
],
// ...
};
```

Then run:

``` bash
Expand Down
12 changes: 8 additions & 4 deletions src/extendCli.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ const generatePDF = require('./generatePdf')

module.exports = options => {
const theme = options.theme || '@vuepress/default'
const filter = options.filter || false
const sorter = options.sorter || false
const outputFileName = options.outputFileName || 'site.pdf'
const outputFileName = options.outputFileName === null ? null : options.outputFileName || 'site.pdf'
const puppeteerLaunchOptions = options.puppeteerLaunchOptions || {}
const pageOptions = options.pageOptions || {}
const individualPdfFolder = options.individualPdfFolder;

return cli => {
cli
Expand All @@ -30,12 +32,14 @@ module.exports = options => {

try {
await generatePDF(nCtx, {
port: nCtx.devProcess.port,
filter,
host: nCtx.devProcess.host,
sorter,
individualPdfFolder,
outputFileName,
pageOptions,
port: nCtx.devProcess.port,
puppeteerLaunchOptions,
pageOptions
sorter,
})
} catch (error) {
console.error(red(error))
Expand Down
72 changes: 46 additions & 26 deletions src/generatePdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,41 @@ const { fs, logger, chalk } = require('@vuepress/shared-utils')
const { yellow, gray } = chalk

module.exports = async (ctx, {
port,
filter,
host,
sorter,
individualPdfFolder,
outputFileName,
pageOptions,
port,
puppeteerLaunchOptions,
pageOptions
sorter,
}) => {
const { pages, tempPath } = ctx
const tempDir = join(tempPath, 'pdf')
fs.ensureDirSync(tempDir)
const pdfDir = individualPdfFolder || join(tempPath, 'pdf')

if (individualPdfFolder && fs.existsSync(pdfDir)) {
fs.removeSync(pdfDir)
}
fs.ensureDirSync(pdfDir)

let exportPages = pages.slice(0)

if (typeof sorter === 'function') {
exportPages = exportPages.sort(sorter)
}

if (typeof filter === 'function') {
exportPages = exportPages.filter(filter)
}

exportPages = exportPages.map(page => {
return {
url: page.path,
title: page.title,
location: `http://${host}:${port}${page.path}`,
path: `${tempDir}/${page.key}.pdf`
path: `${pdfDir}/${page.key}.pdf`,
key: page.key,
frontmatter: page.frontmatter,
}
})

Expand All @@ -50,35 +62,43 @@ module.exports = async (ctx, {
)

await browserPage.pdf({
path: pagePath,
format: 'A4',
...pageOptions
...pageOptions,
path: pagePath,
})

logger.success(`Generated ${yellow(title)} ${gray(`${url}`)}`)
}

await new Promise(resolve => {
const mergedPdf = new pdf.Document()
if (individualPdfFolder) {
fs.writeFileSync(`${pdfDir}/files.json`, JSON.stringify(exportPages), {encoding: 'UTF8'})
}

if (outputFileName) {
await new Promise(resolve => {
const mergedPdf = new pdf.Document()

exportPages
.map(({ path }) => fs.readFileSync(path))
.forEach(file => {
const page = new pdf.ExternalDocument(file)
mergedPdf.addPagesOf(page)
})
exportPages
.map(({path}) => fs.readFileSync(path))
.forEach(file => {
const page = new pdf.ExternalDocument(file)
mergedPdf.addPagesOf(page)
})

mergedPdf.asBuffer((err, data) => {
if (err) {
throw err
} else {
fs.writeFileSync(outputFileName, data, { encoding: 'binary' })
logger.success(`Export ${yellow(outputFileName)} file!`)
resolve()
}
mergedPdf.asBuffer((err, data) => {
if (err) {
throw err
} else {
fs.writeFileSync(outputFileName, data, {encoding: 'binary'})
logger.success(`Export ${yellow(outputFileName)} file!`)
resolve()
}
})
})
})
}

await browser.close()
fs.removeSync(tempDir)
if (!individualPdfFolder) {
fs.removeSync(pdfDir)
}
}