-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPDFElements.vue
More file actions
903 lines (801 loc) · 31.1 KB
/
PDFElements.vue
File metadata and controls
903 lines (801 loc) · 31.1 KB
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
<!--
SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<div :style="{ width, height }" class="pdf-elements-root">
<div
v-if="pdfDocuments.length"
class="pages-container"
:style="{ transform: `scale(${visualScale / scale})`, transformOrigin: 'top center' }"
>
<div v-for="(pdfDoc, docIndex) in pdfDocuments" :key="docIndex">
<div v-for="(page, pIndex) in pdfDoc.pages" :key="`${docIndex}-${pIndex}`" class="page-slot">
<div class="page-wrapper"
@mousedown="selectPage(docIndex, pIndex)"
@touchstart="selectPage(docIndex, pIndex)">
<div class="page-canvas" :class="{ 'shadow-outline': docIndex === selectedDocIndex && pIndex === selectedPageIndex }">
<PDFPage
:ref="`page${docIndex}-${pIndex}`"
:page="page"
:scale="scale"
@onMeasure="onMeasure($event, docIndex, pIndex)"
/>
<div
class="overlay"
>
<div
v-if="isAddingMode && previewPageDocIndex === docIndex && previewPageIndex === pIndex && previewElement && previewVisible"
class="preview-element"
:style="{
left: `${previewPosition.x * previewScale.x}px`,
top: `${previewPosition.y * previewScale.y}px`,
width: `${previewElement.width * previewScale.x}px`,
height: `${previewElement.height * previewScale.y}px`,
}"
>
<slot
name="custom"
:object="previewElement"
:isSelected="false"
/>
</div>
<DraggableElement
v-for="object in pdfDoc.allObjects[pIndex]"
:key="object.id"
:ref="`draggable${docIndex}-${pIndex}-${object.id}`"
:object="object"
:pages-scale="getRenderPageScale(docIndex, pIndex)"
:page-width="getPageWidth(docIndex, pIndex)"
:page-height="getPageHeight(docIndex, pIndex)"
:on-update="(payload) => updateObject(docIndex, object.id, payload)"
:on-delete="() => deleteObject(docIndex, object.id)"
:on-drag-start="(mouseX, mouseY, pointerOffset, dragShift) => startDraggingElement(docIndex, pIndex, object, mouseX, mouseY, pointerOffset, dragShift)"
:on-drag-move="updateDraggingPosition"
:on-drag-end="stopDraggingElement"
:is-being-dragged-globally="isDraggingElement && draggingObject && draggingObject.id === object.id"
:dragging-client-pos="draggingClientPosition"
:current-doc-index="docIndex"
:current-page-index="pIndex"
:global-drag-doc-index="draggingDocIndex"
:global-drag-page-index="draggingPageIndex"
:show-selection-ui="showSelectionHandles && !hideSelectionUI && object.resizable !== false"
:show-default-actions="showElementActions && !hideSelectionUI"
>
<template #default="slotProps">
<slot
:name="slotProps.object.type ? `element-${slotProps.object.type}` : 'custom'"
:object="slotProps.object"
:onDelete="slotProps.onDelete"
:onResize="slotProps.onResize"
>
<slot
name="custom"
:object="slotProps.object"
:onDelete="slotProps.onDelete"
:onResize="slotProps.onResize"
/>
</slot>
</template>
<template #actions="slotProps">
<slot
name="actions"
:object="slotProps.object"
:onDelete="slotProps.onDelete"
/>
</template>
</DraggableElement>
</div>
</div>
<div v-if="showPageFooter" class="page-footer">
<span>{{ pdfDoc.name }}</span>
<span>{{ formatPageNumber(pIndex + 1, pdfDoc.numPages) }}</span>
</div>
</div>
</div>
</div>
</div>
<div
v-if="isDraggingElement && draggingObject"
class="drag-portal"
:style="{
position: 'fixed',
left: `${draggingClientPosition.x}px`,
top: `${draggingClientPosition.y}px`,
width: `${draggingObject.width * draggingScale}px`,
height: `${draggingObject.height * draggingScale}px`,
pointerEvents: 'none',
}"
>
<slot
:name="draggingObject.type ? `element-${draggingObject.type}` : 'custom'"
:object="draggingObject"
:isSelected="false"
>
<slot
name="custom"
:object="draggingObject"
:isSelected="false"
/>
</slot>
</div>
</div>
</template>
<script>
import debounce from 'debounce'
import PDFPage from './PDFPage.vue'
import DraggableElement from './DraggableElement.vue'
import { readAsPDF, readAsArrayBuffer } from '../utils/asyncReader.js'
export default {
name: 'PDFElements',
components: {
PDFPage,
DraggableElement,
},
props: {
width: {
type: String,
default: '100%',
},
height: {
type: String,
default: '100%',
},
initFiles: {
type: Array,
default: () => [],
},
initFileNames: {
type: Array,
default: () => [],
},
initialScale: {
type: Number,
default: 1,
},
showPageFooter: {
type: Boolean,
default: true,
},
hideSelectionUI: {
type: Boolean,
default: false,
},
showSelectionHandles: {
type: Boolean,
default: true,
},
showElementActions: {
type: Boolean,
default: true,
},
pageCountFormat: {
type: String,
default: '{currentPage} of {totalPages}',
},
autoFitZoom: {
type: Boolean,
default: false,
},
},
data() {
return {
scale: this.initialScale,
pdfDocuments: [],
selectedDocIndex: -1,
selectedPageIndex: -1,
isAddingMode: false,
previewElement: null,
previewPosition: { x: 0, y: 0 },
previewScale: { x: 1, y: 1 },
previewPageDocIndex: -1,
previewPageIndex: -1,
previewVisible: false,
pagesBoundingRects: {},
isDraggingElement: false,
draggingObject: null,
draggingDocIndex: -1,
draggingPageIndex: -1,
draggingClientPosition: { x: 0, y: 0 },
draggingScale: 1,
draggingInitialMouseOffset: { x: 0, y: 0 },
draggingElementShift: { x: 0, y: 0 },
lastMouseClientPos: { x: 0, y: 0 },
viewportRafId: 0,
objectIndexCache: {},
zoomRafId: null,
boundHandleWheel: null,
debouncedApplyZoom: null,
visualScale: this.initialScale,
}
},
mounted() {
this.boundHandleWheel = this.handleWheel.bind(this)
this.debouncedApplyZoom = debounce(this.commitZoom, 150)
this.init()
document.addEventListener('mousemove', this.handleMouseMove)
document.addEventListener('touchmove', this.handleMouseMove, { passive: true })
document.addEventListener('mouseup', this.finishAdding)
document.addEventListener('touchend', this.finishAdding)
document.addEventListener('keydown', this.handleKeyDown)
window.addEventListener('scroll', this.onViewportScroll, { passive: true })
window.addEventListener('resize', this.onViewportScroll)
this.$el?.addEventListener('scroll', this.onViewportScroll, { passive: true })
this.$el?.addEventListener('wheel', this.boundHandleWheel, { passive: false })
if (this.autoFitZoom) {
window.addEventListener('resize', this.adjustZoomToFit)
}
},
beforeUnmount() {
if (this.zoomRafId) {
cancelAnimationFrame(this.zoomRafId)
}
this.debouncedApplyZoom?.clear?.()
if (this.boundHandleWheel) {
this.$el?.removeEventListener('wheel', this.boundHandleWheel)
}
document.removeEventListener('mousemove', this.handleMouseMove)
document.removeEventListener('touchmove', this.handleMouseMove)
document.removeEventListener('mouseup', this.finishAdding)
document.removeEventListener('touchend', this.finishAdding)
document.removeEventListener('keydown', this.handleKeyDown)
window.removeEventListener('scroll', this.onViewportScroll)
window.removeEventListener('resize', this.onViewportScroll)
this.$el?.removeEventListener('scroll', this.onViewportScroll)
if (this.autoFitZoom) {
window.removeEventListener('resize', this.adjustZoomToFit)
}
if (this.viewportRafId) {
window.cancelAnimationFrame(this.viewportRafId)
this.viewportRafId = 0
}
},
methods: {
async init() {
if (!this.initFiles || this.initFiles.length === 0) return
const docs = []
for (let i = 0; i < this.initFiles.length; i++) {
const file = this.initFiles[i]
const name = this.initFileNames[i] || `document-${i + 1}.pdf`
let pdfDoc
if (file instanceof Blob) {
const buffer = await readAsArrayBuffer(file)
pdfDoc = await readAsPDF({ data: buffer })
} else {
pdfDoc = await readAsPDF(file)
}
const pages = []
for (let p = 1; p <= pdfDoc.numPages; p++) {
pages.push(pdfDoc.getPage(p))
}
docs.push({
name,
file,
pdfDoc,
numPages: pdfDoc.numPages,
pages,
pagesScale: Array(pdfDoc.numPages).fill(this.scale),
allObjects: Array(pdfDoc.numPages).fill(0).map(() => []),
})
}
this.pdfDocuments = docs
if (docs.length) {
this.selectedDocIndex = 0
this.selectedPageIndex = 0
this.$emit('pdf-elements:end-init', { docsCount: docs.length })
}
},
selectPage(docIndex, pageIndex) {
this.selectedDocIndex = docIndex
this.selectedPageIndex = pageIndex
},
startDraggingElement(docIndex, pageIndex, object, mouseX, mouseY, pointerOffset, dragShift) {
this.isDraggingElement = true
this.draggingObject = { ...object }
this.draggingDocIndex = docIndex
this.draggingPageIndex = pageIndex
this.draggingScale = this.getDisplayedPageScale(docIndex, pageIndex)
this.lastMouseClientPos.x = mouseX
this.lastMouseClientPos.y = mouseY
this.draggingElementShift = dragShift && typeof dragShift.x === 'number' && typeof dragShift.y === 'number'
? dragShift
: { x: 0, y: 0 }
const pageKey = `${docIndex}-${pageIndex}`
if (!this.pagesBoundingRects[pageKey]) {
this.cachePageBounds()
}
const pageRect = this.pagesBoundingRects[pageKey]?.rect
if (pointerOffset && typeof pointerOffset.x === 'number' && typeof pointerOffset.y === 'number') {
this.draggingInitialMouseOffset.x = pointerOffset.x
this.draggingInitialMouseOffset.y = pointerOffset.y
this.draggingClientPosition.x = mouseX - this.draggingInitialMouseOffset.x
this.draggingClientPosition.y = mouseY - this.draggingInitialMouseOffset.y
} else if (pageRect) {
const elementScreenX = pageRect.left + (object.x * this.draggingScale)
const elementScreenY = pageRect.top + (object.y * this.draggingScale)
this.draggingInitialMouseOffset.x = mouseX - elementScreenX
this.draggingInitialMouseOffset.y = mouseY - elementScreenY
this.draggingClientPosition.x = mouseX - this.draggingInitialMouseOffset.x
this.draggingClientPosition.y = mouseY - this.draggingInitialMouseOffset.y
}
this.cachePageBounds()
},
updateDraggingPosition(clientX, clientY) {
if (!this.isDraggingElement) return
this.lastMouseClientPos.x = clientX
this.lastMouseClientPos.y = clientY
this.draggingClientPosition.x = clientX - this.draggingInitialMouseOffset.x
this.draggingClientPosition.y = clientY - this.draggingInitialMouseOffset.y
},
stopDraggingElement() {
if (this.draggingObject) {
const objectId = this.draggingObject.id
const originalDocIndex = this.draggingDocIndex
const finalPageIndex = this.checkAndMoveObjectPage(
this.draggingDocIndex,
objectId,
this.lastMouseClientPos.x,
this.lastMouseClientPos.y
)
if (finalPageIndex !== undefined) {
this.$nextTick(() => {
this.selectPage(originalDocIndex, finalPageIndex)
const refKey = `draggable${originalDocIndex}-${finalPageIndex}-${objectId}`
const draggableRefs = this.$refs[refKey]
if (draggableRefs && Array.isArray(draggableRefs) && draggableRefs[0]) {
draggableRefs[0].isSelected = true
}
})
}
}
this.isDraggingElement = false
this.draggingObject = null
this.draggingDocIndex = -1
this.draggingPageIndex = -1
this.draggingElementShift = { x: 0, y: 0 }
},
startAddingElement(templateObject) {
if (!this.pdfDocuments.length) return
this.isAddingMode = true
this.previewElement = { ...templateObject }
this.previewPageDocIndex = 0
this.previewPageIndex = 0
this.previewVisible = false
this.previewScale = { x: 1, y: 1 }
this.cachePageBounds()
},
cachePageBounds() {
this.pagesBoundingRects = {}
for (let docIdx = 0; docIdx < this.pdfDocuments.length; docIdx++) {
for (let pageIdx = 0; pageIdx < this.pdfDocuments[docIdx].pages.length; pageIdx++) {
const canvas = this.getPageCanvasElement(docIdx, pageIdx)
if (!canvas) continue
const rect = canvas.getBoundingClientRect()
this.pagesBoundingRects[`${docIdx}-${pageIdx}`] = {
docIndex: docIdx,
pageIndex: pageIdx,
rect,
}
}
}
},
getDisplayedPageScale(docIndex, pageIndex) {
const doc = this.pdfDocuments[docIndex]
if (!doc) return 1
const base = doc.pagesScale[pageIndex] || 1
const factor = this.visualScale && this.scale ? (this.visualScale / this.scale) : 1
return base * factor
},
getRenderPageScale(docIndex, pageIndex) {
const doc = this.pdfDocuments[docIndex]
if (!doc) return 1
return doc.pagesScale[pageIndex] || 1
},
getPageComponent(docIndex, pageIndex) {
const pageRef = this.$refs[`page${docIndex}-${pageIndex}`]
return pageRef && Array.isArray(pageRef) && pageRef[0] ? pageRef[0] : null
},
getPageCanvasElement(docIndex, pageIndex) {
const pageComponent = this.getPageComponent(docIndex, pageIndex)
return pageComponent ? (pageComponent.$el || pageComponent) : null
},
onViewportScroll() {
if (this.viewportRafId) return
this.viewportRafId = window.requestAnimationFrame(() => {
if (this.isAddingMode || this.isDraggingElement) {
this.cachePageBounds()
}
this.viewportRafId = 0
})
},
handleMouseMove(event) {
if (!this.isAddingMode || !this.previewElement) return
const clientX = event.type.includes('touch') ? event.touches[0].clientX : event.clientX
const clientY = event.type.includes('touch') ? event.touches[0].clientY : event.clientY
let foundPage = false
for (const key in this.pagesBoundingRects) {
const { docIndex, pageIndex, rect } = this.pagesBoundingRects[key]
if (clientX >= rect.left && clientX <= rect.right &&
clientY >= rect.top && clientY <= rect.bottom) {
this.previewPageDocIndex = docIndex
this.previewPageIndex = pageIndex
foundPage = true
const canvasEl = this.getPageCanvasElement(docIndex, pageIndex)
const pagesScale = this.pdfDocuments[docIndex]?.pagesScale?.[pageIndex] || 1
const layoutWidth = canvasEl?.offsetWidth || rect.width
const layoutHeight = canvasEl?.offsetHeight || rect.height
const layoutScaleX = layoutWidth ? rect.width / layoutWidth : 1
const layoutScaleY = layoutHeight ? rect.height / layoutHeight : 1
const relX = (clientX - rect.left) / layoutScaleX / pagesScale
const relY = (clientY - rect.top) / layoutScaleY / pagesScale
const pageWidth = layoutWidth / pagesScale
const pageHeight = layoutHeight / pagesScale
this.previewScale.x = pagesScale * layoutScaleX
this.previewScale.y = pagesScale * layoutScaleY
let x = relX - this.previewElement.width / 2
let y = relY - this.previewElement.height / 2
x = Math.max(0, Math.min(x, pageWidth - this.previewElement.width))
y = Math.max(0, Math.min(y, pageHeight - this.previewElement.height))
this.previewPosition.x = x
this.previewPosition.y = y
this.previewVisible = true
break
}
}
if (!foundPage) {
this.previewVisible = false
this.previewScale = { x: 1, y: 1 }
}
},
handleKeyDown(event) {
if (event.key === 'Escape' && this.isAddingMode) {
this.cancelAdding()
}
},
handleWheel(event) {
if (!event.ctrlKey) return
event.preventDefault()
const factor = 1 - (event.deltaY * 0.002)
const nextVisual = Math.max(0.5, Math.min(3.0, this.visualScale * factor))
this.visualScale = nextVisual
this.debouncedApplyZoom()
},
commitZoom() {
const newScale = this.visualScale
this.scale = newScale
this.pdfDocuments.forEach((doc) => {
doc.pagesScale = doc.pagesScale.map(() => this.scale)
})
this.cachePageBounds()
},
finishAdding() {
if (!this.isAddingMode || !this.previewElement) return
if (!this.previewVisible) return
const objectToAdd = {
...this.previewElement,
id: `obj-${Date.now()}`,
x: Math.round(this.previewPosition.x),
y: Math.round(this.previewPosition.y),
}
const doc = this.pdfDocuments[this.previewPageDocIndex]
const pageWidth = this.getPageWidth(this.previewPageDocIndex, this.previewPageIndex)
const pageHeight = this.getPageHeight(this.previewPageDocIndex, this.previewPageIndex)
if (objectToAdd.x < 0 || objectToAdd.y < 0 ||
objectToAdd.x + objectToAdd.width > pageWidth ||
objectToAdd.y + objectToAdd.height > pageHeight) {
this.cancelAdding()
return
}
doc.allObjects[this.previewPageIndex].push(objectToAdd)
const pageIndex = this.previewPageIndex
const docIndex = this.previewPageDocIndex
const objectId = objectToAdd.id
this.cancelAdding()
this.$nextTick(() => {
const refKey = `draggable${docIndex}-${pageIndex}-${objectId}`
const draggableRefs = this.$refs[refKey]
if (draggableRefs && Array.isArray(draggableRefs) && draggableRefs[0]) {
draggableRefs[0].isSelected = true
}
})
},
cancelAdding() {
this.isAddingMode = false
this.previewElement = null
this.previewVisible = false
},
addObjectToPage(object, pageIndex = this.selectedPageIndex, docIndex = this.selectedDocIndex) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return false
if (pageIndex < 0 || pageIndex >= this.pdfDocuments[docIndex].pages.length) return false
const doc = this.pdfDocuments[docIndex]
const pageRef = this.getPageComponent(docIndex, pageIndex)
if (!pageRef) return false
const pageWidth = this.getPageWidth(docIndex, pageIndex)
const pageHeight = this.getPageHeight(docIndex, pageIndex)
if (object.x < 0 || object.y < 0 ||
object.x + object.width > pageWidth ||
object.y + object.height > pageHeight) {
return false
}
doc.allObjects = doc.allObjects.map((objects, pIndex) =>
pIndex === pageIndex ? [...objects, object] : objects,
)
return true
},
getAllObjects(docIndex = this.selectedDocIndex) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return []
const doc = this.pdfDocuments[docIndex]
const scale = this.scale || 1
const result = []
doc.allObjects.forEach((pageObjects, pageIndex) => {
const pageRef = this.getPageComponent(docIndex, pageIndex)
if (!pageRef) return
const measurement = pageRef.getCanvasMeasurement()
const normalizedCanvasHeight = measurement.canvasHeight / scale
pageObjects.forEach(object => {
result.push({
...object,
pageIndex,
pageNumber: pageIndex + 1,
scale,
normalizedCoordinates: {
llx: parseInt(object.x, 10),
lly: parseInt(normalizedCanvasHeight - object.y, 10),
ury: parseInt(normalizedCanvasHeight - object.y - object.height, 10),
},
})
})
})
return result
},
updateObject(docIndex, objectId, payload) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
const doc = this.pdfDocuments[docIndex]
const cacheKey = `${docIndex}-${objectId}`
let currentPageIndex = this.objectIndexCache[cacheKey]
if (currentPageIndex === undefined) {
doc.allObjects.forEach((objects, pIndex) => {
if (objects.find(o => o.id === objectId)) {
currentPageIndex = pIndex
this.objectIndexCache[cacheKey] = pIndex
}
})
}
if (currentPageIndex === undefined) return
const targetObject = doc.allObjects[currentPageIndex]?.find(o => o.id === objectId)
if (!targetObject) return
if (payload._globalDrag && payload._mouseX !== undefined && payload._mouseY !== undefined) {
const mouseX = payload._mouseX
const mouseY = payload._mouseY
if (!this.pagesBoundingRects || Object.keys(this.pagesBoundingRects).length === 0) {
this.cachePageBounds()
}
const currentPageRect = this.pagesBoundingRects[`${docIndex}-${currentPageIndex}`]?.rect
if (currentPageRect) {
const pagesScale = this.getDisplayedPageScale(docIndex, currentPageIndex)
const relX = (mouseX - currentPageRect.left - this.draggingElementShift.x) / pagesScale - (this.draggingInitialMouseOffset.x / pagesScale)
const relY = (mouseY - currentPageRect.top - this.draggingElementShift.y) / pagesScale - (this.draggingInitialMouseOffset.y / pagesScale)
doc.allObjects[currentPageIndex] = doc.allObjects[currentPageIndex].map(obj =>
obj.id === objectId ? { ...obj, x: relX, y: relY } : obj
)
}
return
}
if (payload.x !== undefined || payload.y !== undefined) {
const newX = payload.x !== undefined ? payload.x : targetObject.x
const newY = payload.y !== undefined ? payload.y : targetObject.y
const objWidth = payload.width !== undefined ? payload.width : targetObject.width
const objHeight = payload.height !== undefined ? payload.height : targetObject.height
let bestPageIndex = currentPageIndex
let maxVisibleArea = 0
for (let pIndex = 0; pIndex < doc.pages.length; pIndex++) {
const pageWidth = this.getPageWidth(docIndex, pIndex)
const pageHeight = this.getPageHeight(docIndex, pIndex)
const visibleLeft = Math.max(0, newX)
const visibleTop = Math.max(0, newY)
const visibleRight = Math.min(pageWidth, newX + objWidth)
const visibleBottom = Math.min(pageHeight, newY + objHeight)
if (visibleRight > visibleLeft && visibleBottom > visibleTop) {
const visibleArea = (visibleRight - visibleLeft) * (visibleBottom - visibleTop)
if (visibleArea > maxVisibleArea) {
maxVisibleArea = visibleArea
bestPageIndex = pIndex
}
}
}
if (bestPageIndex !== currentPageIndex) {
const pageWidth = this.getPageWidth(docIndex, bestPageIndex)
const pageHeight = this.getPageHeight(docIndex, bestPageIndex)
const adjustedX = Math.max(0, Math.min(newX, pageWidth - objWidth))
const adjustedY = Math.max(0, Math.min(newY, pageHeight - objHeight))
doc.allObjects[currentPageIndex] = doc.allObjects[currentPageIndex].filter(
obj => obj.id !== objectId
)
const updatedObject = {
...targetObject,
...payload,
x: adjustedX,
y: adjustedY,
}
doc.allObjects[bestPageIndex].push(updatedObject)
this.objectIndexCache[`${docIndex}-${objectId}`] = bestPageIndex
return
}
const pageWidth = this.getPageWidth(docIndex, currentPageIndex)
const pageHeight = this.getPageHeight(docIndex, currentPageIndex)
if (newX < 0 || newY < 0 ||
newX + objWidth > pageWidth ||
newY + objHeight > pageHeight) {
return
}
}
doc.allObjects = doc.allObjects.map(objects =>
objects.map(object => (object.id === objectId ? { ...object, ...payload } : object)),
)
},
deleteObject(docIndex, objectId) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
const doc = this.pdfDocuments[docIndex]
doc.allObjects = doc.allObjects.map(objects =>
objects.filter(object => object.id !== objectId),
)
delete this.objectIndexCache[`${docIndex}-${objectId}`]
},
checkAndMoveObjectPage(docIndex, objectId, mouseX, mouseY) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return undefined
const doc = this.pdfDocuments[docIndex]
const cacheKey = `${docIndex}-${objectId}`
let currentPageIndex = this.objectIndexCache[cacheKey]
if (currentPageIndex === undefined) {
doc.allObjects.forEach((objects, pIndex) => {
if (objects.find(o => o.id === objectId)) {
currentPageIndex = pIndex
this.objectIndexCache[cacheKey] = pIndex
}
})
}
if (currentPageIndex === undefined) return undefined
const targetObject = doc.allObjects[currentPageIndex]?.find(o => o.id === objectId)
if (!targetObject) return currentPageIndex
let targetPageIndex = currentPageIndex
for (const key in this.pagesBoundingRects) {
const { docIndex: rectDocIndex, pageIndex, rect } = this.pagesBoundingRects[key]
if (rectDocIndex === docIndex &&
mouseX >= rect.left && mouseX <= rect.right &&
mouseY >= rect.top && mouseY <= rect.bottom) {
targetPageIndex = pageIndex
break
}
}
const targetPageRect = this.pagesBoundingRects[`${docIndex}-${targetPageIndex}`]?.rect
if (!targetPageRect) return currentPageIndex
const pagesScale = this.getDisplayedPageScale(docIndex, targetPageIndex)
const relX = (mouseX - targetPageRect.left - this.draggingElementShift.x) / pagesScale - (this.draggingInitialMouseOffset.x / pagesScale)
const relY = (mouseY - targetPageRect.top - this.draggingElementShift.y) / pagesScale - (this.draggingInitialMouseOffset.y / pagesScale)
const pageWidth = this.getPageWidth(docIndex, targetPageIndex)
const pageHeight = this.getPageHeight(docIndex, targetPageIndex)
const clampedX = Math.max(0, Math.min(relX, pageWidth - targetObject.width))
const clampedY = Math.max(0, Math.min(relY, pageHeight - targetObject.height))
if (targetPageIndex !== currentPageIndex) {
doc.allObjects[currentPageIndex] = doc.allObjects[currentPageIndex].filter(
obj => obj.id !== objectId
)
doc.allObjects[targetPageIndex].push({
...targetObject,
x: clampedX,
y: clampedY,
})
this.objectIndexCache[cacheKey] = targetPageIndex
} else if (clampedX !== targetObject.x || clampedY !== targetObject.y) {
doc.allObjects[currentPageIndex] = doc.allObjects[currentPageIndex].map(obj =>
obj.id === objectId ? { ...obj, x: clampedX, y: clampedY } : obj
)
}
return targetPageIndex
},
onMeasure(e, docIndex, pageIndex) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
this.pdfDocuments[docIndex].pagesScale[pageIndex] = e.scale
this.cachePageBounds()
},
formatPageNumber(currentPage, totalPages) {
return this.pageCountFormat
.replace('{currentPage}', currentPage)
.replace('{totalPages}', totalPages)
},
getPageWidth(docIndex, pageIndex) {
const pageRef = this.getPageComponent(docIndex, pageIndex)
if (!pageRef) return 0
const doc = this.pdfDocuments[docIndex]
const pagesScale = doc.pagesScale[pageIndex] || 1
return pageRef.getCanvasMeasurement().canvasWidth / pagesScale
},
getPageHeight(docIndex, pageIndex) {
const pageRef = this.getPageComponent(docIndex, pageIndex)
if (!pageRef) return 0
const doc = this.pdfDocuments[docIndex]
const pagesScale = doc.pagesScale[pageIndex] || 1
return pageRef.getCanvasMeasurement().canvasHeight / pagesScale
},
calculateOptimalScale(maxPageWidth) {
const containerWidth = this.$el?.clientWidth || 0
if (!containerWidth || !maxPageWidth) return 1
const availableWidth = containerWidth - 40
return Math.max(0.1, Math.min(2, availableWidth / maxPageWidth))
},
adjustZoomToFit() {
if (!this.autoFitZoom || !this.pdfDocuments.length) return
const canvases = this.$el?.querySelectorAll('canvas')
if (!canvases?.length) return
const maxCanvasWidth = Math.max(...Array.from(canvases).map(canvas =>
canvas.width / (this.scale || 1),
))
const optimalScale = this.calculateOptimalScale(maxCanvasWidth)
if (Math.abs(optimalScale - this.scale) > 0.01) {
this.scale = optimalScale
this.visualScale = optimalScale
}
},
},
}
</script>
<style scoped>
.pdf-elements-root {
width: 100%;
height: 100%;
overflow-y: auto;
overflow-x: hidden;
box-sizing: border-box;
}
.pages-container {
width: 100%;
padding: 20px 0 0 0;
text-align: center;
background: #f7fafc;
overflow: hidden;
}
.page-slot {
margin: 0 auto;
}
.page-wrapper {
display: inline-block;
margin-bottom: 0;
}
.page-canvas {
position: relative;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
}
.shadow-outline {
box-shadow: 0 0 0 3px rgb(66 153 225 / 50%);
}
.preview-element {
position: absolute;
opacity: 0.7;
pointer-events: none;
}
.drag-ghost {
position: fixed;
opacity: 0.9;
pointer-events: none;
z-index: 10000;
transform-origin: top left;
transition: none;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}
.overlay {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
width: 100%;
height: 100%;
}
.page-footer {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px 20px 20px;
color: #4b5563;
font-size: 14px;
}
</style>