Compare commits

..

5 Commits

Author SHA1 Message Date
Juan Felipe Zapata Moreno
d28a31e1bc .env example modificado 2025-09-24 09:05:46 -06:00
19ae058e2d vue datepicker y layouts separados 2025-09-23 19:28:38 -06:00
433994cda2 Maquetador de documentos (#2)
Co-authored-by: Juan Felipe Zapata Moreno <zapata_pipe@hotmail.com>
Reviewed-on: #2
2025-09-23 19:28:13 -06:00
703b39e052 redireccion 2025-09-23 19:26:09 -06:00
Juan Felipe Zapata Moreno
5e56c71bca ADD: Se arregló el toolbar para cambios al texto así como la selección de hoja 2025-09-23 15:49:18 -06:00
8 changed files with 511 additions and 400 deletions

View File

@ -1,10 +1,10 @@
VITE_API_URL=http://backend.holos.test:8080 VITE_API_URL=http://localhost:8080
VITE_BASE_URL=http://frontend.holos.test VITE_BASE_URL=http://frontend.holos.test
VITE_REVERB_APP_ID= VITE_REVERB_APP_ID=
VITE_REVERB_APP_KEY= VITE_REVERB_APP_KEY=
VITE_REVERB_APP_SECRET= VITE_REVERB_APP_SECRET=
VITE_REVERB_HOST="backend.holos.test" VITE_REVERB_HOST="localhost"
VITE_REVERB_PORT=8080 VITE_REVERB_PORT=8080
VITE_REVERB_SCHEME=http VITE_REVERB_SCHEME=http
VITE_REVERB_ACTIVE=false VITE_REVERB_ACTIVE=false

View File

@ -10,6 +10,7 @@ services:
- frontend-v1:/var/www/gols-frontend-v1/node_modules - frontend-v1:/var/www/gols-frontend-v1/node_modules
networks: networks:
- gols-network - gols-network
mem_limit: 512m
volumes: volumes:
frontend-v1: frontend-v1:
driver: local driver: local

5
limpiar_docker.sh Executable file
View File

@ -0,0 +1,5 @@
echo "eliminando imagenes no utilizadas..."
docker image prune -a -f
echo "¡Limpio!"

View File

@ -30,19 +30,32 @@ const dragStart = ref({ x: 0, y: 0 });
const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 }); const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 });
const fileInput = ref(null); const fileInput = ref(null);
/** Referencias adicionales para auto-posicionamiento */
const controlsRef = ref(null);
/** Constantes para precisión WYSIWYG */
const PDF_SCALE_FACTOR = 0.75; // 1px = 0.75 puntos PDF
const CANVAS_DPI = 96; // DPI del canvas
const PDF_DPI = 72; // DPI del PDF
/** Propiedades computadas */ /** Propiedades computadas */
const elementStyles = computed(() => { const elementStyles = computed(() => {
const baseStyles = { const baseStyles = {
left: `${props.element.x}px`, left: `${props.element.x}px`,
top: `${props.element.y}px`, top: `${props.element.y}px`,
width: `${props.element.width || 200}px`, width: `${props.element.width || 200}px`,
height: `${props.element.height || 40}px` height: `${props.element.height || 40}px`,
// Asegurar que la fuente se renderice con la misma métrica que el PDF
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.2',
letterSpacing: 'normal'
}; };
// Aplicar estilos de formato para elementos de texto // Aplicar estilos de formato para elementos de texto
if (props.element.type === 'text' && props.element.formatting) { if (props.element.type === 'text' && props.element.formatting) {
const formatting = props.element.formatting; const formatting = props.element.formatting;
// Aplicar tamaño de fuente con factor de corrección
if (formatting.fontSize) { if (formatting.fontSize) {
baseStyles.fontSize = `${formatting.fontSize}px`; baseStyles.fontSize = `${formatting.fontSize}px`;
} }
@ -50,6 +63,24 @@ const elementStyles = computed(() => {
if (formatting.color) { if (formatting.color) {
baseStyles.color = formatting.color; baseStyles.color = formatting.color;
} }
// Alineación del contenedor en la página
if (formatting.containerAlign) {
const pageWidth = 794; // A4 width por defecto
const elementWidth = props.element.width || 200;
switch (formatting.containerAlign) {
case 'center':
baseStyles.left = `${(pageWidth - elementWidth) / 2}px`;
break;
case 'right':
baseStyles.left = `${pageWidth - elementWidth - 50}px`; // 50px margen
break;
case 'left':
default:
baseStyles.left = `${props.element.x}px`;
}
}
} }
return baseStyles; return baseStyles;
@ -106,6 +137,25 @@ const inputStyles = computed(() => {
return styles; return styles;
}); });
/** Propiedades computadas para posicionamiento dinámico */
const controlsPosition = computed(() => {
if (!props.isSelected || isEditing.value) return {};
// Si el elemento está muy cerca del borde superior (menos de 50px)
const isNearTop = props.element.y < 50;
return {
position: isNearTop ? 'bottom' : 'top',
styles: isNearTop ? {
top: '100%',
marginTop: '8px'
} : {
bottom: '100%',
marginBottom: '8px'
}
};
});
/** Watchers */ /** Watchers */
watch(() => props.isSelected, (selected) => { watch(() => props.isSelected, (selected) => {
if (selected && isEditing.value) { if (selected && isEditing.value) {
@ -356,6 +406,44 @@ const getMaxWidth = () => {
const getMaxHeight = () => { const getMaxHeight = () => {
return 600; // Máximo general return 600; // Máximo general
}; };
// Nuevos métodos para alineación
const updateContainerAlign = (align) => {
emit('update', {
id: props.element.id,
formatting: {
...props.element.formatting,
containerAlign: align
}
});
};
const updateSmartAlign = (align) => {
const pageWidth = 794; // Obtener dinámicamente del viewport
const elementWidth = props.element.width || 200;
let newX = props.element.x;
switch (align) {
case 'center':
newX = (pageWidth - elementWidth) / 2;
break;
case 'right':
newX = pageWidth - elementWidth - 50; // margen derecho
break;
case 'left':
default:
newX = 50; // margen izquierdo
}
emit('update', {
id: props.element.id,
x: newX,
formatting: {
...props.element.formatting,
textAlign: align
}
});
};
</script> </script>
<template> <template>
@ -386,14 +474,21 @@ const getMaxHeight = () => {
class="hidden" class="hidden"
/> />
<!-- Elemento de Texto con formato aplicado --> <!-- Elemento de Texto MEJORADO -->
<div <div
v-if="element.type === 'text'" v-if="element.type === 'text'"
class="w-full h-full flex items-center px-3 py-2 bg-white rounded border border-gray-300 shadow-sm dark:bg-white dark:border-gray-400" class="w-full h-full flex items-center px-3 py-2 bg-white rounded border border-gray-300 shadow-sm dark:bg-white dark:border-gray-400"
:class="textContainerClasses" :class="textContainerClasses"
:style="{ :style="{
fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px', fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px',
color: element.formatting?.color || '#374151' color: element.formatting?.color || '#374151',
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.2',
letterSpacing: 'normal',
// Simular exactamente como se verá en el PDF
textRendering: 'geometricPrecision',
fontSmooth: 'always',
WebkitFontSmoothing: 'antialiased'
}" }"
> >
<input <input
@ -404,7 +499,12 @@ const getMaxHeight = () => {
@keydown="handleKeydown" @keydown="handleKeydown"
class="w-full bg-transparent outline-none cursor-text" class="w-full bg-transparent outline-none cursor-text"
:class="inputClasses" :class="inputClasses"
:style="inputStyles" :style="{
...inputStyles,
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.2',
letterSpacing: 'normal'
}"
@mousedown.stop @mousedown.stop
/> />
<span <span
@ -413,14 +513,17 @@ const getMaxHeight = () => {
:class="textContainerClasses" :class="textContainerClasses"
:style="{ :style="{
fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px', fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px',
color: element.formatting?.color || '#374151' color: element.formatting?.color || '#374151',
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.2',
letterSpacing: 'normal'
}" }"
> >
{{ element.content || 'Nuevo texto' }} {{ element.content || 'Nuevo texto' }}
</span> </span>
</div> </div>
<!-- Elemento de Imagen (sin cambios) --> <!-- Elemento de Imagen -->
<div <div
v-else-if="element.type === 'image'" v-else-if="element.type === 'image'"
class="w-full h-full flex items-center justify-center bg-gray-100 rounded border border-gray-300 dark:bg-primary/10 dark:border-primary/20 overflow-hidden" class="w-full h-full flex items-center justify-center bg-gray-100 rounded border border-gray-300 dark:bg-primary/10 dark:border-primary/20 overflow-hidden"
@ -439,7 +542,7 @@ const getMaxHeight = () => {
</div> </div>
</div> </div>
<!-- Elemento de Tabla (sin cambios en esta parte) --> <!-- Elemento de Tabla -->
<div <div
v-else-if="element.type === 'table'" v-else-if="element.type === 'table'"
class="w-full h-full bg-white rounded border overflow-hidden" class="w-full h-full bg-white rounded border overflow-hidden"
@ -497,93 +600,95 @@ const getMaxHeight = () => {
</div> </div>
</div> </div>
<!-- Controles del elemento con z-index más alto --> <!-- Controles del elemento -->
<div <div
v-if="isSelected && !isEditing" v-if="isSelected && !isEditing"
class="absolute -top-8 right-0 flex gap-1 opacity-100 transition-opacity z-[60]" ref="controlsRef"
class="absolute right-0 flex gap-1 opacity-100 transition-opacity z-[60]"
:style="controlsPosition.styles"
> >
<!-- Indicador de tamaño --> <!-- Flecha indicadora cuando está abajo -->
<div class="px-2 py-1 bg-gray-800 text-white text-xs rounded shadow-sm pointer-events-none"> <div
{{ Math.round(element.width || 200) }} × {{ Math.round(element.height || 40) }} v-if="controlsPosition.position === 'bottom'"
</div> class="absolute -top-2 right-2 w-0 h-0 border-l-4 border-r-4 border-b-4 border-l-transparent border-r-transparent border-b-gray-800"
></div>
<!-- Botón para cargar imagen (solo para elementos de imagen) --> <!-- Botón para cargar imagen (solo para elementos de imagen) -->
<button <button
v-if="element.type === 'image'" v-if="element.type === 'image'"
@click.stop="() => fileInput.click()" @click.stop="() => fileInput.click()"
class="w-6 h-6 bg-blue-500 hover:bg-blue-600 text-white rounded text-xs flex items-center justify-center transition-colors shadow-sm" class="w-7 h-7 bg-blue-500 hover:bg-blue-600 text-white rounded-md text-xs flex items-center justify-center transition-colors shadow-md"
title="Cargar imagen" title="Cargar imagen"
> >
<GoogleIcon name="upload" class="text-xs" /> <GoogleIcon name="upload" class="text-sm" />
</button> </button>
<!-- Botón eliminar --> <!-- Botón eliminar -->
<button <button
@click.stop="handleDelete" @click.stop="handleDelete"
class="w-6 h-6 bg-red-500 hover:bg-red-600 text-white rounded text-xs flex items-center justify-center transition-colors shadow-sm" class="w-7 h-7 bg-red-500 hover:bg-red-600 text-white rounded-md text-xs flex items-center justify-center transition-colors shadow-md"
title="Eliminar" title="Eliminar elemento"
> >
<GoogleIcon name="close" class="text-xs" /> <GoogleIcon name="close" class="text-sm" />
</button> </button>
<!-- Flecha indicadora cuando está arriba -->
<div
v-if="controlsPosition.position === 'top'"
class="absolute -bottom-2 right-2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-gray-800"
></div>
</div> </div>
<!-- Controles de redimensionamiento mejorados --> <!-- Controles de redimensionamiento -->
<div v-if="isSelected && !isEditing" class="absolute inset-0 pointer-events-none z-[55]"> <div v-if="isSelected && !isEditing" class="absolute inset-0 pointer-events-none z-[55]">
<!-- Esquina inferior derecha - MÁS GRANDE Y VISIBLE --> <!-- Esquina inferior derecha -->
<div <div
@mousedown.stop="startResize" @mousedown.stop="startResize"
class="absolute -bottom-2 -right-2 w-4 h-4 bg-blue-500 border-2 border-white cursor-se-resize pointer-events-auto rounded-sm shadow-md hover:bg-blue-600 transition-all" class="absolute -bottom-2 -right-2 w-5 h-5 bg-blue-500 border-2 border-white cursor-se-resize pointer-events-auto rounded-md shadow-lg hover:bg-blue-600 hover:scale-110 transition-all"
title="Redimensionar" title="Redimensionar"
> >
<div class="absolute inset-0.5 bg-white/30 rounded-sm"></div> <div class="absolute inset-1 border border-white/40 rounded-sm"></div>
</div> </div>
<!-- Lado derecho - MÁS VISIBLE --> <!-- Lado derecho -->
<div <div
@mousedown.stop="(event) => startResizeEdge(event, 'right')" @mousedown.stop="(event) => startResizeEdge(event, 'right')"
class="absolute top-2 bottom-2 -right-1 w-2 bg-blue-500 cursor-e-resize pointer-events-auto rounded-sm shadow-sm hover:bg-blue-600 transition-all" class="absolute top-3 bottom-3 -right-1 w-2 bg-blue-500/80 cursor-e-resize pointer-events-auto rounded-full shadow-sm hover:bg-blue-600 hover:w-3 transition-all"
title="Redimensionar ancho" title="Redimensionar ancho"
> >
<!-- Indicador visual en el centro --> <div class="absolute top-1/2 left-1/2 w-0.5 h-6 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"></div>
<div class="absolute top-1/2 left-1/2 w-0.5 h-4 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"></div>
</div> </div>
<!-- Lado inferior - MÁS VISIBLE --> <!-- Lado inferior -->
<div <div
@mousedown.stop="(event) => startResizeEdge(event, 'bottom')" @mousedown.stop="(event) => startResizeEdge(event, 'bottom')"
class="absolute -bottom-1 left-2 right-2 h-2 bg-blue-500 cursor-s-resize pointer-events-auto rounded-sm shadow-sm hover:bg-blue-600 transition-all" class="absolute -bottom-1 left-3 right-3 h-2 bg-blue-500/80 cursor-s-resize pointer-events-auto rounded-full shadow-sm hover:bg-blue-600 hover:h-3 transition-all"
title="Redimensionar alto" title="Redimensionar alto"
> >
<!-- Indicador visual en el centro --> <div class="absolute top-1/2 left-1/2 w-6 h-0.5 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"></div>
<div class="absolute top-1/2 left-1/2 w-4 h-0.5 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"></div>
</div>
<!-- Esquinas adicionales para mejor UX -->
<div
@mousedown.stop="startResize"
class="absolute -top-2 -left-2 w-4 h-4 bg-blue-500 border-2 border-white cursor-nw-resize pointer-events-auto rounded-sm shadow-md hover:bg-blue-600 transition-all"
title="Redimensionar"
>
<div class="absolute inset-0.5 bg-white/30 rounded-sm"></div>
</div>
<div
@mousedown.stop="startResize"
class="absolute -top-2 -right-2 w-4 h-4 bg-blue-500 border-2 border-white cursor-ne-resize pointer-events-auto rounded-sm shadow-md hover:bg-blue-600 transition-all"
title="Redimensionar"
>
<div class="absolute inset-0.5 bg-white/30 rounded-sm"></div>
</div>
<div
@mousedown.stop="startResize"
class="absolute -bottom-2 -left-2 w-4 h-4 bg-blue-500 border-2 border-white cursor-sw-resize pointer-events-auto rounded-sm shadow-md hover:bg-blue-600 transition-all"
title="Redimensionar"
>
<div class="absolute inset-0.5 bg-white/30 rounded-sm"></div>
</div> </div>
</div> </div>
<!-- Tooltips adaptativos -->
<div
v-if="isSelected && !element.content && element.type !== 'image' && !isResizing"
class="absolute right-0 bg-gray-900 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-[60]"
:style="element.y < 50 ? { top: '100%', marginTop: '8px' } : { bottom: '100%', marginBottom: '8px' }"
>
{{ element.type === 'text' ? 'Doble clic para editar texto' : 'Doble clic para editar código' }}
{{ element.type === 'code' ? ' (Ctrl+Enter para guardar)' : '' }}
</div>
<!-- Tooltip para imagen -->
<div
v-if="isSelected && !isEditing && element.type === 'image' && !element.content && !isResizing"
class="absolute right-0 bg-gray-900 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-[60]"
:style="element.y < 50 ? { top: '100%', marginTop: '8px' } : { bottom: '100%', marginBottom: '8px' }"
>
Arrastra las esquinas para redimensionar
</div>
<!-- Resto de elementos sin cambios... -->
<!-- Indicador de arrastre --> <!-- Indicador de arrastre -->
<div <div
v-if="isDragging" v-if="isDragging"
@ -599,7 +704,8 @@ const getMaxHeight = () => {
<!-- Botón para terminar edición de tabla --> <!-- Botón para terminar edición de tabla -->
<div <div
v-if="isEditing && element.type === 'table'" v-if="isEditing && element.type === 'table'"
class="absolute -bottom-10 left-0 flex gap-2 z-[60]" class="absolute left-0 flex gap-2 z-[60]"
:style="element.y < 100 ? { top: '100%', marginTop: '8px' } : { bottom: '100%', marginBottom: '8px' }"
> >
<button <button
@click="finishEditing" @click="finishEditing"
@ -618,29 +724,6 @@ const getMaxHeight = () => {
</template> </template>
<style scoped> <style scoped>
/* Estilos existentes sin cambios... */
.resize-handle-corner {
transition: all 0.2s ease;
}
.resize-handle-corner:hover {
transform: scale(1.1);
}
.resize-handle-edge {
transition: all 0.2s ease;
opacity: 0.7;
}
.resize-handle-edge:hover {
opacity: 1;
transform: scale(1.05);
}
.group:hover .resize-handle-edge {
opacity: 0.8;
}
.select-none { .select-none {
user-select: none; user-select: none;
-webkit-user-select: none; -webkit-user-select: none;

View File

@ -148,25 +148,26 @@ defineExpose({
<button <button
@click="setCurrentPage(Math.max(1, currentPage - 1))" @click="setCurrentPage(Math.max(1, currentPage - 1))"
:disabled="currentPage <= 1" :disabled="currentPage <= 1"
class="p-1.5 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded hover:bg-gray-100 dark:hover:bg-primary/10" class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded-md hover:bg-gray-100 dark:hover:bg-primary/10 transition-colors"
title="Página anterior" title="Página anterior"
> >
<GoogleIcon name="keyboard_arrow_left" class="text-lg" /> <GoogleIcon name="keyboard_arrow_left" class="text-xl" />
</button> </button>
<button <button
@click="handleNextPage" @click="handleNextPage"
:disabled="isExporting" :disabled="isExporting"
class="p-1.5 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded hover:bg-gray-100 dark:hover:bg-primary/10 relative" class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded-md hover:bg-gray-100 dark:hover:bg-primary/10 relative transition-colors"
:title="currentPage >= totalPages ? 'Crear nueva página' : 'Página siguiente'" :title="currentPage >= totalPages ? 'Crear nueva página' : 'Página siguiente'"
> >
<GoogleIcon name="keyboard_arrow_right" class="text-lg" /> <GoogleIcon name="keyboard_arrow_right" class="text-xl" />
<!-- Indicador solo cuando estamos en la última página --> <!-- Indicador mejorado -->
<GoogleIcon <div
v-if="currentPage >= totalPages" v-if="currentPage >= totalPages"
name="add" class="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full flex items-center justify-center"
class="absolute -top-1 -right-1 text-xs text-green-500 bg-white rounded-full" >
/> <GoogleIcon name="add" class="text-white text-xs" />
</div>
</button> </button>
</div> </div>
</div> </div>
@ -175,14 +176,15 @@ defineExpose({
<!-- Selector de tamaño de página --> <!-- Selector de tamaño de página -->
<PageSizeSelector v-model="pageSize" /> <PageSizeSelector v-model="pageSize" />
<span class="text-xs text-gray-500 dark:text-primary-dt/70 bg-gray-50 dark:bg-primary/10 px-2 py-1 rounded"> <!-- Info de página -->
{{ Math.round(ZOOM_LEVEL * 100) }}% {{ currentPageSize.label }} <span class="text-xs text-gray-500 dark:text-primary-dt/70 bg-gray-50 dark:bg-primary/10 px-3 py-1.5 rounded-md border border-gray-200 dark:border-primary/20">
{{ currentPageSize.label }}
</span> </span>
<button <button
@click="addPage" @click="addPage"
:disabled="isExporting" :disabled="isExporting"
class="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors disabled:opacity-50 font-medium" class="flex items-center gap-2 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 font-medium shadow-sm"
> >
<GoogleIcon name="add" class="text-sm" /> <GoogleIcon name="add" class="text-sm" />
Nueva Página Nueva Página
@ -190,16 +192,16 @@ defineExpose({
</div> </div>
</div> </div>
<!-- Viewport de páginas horizontal --> <!-- Resto del viewport -->
<div <div
ref="viewportRef" ref="viewportRef"
class="flex-1 overflow-auto" class="flex-1 overflow-auto"
style="background-color: #f8fafc; background-image: radial-gradient(circle, #e2e8f0 1px, transparent 1px); background-size: 24px 24px;" style="background-color: #f8fafc; background-image: radial-gradient(circle, #e2e8f0 1px, transparent 1px); background-size: 20px 20px;"
> >
<!-- Contenedor horizontal centrado --> <!-- Contenedor horizontal centrado -->
<div class="flex items-center justify-center min-h-full p-6"> <div class="flex items-center justify-center min-h-full p-8">
<div class="flex items-center gap-8"> <div class="flex items-center gap-10">
<!-- Páginas --> <!-- Páginas MEJORADAS -->
<div <div
v-for="(page, pageIndex) in pages" v-for="(page, pageIndex) in pages"
:key="page.id" :key="page.id"
@ -207,38 +209,38 @@ defineExpose({
class="relative group flex-shrink-0" class="relative group flex-shrink-0"
> >
<!-- Header de página --> <!-- Header de página -->
<div class="flex flex-col items-center mb-3"> <div class="flex flex-col items-center mb-4">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3 mb-1">
<span class="text-sm font-medium text-gray-600 dark:text-primary-dt/80"> <span class="text-sm font-semibold text-gray-700 dark:text-primary-dt/90 bg-white dark:bg-primary-d px-3 py-1 rounded-full shadow-sm border border-gray-200 dark:border-primary/20">
Página {{ pageIndex + 1 }} Página {{ pageIndex + 1 }}
</span> </span>
<button <button
v-if="totalPages > 1" v-if="totalPages > 1"
@click="deletePage(pageIndex)" @click="deletePage(pageIndex)"
:disabled="isExporting" :disabled="isExporting"
class="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 disabled:opacity-50 p-1 rounded hover:bg-red-50 transition-all" class="opacity-0 group-hover:opacity-100 w-7 h-7 text-red-500 hover:text-white hover:bg-red-500 disabled:opacity-50 rounded-full flex items-center justify-center transition-all duration-200"
title="Eliminar página" title="Eliminar página"
> >
<GoogleIcon name="delete" class="text-sm" /> <GoogleIcon name="delete" class="text-sm" />
</button> </button>
</div> </div>
<span class="text-xs text-gray-400 dark:text-primary-dt/50"> <span class="text-xs text-gray-500 dark:text-primary-dt/60">
{{ currentPageSize.label }} {{ currentPageSize.label }}
</span> </span>
</div> </div>
<!-- Contenedor de página con sombra --> <!-- Contenedor de página -->
<div class="relative"> <div class="relative">
<!-- Sombra de página --> <!-- Sombra mejorada -->
<div class="absolute top-2 left-2 w-full h-full bg-gray-400/30 rounded-lg"></div> <div class="absolute top-3 left-3 w-full h-full bg-gray-400/20 rounded-xl blur-sm"></div>
<!-- Página PDF --> <!-- Página PDF -->
<div <div
class="pdf-page relative bg-white rounded-lg border border-gray-300 dark:border-primary/20 overflow-hidden" class="pdf-page relative bg-white rounded-xl border border-gray-300 dark:border-primary/30 overflow-hidden transition-all duration-300"
:class="{ :class="{
'ring-2 ring-blue-500 ring-opacity-50 shadow-lg': currentPage === pageIndex + 1, 'ring-3 ring-blue-500/50 shadow-2xl scale-105': currentPage === pageIndex + 1,
'shadow-md hover:shadow-lg': currentPage !== pageIndex + 1, 'shadow-lg hover:shadow-xl hover:scale-102': currentPage !== pageIndex + 1,
'opacity-50': isExporting 'opacity-60': isExporting
}" }"
:style="{ :style="{
width: `${scaledPageWidth}px`, width: `${scaledPageWidth}px`,
@ -248,11 +250,11 @@ defineExpose({
@dragover="handleDragOver" @dragover="handleDragOver"
@click="(e) => handleClick(e, pageIndex)" @click="(e) => handleClick(e, pageIndex)"
> >
<!-- Área de contenido con márgenes visuales --> <!-- Área de contenido -->
<div class="relative w-full h-full"> <div class="relative w-full h-full">
<!-- Guías de margen --> <!-- Guías de margen SUTILES -->
<div <div
class="absolute border border-dashed border-blue-300/40 pointer-events-none" class="absolute border border-dashed border-blue-300/30 pointer-events-none rounded-lg"
:style="{ :style="{
top: `${PAGE_MARGIN * ZOOM_LEVEL}px`, top: `${PAGE_MARGIN * ZOOM_LEVEL}px`,
left: `${PAGE_MARGIN * ZOOM_LEVEL}px`, left: `${PAGE_MARGIN * ZOOM_LEVEL}px`,
@ -261,7 +263,7 @@ defineExpose({
}" }"
></div> ></div>
<!-- Elementos de la página con transformación --> <!-- Elementos de la página -->
<div <div
class="absolute inset-0" class="absolute inset-0"
:style="{ :style="{
@ -288,10 +290,10 @@ defineExpose({
class="absolute inset-0 flex items-center justify-center pointer-events-none z-10" class="absolute inset-0 flex items-center justify-center pointer-events-none z-10"
:style="{ transform: `scale(${1/ZOOM_LEVEL})` }" :style="{ transform: `scale(${1/ZOOM_LEVEL})` }"
> >
<div class="text-center text-gray-400 dark:text-primary-dt/50"> <div class="text-center text-gray-400 dark:text-primary-dt/50 p-6 bg-gray-50/80 dark:bg-primary/5 rounded-xl border-2 border-dashed border-gray-300/50 dark:border-primary/20">
<GoogleIcon name="description" class="text-4xl mb-2" /> <GoogleIcon name="description" class="text-5xl mb-3 opacity-60" />
<p class="text-sm font-medium">Página {{ pageIndex + 1 }}</p> <p class="text-base font-medium mb-1">Página {{ pageIndex + 1 }}</p>
<p class="text-xs">Arrastra elementos aquí</p> <p class="text-sm opacity-75">Arrastra elementos aquí</p>
</div> </div>
</div> </div>
</div> </div>
@ -304,12 +306,18 @@ defineExpose({
<!-- Overlay durante exportación --> <!-- Overlay durante exportación -->
<div <div
v-if="isExporting" v-if="isExporting"
class="absolute inset-0 bg-white/90 dark:bg-primary-d/90 flex items-center justify-center z-50 backdrop-blur-sm" class="absolute inset-0 bg-white/95 dark:bg-primary-d/95 flex items-center justify-center z-50 backdrop-blur-sm"
> >
<div class="text-center bg-white dark:bg-primary-d rounded-lg p-6 shadow-lg border border-gray-200 dark:border-primary/20"> <div class="text-center bg-white dark:bg-primary-d rounded-2xl p-8 shadow-2xl border border-gray-200 dark:border-primary/20 max-w-sm w-full mx-4">
<GoogleIcon name="picture_as_pdf" class="text-5xl text-red-600 dark:text-red-400 animate-pulse mb-3" /> <div class="relative mb-4">
<p class="text-lg font-semibold text-gray-900 dark:text-primary-dt mb-1">Generando PDF...</p> <GoogleIcon name="picture_as_pdf" class="text-6xl text-red-600 dark:text-red-400 animate-pulse" />
<p class="text-sm text-gray-500 dark:text-primary-dt/70">Procesando {{ totalPages }} página{{ totalPages !== 1 ? 's' : '' }}</p> <div class="absolute inset-0 bg-red-100 dark:bg-red-900/20 rounded-full animate-ping opacity-20"></div>
</div>
<p class="text-xl font-semibold text-gray-900 dark:text-primary-dt mb-2">Generando PDF</p>
<p class="text-sm text-gray-600 dark:text-primary-dt/70 mb-4">Procesando {{ totalPages }} página{{ totalPages !== 1 ? 's' : '' }}</p>
<div class="w-full bg-gray-200 dark:bg-primary/20 rounded-full h-1">
<div class="bg-red-600 dark:bg-red-400 h-1 rounded-full animate-pulse" style="width: 100%"></div>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -317,20 +325,16 @@ defineExpose({
<style scoped> <style scoped>
.pdf-page { .pdf-page {
transition: all 0.3s ease; transform-origin: center;
position: relative;
} }
.pdf-page:hover { .scale-102 {
transform: translateY(-2px); transform: scale(1.02);
} }
.pdf-page.ring-2 { .overflow-auto::-webkit-scrollbar {
transform: translateY(-4px); height: 6px;
} width: 6px;
.overflow-auto {
scroll-behavior: smooth;
} }
.overflow-auto::-webkit-scrollbar-track { .overflow-auto::-webkit-scrollbar-track {
@ -339,15 +343,10 @@ defineExpose({
.overflow-auto::-webkit-scrollbar-thumb { .overflow-auto::-webkit-scrollbar-thumb {
background: #cbd5e1; background: #cbd5e1;
border-radius: 4px; border-radius: 3px;
} }
.overflow-auto::-webkit-scrollbar-thumb:hover { .overflow-auto::-webkit-scrollbar-thumb:hover {
background: #94a3b8; background: #94a3b8;
} }
.overflow-auto::-webkit-scrollbar {
height: 8px;
width: 8px;
}
</style> </style>

View File

@ -69,13 +69,13 @@ const selectSize = (size) => {
<template> <template>
<div class="relative"> <div class="relative">
<!-- Selector principal --> <!-- Selector principal MEJORADO -->
<button <button
@click="isOpen = !isOpen" @click="isOpen = !isOpen"
class="flex items-center gap-2 px-3 py-2 text-sm bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-md hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors" class="flex items-center gap-2 px-3 py-2 text-sm bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-lg hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors shadow-sm"
> >
<GoogleIcon name="aspect_ratio" class="text-gray-500 dark:text-primary-dt/70" /> <GoogleIcon name="aspect_ratio" class="text-gray-500 dark:text-primary-dt/70" />
<span class="text-gray-700 dark:text-primary-dt">{{ selectedSize.name }}</span> <span class="text-gray-700 dark:text-primary-dt font-medium">{{ selectedSize.name }}</span>
<GoogleIcon <GoogleIcon
name="expand_more" name="expand_more"
class="text-gray-400 dark:text-primary-dt/50 transition-transform" class="text-gray-400 dark:text-primary-dt/50 transition-transform"
@ -87,34 +87,34 @@ const selectSize = (size) => {
<div <div
v-if="isOpen" v-if="isOpen"
@click.away="isOpen = false" @click.away="isOpen = false"
class="absolute top-full left-0 mt-1 w-72 bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-lg shadow-lg z-50 py-2" class="absolute top-full left-0 mt-2 w-80 bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-xl shadow-xl z-50 py-3"
> >
<div class="px-3 py-2 text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider border-b border-gray-100 dark:border-primary/20"> <div class="px-4 py-2 text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider border-b border-gray-100 dark:border-primary/20 mb-2">
Tamaños de página Tamaños de página
</div> </div>
<div class="max-h-64 overflow-y-auto"> <div class="max-h-72 overflow-y-auto">
<button <button
v-for="size in pageSizes" v-for="size in pageSizes"
:key="size.name" :key="size.name"
@click="selectSize(size)" @click="selectSize(size)"
class="w-full flex items-center gap-3 px-3 py-3 hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors text-left" class="w-full flex items-center gap-4 px-4 py-3 hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors text-left"
:class="{ :class="{
'bg-blue-50 dark:bg-blue-900/20': selectedSize.name === size.name 'bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500': selectedSize.name === size.name
}" }"
> >
<div class="flex-shrink-0"> <div class="flex-shrink-0">
<div <div
class="w-8 h-10 border border-gray-300 dark:border-primary/30 rounded-sm bg-white dark:bg-primary-d flex items-center justify-center" class="w-10 h-12 border-2 border-gray-300 dark:border-primary/30 rounded-md bg-white dark:bg-primary-d flex items-center justify-center shadow-sm"
:class="{ :class="{
'border-blue-500 dark:border-blue-400': selectedSize.name === size.name 'border-blue-500 dark:border-blue-400 shadow-blue-200': selectedSize.name === size.name
}" }"
> >
<div <div
class="bg-gray-200 dark:bg-primary/20 rounded-sm" class="bg-gray-200 dark:bg-primary/20 rounded-sm"
:style="{ :style="{
width: `${Math.min(20, (size.width / size.height) * 32)}px`, width: `${Math.min(24, (size.width / size.height) * 36)}px`,
height: `${Math.min(32, (size.height / size.width) * 20)}px` height: `${Math.min(36, (size.height / size.width) * 24)}px`
}" }"
:class="{ :class="{
'bg-blue-200 dark:bg-blue-800': selectedSize.name === size.name 'bg-blue-200 dark:bg-blue-800': selectedSize.name === size.name
@ -124,15 +124,17 @@ const selectSize = (size) => {
</div> </div>
<div class="flex-1 min-w-0"> <div class="flex-1 min-w-0">
<div class="font-medium text-gray-900 dark:text-primary-dt">{{ size.label }}</div> <div class="font-semibold text-gray-900 dark:text-primary-dt text-base">{{ size.name }}</div>
<div class="text-xs text-gray-500 dark:text-primary-dt/70">{{ size.description }}</div> <div class="text-sm text-gray-600 dark:text-primary-dt/80">{{ size.label.split('(')[1]?.replace(')', '') || size.label }}</div>
<div class="text-xs text-gray-400 dark:text-primary-dt/50 mt-1"> <div class="text-xs text-gray-500 dark:text-primary-dt/60 mt-1">
{{ size.width }} x {{ size.height }} px {{ size.description }}
</div> </div>
</div> </div>
<div v-if="selectedSize.name === size.name" class="flex-shrink-0"> <div v-if="selectedSize.name === size.name" class="flex-shrink-0">
<GoogleIcon name="check" class="text-blue-500 dark:text-blue-400" /> <div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
<GoogleIcon name="check" class="text-white text-sm" />
</div>
</div> </div>
</button> </button>
</div> </div>

View File

@ -60,6 +60,26 @@ const updateFormatting = (key, value) => {
}); });
}; };
const updateContainerAlign = (align) => {
if (!hasTextElement.value) return;
updateFormatting('containerAlign', align);
};
const updateSmartAlign = (align) => {
if (!hasTextElement.value) return;
// Emitir tanto la alineación del texto como la posición del contenedor
emit('smart-align', {
id: props.element.id,
align: align,
formatting: {
...formatting.value,
textAlign: align,
containerAlign: align
}
});
};
/** Colores predefinidos */ /** Colores predefinidos */
const predefinedColors = [ const predefinedColors = [
'#000000', '#333333', '#666666', '#999999', '#000000', '#333333', '#666666', '#999999',

View File

@ -1,11 +1,10 @@
<script setup> <script setup>
import { ref, onMounted, computed } from 'vue'; import { ref, nextTick, onMounted, computed } from 'vue';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib'; import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import GoogleIcon from '@Shared/GoogleIcon.vue'; import GoogleIcon from '@Shared/GoogleIcon.vue';
import Draggable from '@Holos/PDF/Draggable.vue'; import Draggable from '@Holos/Draggable.vue';
import CanvasElement from '@Holos/PDF/Canvas.vue'; import CanvasElement from '@Holos/Canvas.vue';
import PDFViewport from '@Holos/PDF/PDFViewport.vue'; import PDFViewport from '@Holos/PDFViewport.vue';
import TextFormatter from '@Holos/PDF/TextFormatter.vue';
/** Estado reactivo */ /** Estado reactivo */
const pages = ref([{ id: 1, elements: [] }]); const pages = ref([{ id: 1, elements: [] }]);
@ -14,61 +13,10 @@ const elementCounter = ref(0);
const documentTitle = ref('Documento sin título'); const documentTitle = ref('Documento sin título');
const isExporting = ref(false); const isExporting = ref(false);
const currentPage = ref(1); const currentPage = ref(1);
const pageIdCounter = ref(1); // <-- Agregar contador separado para páginas
/** Estado para tamaño de página */
const currentPageSize = ref({
width: 794, // A4 por defecto
height: 1123
});
/** Manejar cambio de tamaño de página */
const handlePageSizeChange = (sizeData) => {
currentPageSize.value = sizeData.dimensions;
// Aquí podrías ajustar elementos existentes si es necesario
window.Notify.info(`Tamaño de página cambiado a ${sizeData.size}`);
};
// Actualizar el método moveElement para usar el tamaño dinámico
const moveElement = (moveData) => {
const element = allElements.value.find(el => el.id === moveData.id);
if (element) {
element.x = Math.max(0, Math.min(currentPageSize.value.width - (element.width || 200), moveData.x));
element.y = Math.max(0, Math.min(currentPageSize.value.height - (element.height || 40), moveData.y));
}
};
/** Referencias */ /** Referencias */
const viewportRef = ref(null); const viewportRef = ref(null);
/** Referencias adicionales */
const textFormatterElement = ref(null);
const showTextFormatter = ref(false);
const selectElement = (elementId) => {
selectedElementId.value = elementId;
const selectedEl = allElements.value.find(el => el.id === elementId);
showTextFormatter.value = selectedEl?.type === 'text';
textFormatterElement.value = selectedEl;
};
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
// Si se actualiza el formato, actualizar la referencia
if (update.formatting && textFormatterElement.value?.id === update.id) {
textFormatterElement.value = { ...element };
}
}
};
const handleCanvasClick = (clickData) => {
selectedElementId.value = null;
showTextFormatter.value = false;
textFormatterElement.value = null;
};
/** Tipos de elementos disponibles */ /** Tipos de elementos disponibles */
const availableElements = [ const availableElements = [
{ {
@ -161,6 +109,14 @@ const handleDragOver = (event) => {
event.preventDefault(); event.preventDefault();
}; };
const handleCanvasClick = (clickData) => {
selectedElementId.value = null;
};
const selectElement = (elementId) => {
selectedElementId.value = elementId;
};
const deleteElement = (elementId) => { const deleteElement = (elementId) => {
const index = allElements.value.findIndex(el => el.id === elementId); const index = allElements.value.findIndex(el => el.id === elementId);
if (index !== -1) { if (index !== -1) {
@ -172,11 +128,26 @@ const deleteElement = (elementId) => {
} }
}; };
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
}
};
const moveElement = (moveData) => {
const element = allElements.value.find(el => el.id === moveData.id);
if (element) {
element.x = moveData.x;
element.y = moveData.y;
}
};
/** Paginación */ /** Paginación */
const addPage = () => { const addPage = () => {
pageIdCounter.value++; // <-- Incrementar contador independiente const newPageId = Math.max(...pages.value.map(p => p.id)) + 1;
pages.value.push({ pages.value.push({
id: pageIdCounter.value, id: newPageId,
elements: [] elements: []
}); });
}; };
@ -240,215 +211,249 @@ const exportPDF = async () => {
isExporting.value = true; isExporting.value = true;
window.Notify.info('Generando PDF...'); window.Notify.info('Generando PDF...');
// Crear un nuevo documento PDF con el tamaño de página seleccionado // Crear un nuevo documento PDF
const pdfDoc = await PDFDocument.create(); const pdfDoc = await PDFDocument.create();
let currentPage = pdfDoc.addPage([595.28, 841.89]); // A4 size in points
// Convertir dimensiones de pixels a puntos (1 px = 0.75 puntos) let currentPageHeight = 841.89;
const pageWidthPoints = currentPageSize.value.width * 0.75;
const pageHeightPoints = currentPageSize.value.height * 0.75;
let currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]);
let currentPageHeight = pageHeightPoints;
let yOffset = 50; // Margen superior let yOffset = 50; // Margen superior
// Obtener fuentes // Obtener fuentes
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica); const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const courierFont = await pdfDoc.embedFont(StandardFonts.Courier); const courierFont = await pdfDoc.embedFont(StandardFonts.Courier);
// Procesar páginas del maquetador // Ordenar elementos por posición (de arriba hacia abajo, de izquierda a derecha)
for (let pageIndex = 0; pageIndex < pages.value.length; pageIndex++) { const sortedElements = [...allElements.value].sort((a, b) => {
const page = pages.value[pageIndex]; if (Math.abs(a.y - b.y) < 20) {
return a.x - b.x; // Si están en la misma línea, ordenar por X
// Crear nueva página PDF si no es la primera }
if (pageIndex > 0) { return a.y - b.y; // Ordenar por Y
currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]); });
currentPageHeight = pageHeightPoints;
// Procesar elementos
for (const element of sortedElements) {
// Calcular posición en el PDF
const x = Math.max(50, Math.min(500, (element.x * 0.75) + 50)); // Convertir y limitar X
let y = currentPageHeight - yOffset - (element.y * 0.75); // Convertir Y
// Verificar si necesitamos una nueva página
const elementHeight = getElementHeight(element);
if (y - elementHeight < 50) {
currentPage = pdfDoc.addPage([595.28, 841.89]);
currentPageHeight = 841.89;
yOffset = 50; yOffset = 50;
y = currentPageHeight - yOffset;
} }
// Ordenar elementos de esta página por posición switch (element.type) {
const sortedElements = [...page.elements].sort((a, b) => { case 'text':
if (Math.abs(a.y - b.y) < 20) { if (element.content) {
return a.x - b.x; // Si están en la misma línea, ordenar por X // Dividir texto largo en líneas
} const words = element.content.split(' ');
return a.y - b.y; // Ordenar por Y const lines = [];
}); let currentLine = '';
const maxWidth = Math.min(400, (element.width || 200) * 0.75);
// Procesar elementos de la página for (const word of words) {
for (const element of sortedElements) { const testLine = currentLine + (currentLine ? ' ' : '') + word;
// Calcular posición en el PDF manteniendo proporciones const testWidth = helveticaFont.widthOfTextAtSize(testLine, 12);
const scaleX = pageWidthPoints / currentPageSize.value.width;
const scaleY = pageHeightPoints / currentPageSize.value.height; if (testWidth <= maxWidth) {
currentLine = testLine;
const x = Math.max(50, element.x * scaleX); } else {
const y = currentPageHeight - (element.y * scaleY) - 50; // Margen superior if (currentLine) lines.push(currentLine);
currentLine = word;
switch (element.type) {
case 'text':
if (element.content) {
// Dividir texto largo en líneas
const words = element.content.split(' ');
const lines = [];
let currentLine = '';
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
const testWidth = helveticaFont.widthOfTextAtSize(testLine, 12);
if (testWidth <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
} }
if (currentLine) lines.push(currentLine);
// Dibujar cada línea
lines.forEach((line, index) => {
currentPDFPage.drawText(line, {
x: x,
y: y - (index * 15),
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0),
});
});
} }
break; if (currentLine) lines.push(currentLine);
case 'image': // Dibujar cada línea
if (element.content && element.content.startsWith('data:image')) { lines.forEach((line, index) => {
try { currentPage.drawText(line, {
// Convertir base64 a bytes x: x,
const base64Data = element.content.split(',')[1]; y: y - (index * 15),
const imageBytes = Uint8Array.from( size: 12,
atob(base64Data), font: helveticaFont,
c => c.charCodeAt(0) color: rgb(0, 0, 0),
); });
});
let image;
if (element.content.includes('image/jpeg') || element.content.includes('image/jpg')) {
image = await pdfDoc.embedJpg(imageBytes);
} else if (element.content.includes('image/png')) {
image = await pdfDoc.embedPng(imageBytes);
}
if (image) { yOffset += lines.length * 15 + 10;
// Calcular dimensiones manteniendo proporción y escala }
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX); break;
const maxHeight = Math.min(300, (element.height || 150) * scaleY);
const imageAspectRatio = image.width / image.height;
let displayWidth = maxWidth;
let displayHeight = maxWidth / imageAspectRatio;
if (displayHeight > maxHeight) {
displayHeight = maxHeight;
displayWidth = maxHeight * imageAspectRatio;
}
currentPDFPage.drawImage(image, { case 'code':
x: x, if (element.content) {
y: y - displayHeight, // Dibujar fondo para el código
width: displayWidth, const codeLines = element.content.split('\n');
height: displayHeight, const codeWidth = Math.min(450, (element.width || 300) * 0.75);
}); const codeHeight = (codeLines.length * 12) + 20;
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Dibujar placeholder para imagen
currentPDFPage.drawRectangle({
x: x,
y: y - 60,
width: 100 * scaleX,
height: 60 * scaleY,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
});
currentPDFPage.drawText('[Imagen no disponible]', { currentPage.drawRectangle({
x: x + 5, x: x - 10,
y: y - 35, y: y - codeHeight,
size: 10, width: codeWidth,
font: helveticaFont, height: codeHeight,
color: rgb(0.7, 0.7, 0.7), color: rgb(0.95, 0.95, 0.95),
}); });
// Dibujar código
codeLines.forEach((line, index) => {
// Truncar líneas muy largas
const maxChars = Math.floor(codeWidth / 6);
const displayLine = line.length > maxChars ?
line.substring(0, maxChars - 3) + '...' : line;
currentPage.drawText(displayLine, {
x: x - 5,
y: y - 15 - (index * 12),
size: 9,
font: courierFont,
color: rgb(0, 0, 0),
});
});
yOffset += codeHeight + 20;
}
break;
case 'image':
if (element.content && element.content.startsWith('data:image')) {
try {
// Convertir base64 a bytes
const base64Data = element.content.split(',')[1];
const imageBytes = Uint8Array.from(
atob(base64Data),
c => c.charCodeAt(0)
);
let image;
if (element.content.includes('image/jpeg') || element.content.includes('image/jpg')) {
image = await pdfDoc.embedJpg(imageBytes);
} else if (element.content.includes('image/png')) {
image = await pdfDoc.embedPng(imageBytes);
} }
} else {
// Placeholder para imagen vacía if (image) {
currentPDFPage.drawRectangle({ // Calcular dimensiones manteniendo proporción
const maxWidth = Math.min(400, (element.width || 200) * 0.75);
const maxHeight = Math.min(300, (element.height || 150) * 0.75);
const imageAspectRatio = image.width / image.height;
let displayWidth = maxWidth;
let displayHeight = maxWidth / imageAspectRatio;
if (displayHeight > maxHeight) {
displayHeight = maxHeight;
displayWidth = maxHeight * imageAspectRatio;
}
currentPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
});
yOffset += displayHeight + 20;
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Dibujar placeholder para imagen
currentPage.drawRectangle({
x: x, x: x,
y: y - 60, y: y - 60,
width: 100 * scaleX, width: 100,
height: 60 * scaleY, height: 60,
borderColor: rgb(0.7, 0.7, 0.7), borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1, borderWidth: 1,
borderDashArray: [3, 3],
}); });
currentPDFPage.drawText('[Imagen]', { currentPage.drawText('[Imagen no disponible]', {
x: x + 25, x: x + 5,
y: y - 35, y: y - 35,
size: 10, size: 10,
font: helveticaFont, font: helveticaFont,
color: rgb(0.7, 0.7, 0.7), color: rgb(0.7, 0.7, 0.7),
}); });
yOffset += 80;
} }
break; } else {
// Placeholder para imagen vacía
currentPage.drawRectangle({
x: x,
y: y - 60,
width: 100,
height: 60,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
borderDashArray: [3, 3],
});
case 'table': currentPage.drawText('[Imagen]', {
if (element.content && element.content.data) { x: x + 25,
const tableData = element.content.data; y: y - 35,
const cellWidth = 80 * scaleX; size: 10,
const cellHeight = 20 * scaleY; font: helveticaFont,
const tableWidth = tableData[0].length * cellWidth; color: rgb(0.7, 0.7, 0.7),
const tableHeight = tableData.length * cellHeight; });
// Dibujar bordes de la tabla yOffset += 80;
currentPDFPage.drawRectangle({ }
x: x, break;
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.3, 0.3, 0.3),
borderWidth: 1,
});
// Dibujar contenido de las celdas case 'table':
tableData.forEach((row, rowIndex) => { if (element.content && element.content.data) {
row.forEach((cell, colIndex) => { const tableData = element.content.data;
const cellX = x + (colIndex * cellWidth); const cellWidth = 80;
const cellY = y - (rowIndex * cellHeight) - 15; const cellHeight = 20;
const tableWidth = tableData[0].length * cellWidth;
const tableHeight = tableData.length * cellHeight;
// Dibujar borde de celda // Dibujar bordes de la tabla
currentPDFPage.drawRectangle({ currentPage.drawRectangle({
x: cellX, x: x,
y: y - ((rowIndex + 1) * cellHeight), y: y - tableHeight,
width: cellWidth, width: tableWidth,
height: cellHeight, height: tableHeight,
borderColor: rgb(0.7, 0.7, 0.7), borderColor: rgb(0.3, 0.3, 0.3),
borderWidth: 0.5, borderWidth: 1,
}); });
// Dibujar texto de la celda (truncar si es muy largo) // Dibujar contenido de las celdas
const maxChars = Math.floor(cellWidth / 8); tableData.forEach((row, rowIndex) => {
const displayText = cell.length > maxChars ? row.forEach((cell, colIndex) => {
cell.substring(0, maxChars - 3) + '...' : cell; const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight) - 15;
currentPDFPage.drawText(displayText, { // Dibujar borde de celda
x: cellX + 5, currentPage.drawRectangle({
y: cellY, x: cellX,
size: 8, y: y - ((rowIndex + 1) * cellHeight),
font: helveticaFont, width: cellWidth,
color: rowIndex === 0 ? rgb(0.2, 0.2, 0.8) : rgb(0, 0, 0), height: cellHeight,
}); borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
// Dibujar texto de la celda (truncar si es muy largo)
const maxChars = 10;
const displayText = cell.length > maxChars ?
cell.substring(0, maxChars - 3) + '...' : cell;
currentPage.drawText(displayText, {
x: cellX + 5,
y: cellY,
size: 8,
font: helveticaFont,
color: rowIndex === 0 ? rgb(0.2, 0.2, 0.8) : rgb(0, 0, 0), // Encabezados en azul
}); });
}); });
} });
break;
} yOffset += tableHeight + 20;
}
break;
} }
} }
@ -499,8 +504,6 @@ const clearCanvas = () => {
pages.value = [{ id: 1, elements: [] }]; pages.value = [{ id: 1, elements: [] }];
selectedElementId.value = null; selectedElementId.value = null;
elementCounter.value = 0; elementCounter.value = 0;
pageIdCounter.value = 1; // <-- Resetear también el contador de páginas
currentPage.value = 1;
} }
}; };
@ -523,7 +526,7 @@ onMounted(() => {
<template> <template>
<div class="flex h-screen bg-gray-50 dark:bg-primary-d/50"> <div class="flex h-screen bg-gray-50 dark:bg-primary-d/50">
<!-- Panel Izquierdo - Elementos (sin cambios) --> <!-- Panel Izquierdo - Elementos -->
<div class="w-64 bg-white dark:bg-primary-d border-r border-gray-200 dark:border-primary/20 flex flex-col"> <div class="w-64 bg-white dark:bg-primary-d border-r border-gray-200 dark:border-primary/20 flex flex-col">
<!-- Header del panel --> <!-- Header del panel -->
<div class="p-4 border-b border-gray-200 dark:border-primary/20"> <div class="p-4 border-b border-gray-200 dark:border-primary/20">
@ -599,12 +602,18 @@ onMounted(() => {
<!-- Área Principal con Viewport --> <!-- Área Principal con Viewport -->
<div class="flex-1 flex flex-col"> <div class="flex-1 flex flex-col">
<!-- Toolbar superior básico --> <!-- Toolbar superior -->
<div class="h-14 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20 flex items-center justify-between px-4"> <div class="h-14 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20 flex items-center justify-between px-4">
<div class="flex items-center gap-4"> <div class="flex items-center gap-4">
<h2 class="font-semibold text-gray-900 dark:text-primary-dt text-sm"> <!-- Herramientas de formato (simuladas) -->
{{ documentTitle }} <div class="flex items-center gap-1 text-sm">
</h2> <button class="p-1 hover:bg-gray-100 dark:hover:bg-primary/10 rounded" :disabled="isExporting">
<GoogleIcon name="format_bold" class="text-gray-600 dark:text-primary-dt" />
</button>
<button class="p-1 hover:bg-gray-100 dark:hover:bg-primary/10 rounded" :disabled="isExporting">
<GoogleIcon name="format_italic" class="text-gray-600 dark:text-primary-dt" />
</button>
</div>
</div> </div>
<div class="flex items-center gap-4"> <div class="flex items-center gap-4">
@ -624,13 +633,6 @@ onMounted(() => {
</div> </div>
</div> </div>
<!-- TextFormatter como toolbar estático -->
<TextFormatter
:element="textFormatterElement"
:visible="showTextFormatter"
@update="updateElement"
/>
<!-- PDFViewport --> <!-- PDFViewport -->
<PDFViewport <PDFViewport
ref="viewportRef" ref="viewportRef"
@ -642,7 +644,6 @@ onMounted(() => {
@add-page="addPage" @add-page="addPage"
@delete-page="deletePage" @delete-page="deletePage"
@page-change="(page) => currentPage = page" @page-change="(page) => currentPage = page"
@page-size-change="handlePageSizeChange"
> >
<template #elements="{ page, pageIndex }"> <template #elements="{ page, pageIndex }">
<CanvasElement <CanvasElement