-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpdf-to-svg-panel.js
2147 lines (1829 loc) · 84.7 KB
/
pdf-to-svg-panel.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* DISCLAIMER: The content of this file is subject to the Miro Developer Terms of Use: https://miro.com/legal/developer-terms-of-use/ */
window.miroAppItems = {
frame: null,
elements: []
};
window.connectingLinesArray = [];
window.textContent = [];
window.sticky_notes = [];
window.baseCells = [];
window.extraCells = [];
window.miroFrames = null;
window.frameToReplicate = {
id: null,
index: null,
element: null
};
window.miroWidgets = null;
/* Function to detect text alignment within a cell */
function isElementWithinAndAligned(inner, outer) {
const innerRect = inner.getBoundingClientRect();
const outerRect = outer.getBoundingClientRect();
// Check if the inner element is within the outer element
const isWithin =
innerRect.left >= outerRect.left &&
innerRect.right <= outerRect.right &&
innerRect.top >= outerRect.top &&
innerRect.bottom <= outerRect.bottom;
// Check if the inner element is centered
const innerCenterX = innerRect.left + innerRect.width / 2;
const innerCenterY = innerRect.top + innerRect.height / 2;
const outerCenterX = outerRect.left + outerRect.width / 2;
const outerCenterY = outerRect.top + outerRect.height / 2;
const isCentered =
Math.abs(innerCenterX - outerCenterX) <= 1 &&
Math.abs(innerCenterY - outerCenterY) <= 1;
// Check if the inner element is aligned to the top-left corner
const isTopLeftAligned =
(Math.abs(innerRect.left - outerRect.left) <= 1 || Math.abs(innerRect.left - outerRect.left) <= 3) &&
(Math.abs(innerRect.top - outerRect.top) <= 1 || Math.abs(innerRect.top - outerRect.top) <= 3);
const isLeftAligned =
Math.abs(innerRect.left - outerRect.left) <= 1 || Math.abs(innerRect.left - outerRect.left) <= 3;
return { isWithin, isCentered, isTopLeftAligned, isLeftAligned };
}
/* Function to check if shape is double - The parsing of the PDF into SVG duplicate several shapes */
function isDoubleShape(shape) {
let shapeRect = shape.getBoundingClientRect();
let referenceArray = window.extraCells;
let isDouble = false;
for(let i=0; i < referenceArray.length; i++) {
let referenceRect = referenceArray[i].extra_cell_element.getBoundingClientRect();
if (Math.trunc(shapeRect.x) === Math.trunc(referenceRect.x) || Math.trunc(shapeRect.x - 1) === Math.trunc(referenceRect.x) || Math.trunc(shapeRect.x + 1) === Math.trunc(referenceRect.x) || Math.trunc(shapeRect.x - 2) === Math.trunc(referenceRect.x) || Math.trunc(shapeRect.x + 2) === Math.trunc(referenceRect.x)) {
if (Math.trunc(shapeRect.y) === Math.trunc(referenceRect.y) || Math.trunc(shapeRect.y - 1) === Math.trunc(referenceRect.y) || Math.trunc(shapeRect.y + 1) === Math.trunc(referenceRect.y) || Math.trunc(shapeRect.y - 2) === Math.trunc(referenceRect.y) || Math.trunc(shapeRect.y + 2) === Math.trunc(referenceRect.y)) {
shape.setAttribute('data-type', 'duplicate-shape');
shape.parentElement.parentElement.setAttribute('data-type', 'duplicate-shape-parent');
isDouble = true;
let currentShapeColor = shape.getAttribute('fill');
if (referenceArray[i].background_color === '#ffffff' && currentShapeColor !== '#ffffff') {
referenceArray[i].background_color = currentShapeColor;
}
}
}
}
return isDouble;
}
/* Function to check if element is the first child of its parent */
function isFirstChild(element) {
return element.parentNode && element.parentNode.firstElementChild === element;
}
/* Function to get PDF data */
async function getPdfObjectData(pdfObjects, objIds) {
const promises = objIds.map((objId) => {
return new Promise((resolve, reject) => {
pdfObjects.get(objId, (data) => {
if (data) {
resolve({ objId, data });
} else {
reject(new Error(`Failed to get data for ${objId}`));
}
});
});
});
try {
const results = await Promise.all(promises);
return results; // Return results for further processing
}
catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw error if necessary
}
}
/* Function to check if rectangle is a underline of links */
function isRectangularLinkLine(pathElement) {
let rect = pathElement.getBoundingClientRect();
if (rect.width < window.mainTable.width && rect.height < window.mainTable.height) {
if (pathElement.nextSibling && pathElement.nextSibling.tagName === 'svg:text') {
// Get the 'd' attribute of the path
var pathData = pathElement.getAttribute('d');
// Parse the path data into commands and coordinates
var commands = pathData.split(/[\s,]/).filter(token => token.trim() !== '');
// Function to calculate the distance between two points
function distance(point1, point2) {
return Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2);
}
// Function to check if four points form a rectangle
function isRectangle(points) {
if (points.length !== 4) return false;
// Calculate distances between all points
var distances = [
distance(points[0], points[1]), // Side 1
distance(points[1], points[2]), // Side 2
distance(points[2], points[3]), // Side 3
distance(points[3], points[0]), // Side 4
distance(points[0], points[2]), // Diagonal 1
distance(points[1], points[3]), // Diagonal 2
];
// Check that opposite sides are equal and diagonals are equal
var tolerance = 0.001; // Adjust based on precision requirements
var isOppositeSidesEqual =
Math.abs(distances[0] - distances[2]) < tolerance &&
Math.abs(distances[1] - distances[3]) < tolerance;
var isDiagonalsEqual = Math.abs(distances[4] - distances[5]) < tolerance;
return isOppositeSidesEqual && isDiagonalsEqual;
}
// Extract points from the path commands
var points = [];
let currentPoint = { x: 0, y: 0 };
for (let i = 0; i < commands.length; i++) {
var command = commands[i];
if (command === 'M' || command === 'L') {
currentPoint = {
x: parseFloat(commands[i + 1]),
y: parseFloat(commands[i + 2]),
};
points.push(currentPoint);
} else if (command === 'H') {
currentPoint = {
x: parseFloat(commands[i + 1]),
y: currentPoint.y,
};
points.push(currentPoint);
} else if (command === 'V') {
currentPoint = {
x: currentPoint.x,
y: parseFloat(commands[i + 1]),
};
points.push(currentPoint);
} else if (command === 'Z') {
// Close the path by connecting to the first point
points.push(points[0]);
}
}
// Remove duplicate points (e.g., if the path ends with 'Z')
var uniquePoints = [];
for (var point of points) {
var isDuplicate = uniquePoints.some(
(p) => Math.abs(p.x - point.x) < 0.001 && Math.abs(p.y - point.y) < 0.001
);
if (!isDuplicate) {
uniquePoints.push(point);
}
}
// Check if the points form a rectangle
if (uniquePoints.length === 4 && isRectangle(uniquePoints)) {
return true;
}
else {
return false;
}
}
}
}
/* Function to check if shape is a rectangle */
function isRectangularBox(pathElement) {
let rect = pathElement.getBoundingClientRect();
if (rect.width < window.mainTable.width && rect.height < window.mainTable.height) {
if (!pathElement.nextSibling || pathElement.nextSibling.tagName !== 'svg:text') {
// Get the 'd' attribute of the path
var pathData = pathElement.getAttribute('d');
// Parse the path data into commands and coordinates
var commands = pathData.split(/[\s,]/).filter(token => token.trim() !== '');
// Function to calculate the distance between two points
function distance(point1, point2) {
return Math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2);
}
// Function to check if four points form a rectangle
function isRectangle(points) {
if (points.length !== 4) return false;
// Calculate distances between all points
var distances = [
distance(points[0], points[1]), // Side 1
distance(points[1], points[2]), // Side 2
distance(points[2], points[3]), // Side 3
distance(points[3], points[0]), // Side 4
distance(points[0], points[2]), // Diagonal 1
distance(points[1], points[3]), // Diagonal 2
];
// Check that opposite sides are equal and diagonals are equal
var tolerance = 0.001; // Adjust based on precision requirements
var isOppositeSidesEqual =
Math.abs(distances[0] - distances[2]) < tolerance &&
Math.abs(distances[1] - distances[3]) < tolerance;
var isDiagonalsEqual = Math.abs(distances[4] - distances[5]) < tolerance;
return isOppositeSidesEqual && isDiagonalsEqual;
}
// Extract points from the path commands
var points = [];
let currentPoint = { x: 0, y: 0 };
for (let i = 0; i < commands.length; i++) {
var command = commands[i];
if (command === 'M' || command === 'L') {
currentPoint = {
x: parseFloat(commands[i + 1]),
y: parseFloat(commands[i + 2])
};
points.push(currentPoint);
} else if (command === 'H') {
currentPoint = {
x: parseFloat(commands[i + 1]),
y: currentPoint.y
};
points.push(currentPoint);
} else if (command === 'V') {
currentPoint = {
x: currentPoint.x,
y: parseFloat(commands[i + 1])
};
points.push(currentPoint);
} else if (command === 'Z') {
// Close the path by connecting to the first point
points.push(points[0]);
}
}
// Remove duplicate points (e.g., if the path ends with 'Z')
var uniquePoints = [];
for (var point of points) {
var isDuplicate = uniquePoints.some(
(p) => Math.abs(p.x - point.x) < 0.001 && Math.abs(p.y - point.y) < 0.001
);
if (!isDuplicate) {
uniquePoints.push(point);
}
}
// Check if the points form a rectangle
if (uniquePoints.length === 4 && isRectangle(uniquePoints)) {
return true;
}
else {
return false;
}
}
}
}
/* Function to check if SVG path is within a specific element */
function checkTextPathsWithinElement(refElement) {
// Define the specific rectangle coordinates (e.g., top-left and bottom-right points)
const elementRect = refElement.getBoundingClientRect;
const rect = {
left: elementRect.left, // x1
top: elementRect.top, // y1
right: elementRect.right, // x2
bottom: elementRect.bottom // y2
};
// Get all elements with the specified tag name
const elements = document.getElementsByTagName('tspan');
// Filter elements within the rectangle
const firstElementInRect = Array.from(elements).find((element) => {
const boundingBox = element.getBoundingClientRect();
// Check if the element's bounding box is within the specified rectangle
const isWithinRect =
boundingBox.left >= rect.left &&
boundingBox.right <= rect.right &&
boundingBox.top >= rect.top &&
boundingBox.bottom <= rect.bottom;
// Check if the element has non-empty textContent
const hasTextContent = element.textContent.trim().length > 0;
// Return true if both conditions are met
return isWithinRect && hasTextContent;
});
}
/* Function to convert PDF coordinates to absolute coordinates */
function convertToAbsoluteCoordinates(pdfX, pdfY, viewport) {
// Flip the y-coordinate (PDF's origin is bottom-left, web's is top-left)
const flippedY = viewport.height - pdfY;
// Apply viewport transformation (scaling and offset)
const absoluteX = pdfX * viewport.scale + viewport.offsetX;
const absoluteY = flippedY * viewport.scale + viewport.offsetY;
return { x: absoluteX, y: absoluteY };
}
/* Function to estimate text width and height */
function estimateTextDimensions(text, fontSize) {
// Approximate width based on font size and text length
const width = text.length * fontSize * 0.6; // Adjust factor based on font
const height = fontSize; // Height is approximately equal to font size
return { width, height };
}
/* Function to find duplicates within an Array */
function findDuplicates(array) {
const seen = new Set();
const duplicates = new Set();
array.forEach(item => {
if (seen.has(item.title)) {
duplicates.add(item.title);
} else {
seen.add(item.title);
}
});
return Array.from(duplicates);
}
/* Function to get Frame Title */
async function getFrameTitles(title) {
window.miroFrames = await miro.board.get({type: 'frame'});
let frames = window.miroFrames;
const duplicateTitles = findDuplicates(frames);
if (duplicateTitles.length > 0) {
console.log("Duplicate titles found:", duplicateTitles);
alert('There are frames with the same title. To parse the PDF it\'s necessary that each frame in your board has a unique title');
return false;
}
else {
console.log("All titles are unique.");
}
for(let i=0; i < frames.length; i++){
let htmlString = frames[i].title;
extractRenderedText(htmlString, 'frame', i);
}
let titleFound = false;
for(let i=0; i < frames.length; i++){
if (frames[i].plain_text === title) {
titleFound = true;
window.frameToReplicate.id = frames[i].id;
window.frameToReplicate.index = i;
window.frameToReplicate.element = frames[i];
return true;
}
}
if (!titleFound) {
alert('The provided frame title was not found on this board');
return false;
}
else {
return window.frameToReplicate;
}
}
/* Function to extract text as rendered (without spaces and tags) */
function extractRenderedText(htmlString, type, index) {
// Create a temporary container element
const container = document.createElement("div");
container.style.position = "absolute";
container.style.top = "-9999px"; // Move off-screen to avoid visibility
container.style.left = "-9999px";
container.style.visibility = "hidden";
// Set the HTML string as the content
container.innerHTML = htmlString;
document.body.appendChild(container); // Append to the DOM
// Extract the rendered text
const renderedText = container.textContent; // innerText respects rendered spacing
if (type === 'frame') {
window.miroFrames[index].plain_text = renderedText;
}
else if (type === 'widget') {
window.miroWidgets[index].plain_text = renderedText.replace(/\s+/g, ''); // Remove all whitespace characters
}
// Remove the temporary container
document.body.removeChild(container);
return renderedText;
}
/* Function to add individual widgets to Frames */
async function attachToFrame() {
let frame = window.miroAppItems.frame;
let array = window.miroAppItems.elements;
for(let i=0; i < array.length; i++) {
await frame.add(array[i]);
}
return true;
}
/* Function to generate cells from intersections */
function generateCellsFromIntersections(intersections) {
const cells = [];
// Assuming the cells are rectangular, we can create bounding boxes for each cell
// This is a simplified approach; you may need more sophisticated logic for irregular tables
for (let i = 0; i < intersections.length - 1; i++) {
const cell = {
x: intersections[i].x,
y: intersections[i].y,
width: Math.abs(intersections[i + 1].x - intersections[i].x),
height: Math.abs(intersections[i + 1].y - intersections[i].y)
};
cells.push(cell);
}
return cells;
}
/* Function to create Miro Frames */
async function createFrame(title,x,y,width,height,color) {
const frame = await window.miro.board.createFrame({
title: title,
style: {
fillColor: (color || '#ffffff')
},
x: x,
y: y,
width: width,
height: height
});
window.miroAppItems.frame = frame;
return frame;
}
/* Function to create Miro rectangular shapes */
async function createRectangle(text,x,y,w,h,style,frame,htmlId) {
const shape = await window.miro.board.createShape({
content: (text || ''),
shape: 'rectangle',
style: style,
x: x,
y: y,
width: (w < 8 ? 8 : w),
height: (h < 8 ? 8 : h)
});
if (frame) { await frame.add(shape) }
let p = window.connectingLinesArray.length;
while (--p >= 0) {
if (connectingLinesArray[p].startElement && connectingLinesArray[p].startElement.html_id === htmlId) {
connectingLinesArray[p].startElement.miro_id = shape.id;
}
if (connectingLinesArray[p].endElement && connectingLinesArray[p].endElement.html_id === htmlId) {
connectingLinesArray[p].endElement.miro_id = shape.id;
}
}
window.miroAppItems.elements.push(shape);
return shape;
}
/* Function to create Miro sticky notes */
async function createStickyNote(text,x,y,w,type,style,tags,frame,htmlId) {
const sticky = await window.miro.board.createStickyNote({
content: (text || ''),
shape: type,
style: style,
x: x,
y: y,
width: w,
tagIds: tags
});
if (frame) { await frame.add(sticky) }
let p = window.connectingLinesArray.length;
while (--p >= 0) {
if (connectingLinesArray[p].startElement.html_id === htmlId) {
connectingLinesArray[p].startElement.miro_id = sticky.id;
}
if (connectingLinesArray[p].endElement.html_id === htmlId) {
connectingLinesArray[p].endElement.miro_id = sticky.id;
}
}
window.miroAppItems.elements.push(sticky);
return sticky;
}
/* Function to create Miro connecting lines */
async function createConnectingLine(start,end,snapStart,snapEnd) {
// Create a connector.
const connector = await miro.board.createConnector({
shape: 'curved',
style: {
startStrokeCap: 'none',
endStrokeCap: 'rounded_stealth',
strokeStyle: 'normal',
strokeColor: '#333333', // Magenta
strokeWidth: 2
},
// Set the start point of the connector.
start: {
// Define the start board item for the connector by specifying the 'start' item ID.
item: start,
// Set a point on the border of the 'start' shape to mark the start point of the connector.
snapTo: snapStart
},
// Set the end point of the connector.
end: {
// Define the end board item for the connector by specifying the 'end' item ID.
item: end,
// Set a snapTo of 'end' shape to mark the end point of the connector.
snapTo: snapEnd
}
});
return connector;
}
/* Function to trigger multiple shape creations */
async function createShapes(array, type, frame) {
const shapeCreationPromises = []; // Array to hold all promises
const viewport = await miro.board.viewport.get();
// Loop through the shapes and trigger creation
if (!array) {debugger;}
for (let i = 0; i < array.length; i++) {
if (type === 'base_cells') {
let el = array[i].element;
let rect = el.getBoundingClientRect();
let text = (array[i].formatted_text ? array[i].formatted_text : array[i].text_content_orig ? array[i].text_content_orig : '');
let x = ((rect.left + rect.width / 2) + (frame.x - (frame.width / 2)));
let y = ((rect.top + rect.height / 2) + (frame.y - (frame.height / 2)));
let w = rect.width;
let h = rect.height;
let style = {
color: (array[i]?.font_color ? array[i]?.font_color : '#ff0000'),
fillColor: (array[i]?.text_style?.fillColor ? array[i]?.text_style?.fillColor : array[i]?.background_color ? array[i]?.background_color : '#ffffff'),
fontSize: 4,
fontFamily: 'arial',
textAlign: array[i]?.text_alignment_horizontal ? 'left' : 'center',
textAlignVertical: array[i]?.text_alignment_vertical ? 'top' : 'middle',
borderStyle: 'normal',
borderOpacity: 1.0,
borderColor: linesColor,
borderWidth: 1.0,
fillOpacity: (array[i]?.text_style?.fillOpacity ? array[i]?.text_style?.fillOpacity : array[i]?.background_opacity ? array[i]?.background_opacity : 1.0)
};
shapeCreationPromises.push(createRectangle(text,x,y,w,h,style,frame));
}
else if (type === 'extra_cells') {
for(let f=0; f < window.miroWidgets.length; f++) {
if (window.miroWidgets[f].type === 'shape') {
if (array[i].text_content === window.miroWidgets[f].plain_text) {
array[i].formatted_text = window.miroWidgets[f].content;
array[i].text_style = window.miroWidgets[f].style;
}
}
}
let el = array[i].extra_cell_element
let rect = el.getBoundingClientRect();
let text = (array[i].formatted_text ? array[i].formatted_text : array[i].text_content_orig ? array[i].text_content_orig : '');
let x = ((rect.left + rect.width / 2) + (frame.x - (frame.width / 2)));
let y = ((rect.top + rect.height / 2) + (frame.y - (frame.height / 2)));
let w = rect.width;
let h = rect.height;
let style = {
color: (array[i]?.text_style?.color ? array[i]?.text_style?.color : array[i]?.font_color ? array[i]?.font_color : '#1a1a1a'),
fillColor: (array[i]?.text_style?.fillColor ? array[i]?.text_style?.fillColor : array[i]?.background_color ? array[i]?.background_color : '#ffffff'),
fontSize: 4,
fontFamily: array[i]?.text_style?.fontFamily ? array[i]?.text_style?.fontFamily : 'arial',
textAlign: array[i]?.text_style?.textAlign ? array[i]?.text_style?.textAlign : array[i]?.text_alignment_horizontal ? 'left' : 'center',
textAlignVertical: array[i]?.text_style?.textAlignVertical ? array[i]?.text_style?.textAlignVertical : array[i]?.text_alignment_vertical ? 'top' : 'middle',
borderStyle: array[i]?.text_style?.borderStyle ? array[i]?.text_style.borderStyle : 'normal',
borderOpacity: array[i]?.text_style?.borderOpacity ? array[i]?.text_style?.borderOpacity : 1.0,
borderColor: array[i]?.text_style?.borderColor ? array[i]?.text_style?.borderColor : linesColor,
borderWidth: array[i]?.text_style?.borderWidth ? array[i]?.text_style?.borderWidth : 2.0,
fillOpacity: (array[i]?.text_style?.fillOpacity ? array[i]?.text_style?.fillOpacity : array[i]?.background_opacity ? array[i]?.background_opacity : 1.0)
};
shapeCreationPromises.push(createRectangle(text,x,y,w,h,style,frame,array[i].extra_cell));
}
else if (type === 'stickies') {
for(let f=0; f < window.miroWidgets.length; f++) {
if (window.miroWidgets[f].type === 'sticky_note') {
if (array[i].text_content === window.miroWidgets[f].plain_text) {
array[i].formatted_text = window.miroWidgets[f].content;
array[i].text_style = window.miroWidgets[f].style;
array[i].tags = window.miroWidgets[f].tagIds;
}
}
}
const colorMapping = {
'#f5f6f8': 'gray',
'#fff9b1': 'light_yellow',
'#f5d128': 'yellow',
'#ff9d48': 'orange',
'#d5f692': 'light_green',
'#c9df56': 'green',
'#93d275': 'dark_green',
'#67c6c0': 'cyan',
'#ffcee0': 'light_pink',
'#ea94bb': 'pink',
'#c6a2d2': 'violet',
'#f0939d': 'red',
'#a6ccf5': 'light_blue',
'#6cd8fa': 'blue',
'#9ea9ff': 'dark_blue',
'#000000': 'black'
};
let el = array[i].element
let rect = el.getBoundingClientRect();
let text = (array[i].formatted_text ? array[i].formatted_text : '');
let x = ((rect.left + rect.width / 2) + (frame.x - (frame.width / 2)));
let y = ((rect.top + rect.height / 2) + (frame.y - (frame.height / 2)));
let w = rect.width;
let type = array[i].shape;
let style = {
fillColor: colorMapping[el.getAttribute('fill')],
textAlign: 'center',
textAlignVertical: 'middle'
};
let tags = (array[i].tags ? array[i].tags : []);
shapeCreationPromises.push(createStickyNote(text,x,y,w,type,style,tags,frame,array[i].id));
}
else if (type === 'frame') {
const frame = array[i];
const frameRect = frame.getBoundingClientRect();
const frameX = (frameRect.left + (frameRect.width / 2) + (viewport.x + (viewport.width / 2)));
const frameY = (frameRect.top + (frameRect.height / 2) + (viewport.y + (viewport.height / 2)));
shapeCreationPromises.push(createFrame('App Frame',frameX,frameY,frameRect.width,frameRect.height,window.miroFrames[0]?.style?.fillColor));
}
else if (type === 'floating_boxes') {
for(let f=0; f < window.miroWidgets.length; f++) {
if (window.miroWidgets[f].type === 'shape') {
if (array[i].text_content === window.miroWidgets[f].plain_text) {
array[i].formatted_text = window.miroWidgets[f].content;
array[i].text_style = window.miroWidgets[f].style;
}
}
}
let el = array[i].element
let rect = el.getBoundingClientRect();
let text = (array[i]?.formatted_text ? array[i]?.formatted_text : array[i]?.text_content_orig ? array[i]?.text_content_orig : '');
let x = ((rect.left + rect.width / 2) + (frame.x - (frame.width / 2)));
let y = ((rect.top + rect.height / 2) + (frame.y - (frame.height / 2)));
let w = rect.width;
let h = rect.height;
let style = {
color: (array[i]?.text_style?.color ? array[i]?.text_style?.color : array[i]?.font_color ? array[i]?.font_color : '#000000'),
fillColor: (array[i]?.background_color ? array[i]?.background_color : array[i]?.text_style?.fillColor ? array[i]?.text_style?.fillColor : '#ff0000'),
fontSize: 4,
fontFamily: array[i]?.text_style?.fontFamily ? array[i]?.text_style?.fontFamily : 'arial',
textAlign: array[i]?.text_style?.textAlign ? array[i]?.text_style?.textAlign : array[i]?.text_alignment_horizontal ? 'left' : 'center',
textAlignVertical: array[i]?.text_style?.textAlignVertical ? array[i]?.text_style?.textAlignVertical : array[i]?.text_alignment_vertical ? 'top': 'middle',
borderStyle: array[i]?.text_style?.borderStyle ? array[i]?.text_style?.borderStyle : 'normal',
borderOpacity: array[i]?.text_style?.borderOpacity ? array[i]?.text_style?.borderOpacity : 1.0,
borderColor: array[i]?.text_style?.borderColor ? array[i]?.text_style?.borderColor : '#ffffff',
borderWidth: array[i]?.text_style?.borderWidth ? array[i]?.text_style?.borderWidth : 1.0,
fillOpacity: (array[i]?.opacity ? array[i]?.opacity : array[i]?.text_style?.fillOpacity ? array[i]?.text_style?.fillOpacity : 1.0)
};
shapeCreationPromises.push(createRectangle(text,x,y,w,h,style,frame,array[i].element));
}
else if (type === 'connecting_lines') {
if (array[i].startElement && array[i].endElement) {
const line = array[i];
const startEl = array[i].startElement.miro_id;
const endEl = array[i].endElement.miro_id;
const startSnap = array[i].startElement.side;
const endSnap = array[i].endElement.side;
shapeCreationPromises.push(createConnectingLine(startEl,endEl,startSnap,endSnap));
}
}
}
// Wait for all shape creations to complete
const allShapes = await Promise.all(shapeCreationPromises);
// Return the results once all are completed
return allShapes;
}
/* Function to classify a path as a square or rectangle */
function classifyShape(path, THRESHOLD) {
const bbox = path.getBBox(); // Get the bounding box
const width = bbox.width;
const height = bbox.height;
// Calculate the difference between width and height
const difference = Math.abs(width - height);
const maxDimension = Math.max(width, height);
// Normalize the difference to a ratio (0 to 1)
const ratio = difference / maxDimension;
// Classify based on the threshold
if (ratio <= THRESHOLD) {
return 'square';
} else {
return 'rectangle';
}
}
/* Function check if an element is within another */
function isElementWithin(elementA, elementB) {
const rectA = elementA.getBoundingClientRect();
const rectB = elementB.getBoundingClientRect();
// Check if B's edges are within A's edges
const isWithin =
rectB.left >= rectA.left &&
rectB.right <= rectA.right &&
rectB.top >= rectA.top &&
rectB.bottom <= rectA.bottom;
return isWithin;
}
/* Function to check if a specific text is within a specific element */
function isTextElementWithin(elementA, elementB) {
const rectA = elementA.getBoundingClientRect()
const rectB = elementB.rect;
// Check if B's edges are within A's edges
const isWithin =
rectB.left >= rectA.left &&
rectB.right <= rectA.right &&
rectB.top >= rectA.top &&
rectB.bottom <= rectA.bottom;
return isWithin;
}
/* Function to locate the SVG html text element that is within a specific SVG element */
function findTHtmlTextElementWithin(elementA,string) {
const rectA = elementA.getBoundingClientRect();
const arrayOfTextElements = document.querySelectorAll('tspan:not([data-matched])');
let rectB;
for(let i=0; i < arrayOfTextElements.length; i++) {
if (string !== '' && (arrayOfTextElements[i].textContent&& arrayOfTextElements[i].textConent !== '')) {
rectB = arrayOfTextElements[i].getBoundingClientRect();
// Check if B's edges are within A's edges
let isWithin =
rectB.left >= rectA.left &&
rectB.right <= rectA.right &&
rectB.top >= rectA.top &&
rectB.bottom <= rectA.bottom;
if (isWithin) {
//if (string === 'F84379') {debugger;}
return arrayOfTextElements[i];
}
}
}
}
/* Function to check if a point is near a square */
function isNearSquare(point, threshold = 34) {
const squares = document.querySelectorAll('path[data-type="sticky_note"]');
for(let i=0; i < squares.length;i++) {
const rect = squares[i].getBoundingClientRect();
const { left, right, top, bottom } = rect;
// Check if the point is close to any edge of the square
const nearLeft = Math.abs(point.x - left) <= threshold && point.y >= top && point.y <= bottom;
const nearRight = Math.abs(point.x - right) <= threshold && point.y >= top && point.y <= bottom;
const nearTop = Math.abs(point.y - top) <= threshold && point.x >= left && point.x <= right;
const nearBottom = Math.abs(point.y - bottom) <= threshold && point.x >= left && point.x <= right;
if (nearLeft || nearRight || nearTop || nearBottom) {
return {
html_id: squares[i].id,
side: (nearLeft ? 'left' : (nearRight ? 'right' : (nearTop ? 'top' : (nearBottom ? 'bottom' : null))))
};
}
}
return null;
}
/* Function to capture and log the X, Y coordinates of a mouse click */
function getClickCoordinates(event) {
const x = event.clientX; // X coordinate of the mouse click
const y = event.clientY; // Y coordinate of the mouse click
console.log(`Mouse clicked at X: ${x}, Y: ${y}`);
}
/* Attach the event listener to the document */
//document.addEventListener('click', getClickCoordinates); // (used only for debugging purposes)
/* Function to identify the location of an element taking transformations into a account */
function parseTransformMatrix(matrixString) {
let matrixValues = matrixString.replaceAll('matrix(','');
matrixValues = matrixValues.replaceAll(')','');
matrixValues = matrixValues.split(' ');
return {
a: parseFloat(matrixValues[0]), // Scale X
b: parseFloat(matrixValues[1]), // Skew Y
c: parseFloat(matrixValues[2]), // Skew X
d: parseFloat(matrixValues[3]), // Scale Y
e: parseFloat(matrixValues[4]), // Translate X
f: parseFloat(matrixValues[5]) // Translate Y
};
}
/* Function to identify to a point to determine its location */
function applyMatrixToPoint(x, y, matrix) {
let result = {
x: matrix.a * x + matrix.c * y + matrix.e,
y: matrix.b * x + matrix.d * y + matrix.f
};
return result;
}
/* Function to parse the 'd' attribute and extract line segments */
function parsePathElement(path) {
const d = path.getAttribute('d'); // Get the 'd' attribute
const commands = d.match(/[a-zA-Z][^a-zA-Z]*/g); // Split commands and their coordinates
let previousPoint = null; // Track the previous point for segments
commands.forEach(command => {
const type = command[0]; // The command type (e.g., M, L)
const values = command.slice(1).trim().split(/[\s,]+/).map(Number); // Extract coordinates
if (type === 'M' || type === 'L') {
const x = values[0];
const y = values[1];
if (previousPoint) {
// Store the line segment coordinates
lines.push({
x1: previousPoint.x,
y1: previousPoint.y,
x2: x,
y2: y
});
}
// Update the previous point
previousPoint = { x, y };
}
});
}
/* Function to get intersection point */
function getIntersection(vLine, hLine) {
// Getting the bounding rectangles of vertical and horizontal lines
const vRect = vLine.getBoundingClientRect(); // Vertical line bounding box
const hRect = hLine.getBoundingClientRect(); // Horizontal line bounding box
// The vertical line (vLine) must have the same x position in the range of the horizontal line (hLine)
// And the horizontal line (hLine) must have the same y position in the range of the vertical line (vLine)
if (
vRect.left <= hRect.right && vRect.right >= hRect.left && // Vertical line intersects with horizontal line's x range
hRect.top <= vRect.bottom && hRect.bottom >= vRect.top // Horizontal line intersects with vertical line's y range
) {
// Return the intersection point (x, y), using the center of the bounding box
return {
x: (vRect.left + vRect.right) / 2,
y: (hRect.top + hRect.bottom) / 2
};
}
return null; // No intersection
}
/* Function to calculate boxes from line intersections */
function generateCellsFromIntersections3(verticalLines, horizontalLines, color) {
const cells = [];
let count = 0;
// Iterate over vertical lines using a for loop
for (let i = 0; i < verticalLines.length - 1; i++) {
const vLine1 = verticalLines[i];
const vLine2 = verticalLines[i + 1];
// Iterate over horizontal lines using a for loop
for (let j = 0; j < horizontalLines.length - 1; j++) {
const hLine1 = horizontalLines[j];
const hLine2 = horizontalLines[j + 1];
// Get the intersection points (e.g., use the bounding boxes of the lines)
const intersectionTopLeft = getIntersection(vLine1, hLine1);
const intersectionBottomRight = getIntersection(vLine2, hLine2);
if (intersectionTopLeft && intersectionBottomRight) {
let { x: x1, y: y1 } = intersectionTopLeft; // Top-left corner
let { x: x2, y: y2 } = intersectionBottomRight; // Bottom-right corner
// Create a new div element for the cell
const cell = document.createElement('div');
cell.style.position = 'absolute'; // Position using absolute positioning
// Position the cell based on the top-left corner of the intersection
cell.style.left = `${x1}px`; // Horizontal position of the cell
cell.style.top = `${y1}px`; // Vertical position of the cell
// Set the width and height based on the intersection dimensions
cell.style.width = `${(Math.abs(x2 - x1) - 1)}px`; // Width based on intersection distance
cell.style.height = `${(Math.abs(y2 - y1) - 1)}px`; // Height based on intersection distance
// Style the cell (e.g., color, border)
cell.style.backgroundColor = 'white'; // Color for the cell
cell.style.border = `1px solid ${color}`; // Border for visibility
cell.id = `base_cell_${count}`;
cell.className = 'base_cell';
cell.style.zIndex = '-1';
cell.setAttribute('fill', '#ffffff');
// Append the cell to the parent container (usually an SVG or HTML container)
document.getElementById('output').appendChild(cell); // Append to the body or a specific parent element
count = count + 1;
cells.push(cell);
}
}
}
let firstCell = cells[0].getBoundingClientRect();
let lastCell = cells[cells.length - 1].getBoundingClientRect();
window.mainTable = {
top: Math.trunc(firstCell.top),
left: Math.trunc(firstCell.left),
bottom: Math.trunc(lastCell.bottom),
right: Math.trunc(lastCell.right),
width: (Math.trunc(lastCell.right) - Math.trunc(firstCell.left)),
height: (Math.trunc(lastCell.bottom) - Math.trunc(firstCell.top))
}
return cells;
}
/* Function to start parsing the created SVGs created by the PDF parser */
function postProcessSVG(svg) {
const lines = [];
// Get all lines (or paths that represent table borders)
var paths = svg.querySelectorAll('svg path[stroke-linejoin="miter"]');
var table = svg.querySelectorAll('#output svg g > [clip-path="url(#clippath3)"]')[0];
var tableHeight = table.getBoundingClientRect().height;
var tableWidth = table.getBoundingClientRect().width;
for(let i=0; i < paths.length; i++) {
//if (paths[i].getBoundingClientRect().height + 52 > tableHeight || paths[i].getBoundingClientRect().width === tableWidth) {
if ((paths[i].getBoundingClientRect().height + 52 > tableHeight || paths[i].getBoundingClientRect().height + 52 > (tableHeight*0.70)) || paths[i].getBoundingClientRect().width === tableWidth) {
paths[i].setAttribute('id',`table_line${i}`);