-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-pdf.js
64 lines (55 loc) · 1.44 KB
/
generate-pdf.js
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
// Generate a PDF from the HTML code in this repo.
//
// Usage:
// ANVIL_API_TOKEN=your_token yarn generate-pdf:react && open ./generate-react.output.pdf
import fs from 'fs'
import path from 'path'
import Anvil from '@anvilco/anvil'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
import Statement from './components/Statement'
const apiKey = process.env.ANVIL_API_TOKEN
function buildHTMLToPDFPayload () {
const sheet = new ServerStyleSheet()
const html = ReactDOMServer.renderToStaticMarkup(
sheet.collectStyles(
<Statement />
)
)
const css = sheet.instance.toString()
return {
type: 'html',
title: 'HTML Statement',
data: {
html,
css,
},
page: {
marginLeft: '60px',
marginRight: '60px',
},
}
}
async function main () {
const client = new Anvil({
apiKey,
})
const exampleData = buildHTMLToPDFPayload()
const { statusCode, data, errors } = await client.generatePDF(exampleData)
if (statusCode === 200) {
const scriptDir = __dirname
const outputFilePath = path.join(scriptDir, '..', 'generate-react.output.pdf')
fs.writeFileSync(outputFilePath, data, { encoding: null })
} else {
console.log(statusCode, JSON.stringify(errors || data, null, 2))
}
}
main()
.then(() => {
process.exit(0)
})
.catch((err) => {
console.log(err.stack || err.message)
process.exit(1)
})