forked from ZeMunchkin/react-component-export-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (76 loc) · 2.52 KB
/
index.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';
import ReactDOM from 'react-dom';
const fileType = {
PNG: 'image/png',
JPEG: 'image/jpeg',
PDF: 'application/pdf'
};
/**
* @param {string} uri
* @param {string} filename
*/
const saveAs = (uri, filename) => {
const link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
window.open(uri);
}
};
/**
* @param {React.RefObject} node
* @param {string} fileName
* @param {string} backgroundColor
* @param {string} type
*/
const exportComponent = (node, fileName, backgroundColor, type) => {
const element = ReactDOM.findDOMNode(node.current);
return html2canvas(element, {
backgroundColor: backgroundColor,
scrollY: -window.scrollY,
useCORS: true,
}).then(canvas => {
if (type === fileType.PDF) {
const pdf = canvas.width > canvas.height
? new JsPDF('l', 'mm', [canvas.width, canvas.height])
: new JsPDF('p', 'mm', [canvas.height, canvas.width]);
pdf.addImage(canvas.toDataURL(fileType.PNG, 1.0), 'PNG', 0, 0);
pdf.save(fileName);
} else {
saveAs(canvas.toDataURL(type, 1.0), fileName);
}
});
};
/**
* @param {React.RefObject} node
* @param {string} fileName='component.png'
* @param {string} backgroundColor=null
* @param {string} type=fileType.PNG
*/
const exportComponentAsPNG = (node, fileName = 'component.png', backgroundColor = null, type = fileType.PNG) => {
return exportComponent(node, fileName, backgroundColor, type);
};
/**
* @param {React.RefObject} node
* @param {string} fileName='component.jpeg'
* @param {string} backgroundColor=null
* @param {string} type=fileType.JPEG
*/
const exportComponentAsJPEG = (node, fileName = 'component.jpeg', backgroundColor = null, type = fileType.JPEG) => {
return exportComponent(node, fileName, backgroundColor, type);
};
/**
* @param {React.RefObject} node
* @param {string} fileName='component.pdf'
* @param {string} backgroundColor=null
* @param {string} type=fileType.PDF
*/
const exportComponentAsPDF = (node, fileName = 'component.pdf', backgroundColor = null, type = fileType.PDF) => {
return exportComponent(node, fileName, backgroundColor, type);
};
export { exportComponentAsJPEG, exportComponentAsPDF, exportComponentAsPNG };