forked from yWorks/svg2pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg2pdf.ts
71 lines (56 loc) · 2.06 KB
/
svg2pdf.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
import { SvgNode } from './nodes/svgnode'
import { Context } from './context/context'
import { ReferencesHandler } from './context/referenceshandler'
import { parse } from './parse'
import { ColorFill } from './fill/ColorFill'
import { jsPDF } from 'jspdf'
import { StyleSheets } from './context/stylesheets'
import { Viewport } from './context/viewport'
export async function svg2pdf(
element: Element,
pdf: jsPDF,
options: Svg2PdfOptions = {}
): Promise<jsPDF> {
const x = options.x ?? 0.0
const y = options.y ?? 0.0
const extCss = options.loadExternalStyleSheets ?? false
// create context object
const idMap: { [id: string]: SvgNode } = {}
const refsHandler = new ReferencesHandler(idMap)
const styleSheets = new StyleSheets(element, extCss)
await styleSheets.load()
// start with the entire page size as viewport
const viewport = new Viewport(pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight())
const svg2pdfParameters = { ...options, element }
const context = new Context(pdf, { refsHandler, styleSheets, viewport, svg2pdfParameters })
pdf.advancedAPI()
pdf.saveGraphicsState()
// set offsets
pdf.setCurrentTransformationMatrix(pdf.Matrix(1, 0, 0, 1, x, y))
// set default values that differ from pdf defaults
pdf.setLineWidth(context.attributeState.strokeWidth)
const fill = (context.attributeState.fill as ColorFill).color
pdf.setFillColor(fill.r, fill.g, fill.b)
pdf.setFont(context.attributeState.fontFamily)
// correct for a jsPDF-instance measurement unit that differs from `pt`
pdf.setFontSize(context.attributeState.fontSize * pdf.internal.scaleFactor)
const node = parse(element, idMap)
await node.render(context)
pdf.restoreGraphicsState()
pdf.compatAPI()
context.textMeasure.cleanupTextMeasuring()
return pdf
}
jsPDF.API.svg = function(
element: Element,
options: Svg2PdfOptions = {}
): ReturnType<typeof svg2pdf> {
return svg2pdf(element, this, options)
}
export interface Svg2PdfOptions {
x?: number
y?: number
width?: number
height?: number
loadExternalStyleSheets?: boolean
}