-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.ts
76 lines (65 loc) · 1.9 KB
/
renderer.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
import PDFDocument from 'pdfkit'
import * as fs from 'fs'
import {
PDFNodes,
PDFElements,
PDFDocumentElement,
PDFTextNode,
PDFElement,
PDFNode,
} from './elements'
import { App, createRenderer, CreateAppFunction } from 'vue'
import { nodeMap, nodeOps } from './nodeOps'
export const createApp = ((...args): App => {
const renderer = createRenderer<PDFNode, PDFElement>(nodeOps)
const app = renderer.createApp(...args)
const { mount } = app
app.mount = (doc: PDFDocumentElement): any => {
const proxy = mount(doc)
renderDocument()
return proxy
}
return app
}) as CreateAppFunction<PDFElement>
export const renderDocument = (fileName: string = 'file') => {
const pdf = new PDFDocument()
const stream = pdf.pipe(fs.createWriteStream(`./${fileName}.pdf`))
const defaultStyles: Record<string, string> = {
color: 'black',
}
const getParentStyle = (attr: string, parent: PDFNodes | PDFElements): string => {
if (parent instanceof PDFDocumentElement) return defaultStyles[attr]
if (attr in parent.styles) {
return parent.styles[attr]
}
if (parent.parent !== undefined) return getParentStyle(attr, nodeMap[parent.parent])
return defaultStyles[attr]
}
const draw = (node: PDFNodes | PDFElements) => {
const color = getParentStyle('color', node)
pdf.fill(color)
for (const [key, val] of Object.entries(node.styles)) {
if (key === 'color') {
pdf.fill(val)
}
}
if (node instanceof PDFTextNode) {
pdf.text(node.text)
}
}
const traverse = (node: PDFNodes | PDFElements) => {
if (node instanceof PDFElement) {
for (const child of node.children) {
draw(nodeMap[child])
traverse(nodeMap[child])
}
}
}
const rootNode = nodeMap['root']
pdf.fontSize(40)
traverse(rootNode)
pdf.end()
stream.on('finish', () => {
console.log('\nFinished writing on the file. \n')
})
}