1import React, { useEffect, useRef, useState } from 'react';
2import './styles.css';
3
4const Dropzone = () => {
5 const dropRef = useRef(null);
6 const [docs, addDocument] = useState([]);
7 const [thumbArray, addThumbToArray] = useState([]);
8
9 useEffect(() => {
10 if (docs.length >= 1) {
11 const Core = window.instance.Core;
12 const loadDocumentAndThumb = async () => {
13 const doc = await Core.createDocument(docs[docs.length - 1]);
14 doc.loadThumbnail(1, (thumbnail) => {
15 addThumbToArray([...thumbArray, thumbnail]);
16 });
17 }
18 loadDocumentAndThumb();
19 }
20 // eslint-disable-next-line react-hooks/exhaustive-deps
21 }, [docs]);
22
23 const mergeDocuments = async () => {
24 const Core = window.instance.Core;
25 if (docs.length > 0) {
26 const doc = await Core.createDocument(docs[0]);
27 let i;
28 for (i = 1; i < docs.length; i++) {
29 let doc2 = await Core.createDocument(docs[i]);
30 await doc.insertPages(doc2);
31 }
32
33 const data = await doc.getFileData();
34 const arr = new Uint8Array(data);
35 const blob = new Blob([arr], { type: 'application/pdf' });
36 downloadBlob(blob);
37 }
38 addDocument([]);
39 addThumbToArray([]);
40 };
41
42 const downloadBlob = (blob) => {
43 const a = document.createElement('a');
44 document.body.appendChild(a);
45 const url = window.URL.createObjectURL(blob);
46 a.href = url;
47 a.download = 'merged-file.pdf';
48 a.click();
49 setTimeout(() => {
50 window.URL.revokeObjectURL(url);
51 document.body.removeChild(a);
52 }, 0);
53 };
54
55 const onDropEvent = (ev) => {
56 ev.preventDefault();
57 const viewerID = ev.dataTransfer.getData('dataTransferWebViewerFrame');
58 const otherWebViewerIframe = window.parent.document.querySelector(
59 `#${viewerID}`,
60 );
61 if (!otherWebViewerIframe) {
62 console.warn('Could not find other instance of WebViewer');
63 }
64
65 const extractedDataPromise =
66 otherWebViewerIframe.contentWindow.extractedDataPromise;
67 if (!extractedDataPromise) {
68 console.warn('Could not retrieve data from other instance of WebViewer');
69 }
70
71 extractedDataPromise.then(docToMerge => {
72 addDocument([...docs, docToMerge]);
73 });
74 };
75
76 return (
77 <div>
78 <div
79 className="dropDiv"
80 ref={dropRef}
81 onDrop={ev => {
82 onDropEvent(ev);
83 }}
84 onDragOver={(ev) => {
85 ev.preventDefault();
86 ev.dataTransfer.dropEffect = 'move';
87 }}
88 >
89 <p>Drop the thumbs from the viewers here</p>
90 <button onClick={mergeDocuments}>Download</button>
91 </div>
92 <div className="list">
93 {thumbArray.map((thumb, i) => {
94 return <img key={i} src={thumb.toDataURL()} alt={i} />
95 })}
96 </div>
97 </div>
98 );
99};
100
101export default Dropzone;
102