Conflictos resueltos

This commit is contained in:
Juan Felipe Zapata Moreno 2025-09-24 18:31:31 -06:00
commit 9fbcc76638
5 changed files with 1383 additions and 985 deletions

File diff suppressed because it is too large Load Diff

View File

@ -39,24 +39,24 @@ const handleDragEnd = () => {
draggable="true"
@dragstart="handleDragStart"
@dragend="handleDragEnd"
class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 bg-white cursor-grab hover:bg-gray-50 hover:border-blue-300 transition-colors dark:bg-primary-d dark:border-primary/20 dark:hover:bg-primary/10"
class="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 rounded-lg border border-gray-200 bg-white cursor-grab hover:bg-gray-50 hover:border-blue-300 transition-colors"
:class="{
'opacity-50 cursor-grabbing': isDragging,
'shadow-sm hover:shadow-md': !isDragging
}"
>
<div class="flex-shrink-0 w-8 h-8 rounded-md bg-blue-100 flex items-center justify-center dark:bg-blue-900/30">
<div class="flex-shrink-0 w-6 h-6 sm:w-8 sm:h-8 rounded-md bg-blue-100 flex items-center justify-center">
<GoogleIcon
:name="icon"
class="text-blue-600 dark:text-blue-400 text-lg"
class="text-blue-600 text-sm sm:text-lg"
/>
</div>
<div class="flex-1 min-w-0">
<div class="text-sm font-medium text-gray-900 dark:text-primary-dt">
<div class="text-xs sm:text-sm font-medium text-gray-900">
{{ title }}
</div>
<div class="text-xs text-gray-500 dark:text-primary-dt/70 truncate">
<div class="text-xs text-gray-500 truncate hidden sm:block">
{{ description }}
</div>
</div>

View File

@ -0,0 +1,201 @@
<script setup>
import { ref, computed, watch } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
const props = defineProps({
element: {
type: Object,
required: true
},
isEditing: {
type: Boolean,
default: false
}
});
const emit = defineEmits(['update', 'finish-editing']);
// Estructura simple: empezar con una celda
const tableData = ref([]);
// Watcher para sincronizar datos
watch(() => props.element.content, (newContent) => {
if (newContent && newContent.data && Array.isArray(newContent.data)) {
tableData.value = JSON.parse(JSON.stringify(newContent.data));
} else {
// Inicializar con una sola celda
tableData.value = [['']];
}
}, { immediate: true });
const rows = computed(() => tableData.value.length);
const cols = computed(() => tableData.value[0]?.length || 1);
// Agregar fila
const addRow = () => {
const newRow = new Array(cols.value).fill('');
tableData.value.push(newRow);
updateTable();
};
// Agregar columna
const addColumn = () => {
tableData.value.forEach(row => {
row.push('');
});
updateTable();
};
// Eliminar fila (no permitir si solo hay una)
const removeRow = (rowIndex) => {
if (tableData.value.length > 1) {
tableData.value.splice(rowIndex, 1);
updateTable();
}
};
// Eliminar columna (no permitir si solo hay una)
const removeColumn = (colIndex) => {
if (tableData.value[0]?.length > 1) {
tableData.value.forEach(row => {
row.splice(colIndex, 1);
});
updateTable();
}
};
// Actualizar celda
const updateCell = (rowIndex, colIndex, value) => {
if (tableData.value[rowIndex]) {
tableData.value[rowIndex][colIndex] = value;
updateTable();
}
};
// Actualizar tabla
const updateTable = () => {
const updatedContent = {
data: JSON.parse(JSON.stringify(tableData.value)),
rows: tableData.value.length,
cols: tableData.value[0]?.length || 1
};
// Calcular dimensiones dinámicas basadas en contenido
const cellWidth = 120;
const cellHeight = 35;
const newWidth = Math.max(120, updatedContent.cols * cellWidth);
const newHeight = Math.max(40, updatedContent.rows * cellHeight);
emit('update', {
id: props.element.id,
content: updatedContent,
width: newWidth,
height: newHeight
});
};
const finishEditing = () => {
emit('finish-editing');
};
</script>
<template>
<div class="w-full h-full bg-white rounded border border-gray-300 overflow-hidden">
<!-- Controles de tabla (solo cuando está editando) -->
<div
v-if="isEditing"
class="flex items-center gap-2 p-2 bg-gray-50 border-b"
>
<button
@click="addRow"
class="px-2 py-1 text-xs bg-green-500 hover:bg-green-600 text-white rounded flex items-center gap-1"
title="Agregar fila"
>
<GoogleIcon name="add" class="text-xs" />
+
</button>
<button
@click="addColumn"
class="px-2 py-1 text-xs bg-blue-500 hover:bg-blue-600 text-white rounded flex items-center gap-1"
title="Agregar columna"
>
<GoogleIcon name="add" class="text-xs" />
+
</button>
<div class="flex-1"></div>
<span class="text-xs text-gray-500">
{{ rows }}x{{ cols }}
</span>
<button
@click="finishEditing"
class="px-2 py-1 text-xs bg-gray-600 hover:bg-gray-700 text-white rounded"
>
Cerrar
</button>
</div>
<!-- Tabla -->
<div class="w-full h-full">
<table class="w-full h-full border-collapse text-sm">
<tbody>
<tr
v-for="(row, rowIndex) in tableData"
:key="`row-${rowIndex}`"
class="group"
:style="{ height: `${100/rows}%` }"
>
<td
v-for="(cell, colIndex) in row"
:key="`cell-${rowIndex}-${colIndex}`"
class="border border-gray-300 p-1 relative group/cell"
:style="{ width: `${100/cols}%` }"
>
<!-- Controles de celda (solo cuando está editando) -->
<div
v-if="isEditing && (rows > 1 || cols > 1)"
class="absolute -top-2 -right-2 opacity-0 group-hover/cell:opacity-100 transition-opacity z-10"
>
<!-- Eliminar fila -->
<button
v-if="rows > 1 && colIndex === 0"
@click="removeRow(rowIndex)"
class="w-4 h-4 bg-red-500 text-white rounded-full text-xs flex items-center justify-center mr-1"
title="Eliminar fila"
>
×
</button>
<!-- Eliminar columna -->
<button
v-if="cols > 1 && rowIndex === 0"
@click="removeColumn(colIndex)"
class="w-4 h-4 bg-red-500 text-white rounded-full text-xs flex items-center justify-center"
title="Eliminar columna"
>
×
</button>
</div>
<!-- Input de celda -->
<input
v-if="isEditing"
:value="cell"
@input="updateCell(rowIndex, colIndex, $event.target.value)"
class="w-full h-full bg-transparent outline-none text-center text-sm resize-none"
@click.stop
:placeholder="rowIndex === 0 && colIndex === 0 && !cell ? 'Escribe aquí...' : ''"
/>
<!-- Vista de solo lectura -->
<div v-else class="w-full h-full flex items-center justify-center text-center text-sm p-1">
{{ cell || (rowIndex === 0 && colIndex === 0 ? 'Tabla' : '') }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>

View File

@ -2,111 +2,153 @@
import { ref, computed, watch } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
/** Propiedades */
const props = defineProps({
element: {
selectedElement: {
type: Object,
default: null
},
visible: {
type: Boolean,
default: false
},
activeTextElement: {
type: Object,
default: null
}
});
/** Eventos */
const emit = defineEmits(['update']);
const emit = defineEmits(['update', 'smart-align']);
/** Propiedades computadas */
const formatting = computed(() => props.element?.formatting || {});
const hasTextElement = computed(() => props.element?.type === 'text');
// Determinar si hay un elemento de texto activo (puede ser texto directo o celda de tabla)
const hasActiveText = computed(() => {
return props.visible && (
props.selectedElement?.type === 'text' ||
props.activeTextElement?.type === 'text' ||
(props.selectedElement?.type === 'table' && props.activeTextElement)
);
});
/** Métodos */
// Obtener formato del elemento activo
const formatting = computed(() => {
if (props.activeTextElement) {
return props.activeTextElement.formatting || {};
}
if (props.selectedElement?.type === 'text') {
return props.selectedElement.formatting || {};
}
return {};
});
// Obtener información del elemento activo
const activeElementInfo = computed(() => {
if (props.activeTextElement) {
return {
type: 'text',
context: props.selectedElement?.type === 'table' ? 'table-cell' : 'text-element'
};
}
if (props.selectedElement?.type === 'text') {
return {
type: 'text',
context: 'text-element'
};
}
return null;
});
/** Métodos de formato */
const toggleBold = () => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('bold', !formatting.value.bold);
};
const toggleItalic = () => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('italic', !formatting.value.italic);
};
const toggleUnderline = () => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('underline', !formatting.value.underline);
};
const updateFontSize = (size) => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('fontSize', size);
};
const updateTextAlign = (align) => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('textAlign', align);
};
const updateColor = (color) => {
if (!hasTextElement.value) return;
if (!hasActiveText.value) return;
updateFormatting('color', color);
};
const updateFormatting = (key, value) => {
const newFormatting = { ...formatting.value, [key]: value };
emit('update', {
id: props.element.id,
formatting: newFormatting
});
};
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
}
});
// Determinar qué elemento actualizar
let targetId = null;
if (props.activeTextElement) {
targetId = props.activeTextElement.id;
} else if (props.selectedElement?.type === 'text') {
targetId = props.selectedElement.id;
}
if (targetId) {
emit('update', {
id: targetId,
formatting: newFormatting,
context: activeElementInfo.value?.context
});
}
};
/** Colores predefinidos */
/** Colores y tamaños predefinidos */
const predefinedColors = [
'#000000', '#333333', '#666666', '#999999',
'#FF0000', '#00FF00', '#0000FF', '#FFFF00',
'#FF00FF', '#00FFFF', '#FFA500', '#800080'
];
/** Tamaños de fuente */
const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
</script>
<template>
<div
v-if="visible && hasTextElement"
class="flex items-center gap-6 px-4 py-2 bg-gray-50 dark:bg-primary-d/50 border-b border-gray-200 dark:border-primary/20"
class="bg-gray-50 border-b border-gray-200 transition-all duration-300"
:class="{
'h-12 opacity-100': visible && hasActiveText,
'h-0 opacity-0 overflow-hidden': !visible || !hasActiveText
}"
>
<!-- Estilo de texto -->
<div class="flex items-center gap-2">
<span class="text-xs font-medium text-gray-600 dark:text-primary-dt/80">Estilo:</span>
<div class="flex gap-1">
<div
v-if="hasActiveText"
class="flex items-center gap-4 px-4 py-2 h-full"
>
<!-- Información del elemento activo -->
<div class="flex items-center gap-2 text-xs text-gray-600 border-r border-gray-300 pr-4">
<GoogleIcon
:name="activeElementInfo?.context === 'table-cell' ? 'table_chart' : 'text_fields'"
class="text-sm"
/>
<span>
{{ activeElementInfo?.context === 'table-cell' ? 'Celda de tabla' : 'Texto' }}
</span>
</div>
<!-- Controles de estilo -->
<div class="flex items-center gap-1">
<button
@click="toggleBold"
:class="[
'w-8 h-8 rounded flex items-center justify-center text-sm font-bold transition-colors',
formatting.bold
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Negrita (Ctrl+B)"
>
@ -119,7 +161,7 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
'w-8 h-8 rounded flex items-center justify-center text-sm italic transition-colors',
formatting.italic
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Cursiva (Ctrl+I)"
>
@ -132,38 +174,32 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
'w-8 h-8 rounded flex items-center justify-center text-sm underline transition-colors',
formatting.underline
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Subrayado (Ctrl+U)"
>
U
</button>
</div>
</div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300 dark:bg-primary/30"></div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Tamaño de fuente -->
<div class="flex items-center gap-2">
<span class="text-xs font-medium text-gray-600 dark:text-primary-dt/80">Tamaño:</span>
<!-- Tamaño de fuente -->
<select
:value="formatting.fontSize || 12"
@change="updateFontSize(parseInt($event.target.value))"
class="px-2 py-1 text-sm border border-gray-200 rounded bg-white dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
class="px-2 py-1 text-sm border border-gray-200 rounded bg-white focus:ring-2 focus:ring-blue-500"
>
<option v-for="size in fontSizes" :key="size" :value="size">
{{ size }}px
</option>
</select>
</div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300 dark:bg-primary/30"></div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Alineación -->
<div class="flex items-center gap-2">
<span class="text-xs font-medium text-gray-600 dark:text-primary-dt/80">Alinear:</span>
<!-- Alineación -->
<div class="flex gap-1">
<button
@click="updateTextAlign('left')"
@ -171,7 +207,7 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
'w-8 h-8 rounded flex items-center justify-center transition-colors',
(formatting.textAlign || 'left') === 'left'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Alinear izquierda"
>
@ -184,7 +220,7 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
'w-8 h-8 rounded flex items-center justify-center transition-colors',
formatting.textAlign === 'center'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Centrar"
>
@ -197,27 +233,23 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
'w-8 h-8 rounded flex items-center justify-center transition-colors',
formatting.textAlign === 'right'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200 dark:bg-primary-d dark:text-primary-dt dark:hover:bg-primary/10 dark:border-primary/20'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Alinear derecha"
>
<GoogleIcon name="format_align_right" class="text-sm" />
</button>
</div>
</div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300 dark:bg-primary/30"></div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Color de texto -->
<div class="flex items-center gap-2">
<span class="text-xs font-medium text-gray-600 dark:text-primary-dt/80">Color:</span>
<!-- Color -->
<div class="flex items-center gap-2">
<!-- Color actual -->
<div
class="w-8 h-8 rounded border-2 border-gray-300 cursor-pointer relative overflow-hidden"
:style="{ backgroundColor: formatting.color || '#000000' }"
title="Color actual"
title="Color de texto"
>
<input
type="color"
@ -227,10 +259,9 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
/>
</div>
<!-- Colores rápidos -->
<div class="flex gap-1">
<button
v-for="color in predefinedColors.slice(0, 6)"
v-for="color in predefinedColors.slice(0, 4)"
:key="color"
@click="updateColor(color)"
class="w-6 h-6 rounded border border-gray-300 hover:scale-110 transition-transform"
@ -242,12 +273,11 @@ const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
></button>
</div>
</div>
</div>
<!-- Información del elemento -->
<div class="ml-auto flex items-center gap-2 text-xs text-gray-500 dark:text-primary-dt/70">
<GoogleIcon name="text_fields" class="text-sm" />
<span>Elemento de texto seleccionado</span>
<!-- Información de estado -->
<div class="ml-auto text-xs text-gray-500">
{{ activeElementInfo?.context === 'table-cell' ? 'Formateando celda de tabla' : 'Formateando texto' }}
</div>
</div>
</div>
</template>

View File

@ -1,10 +1,11 @@
<script setup>
import { ref, nextTick, onMounted, computed } from 'vue';
import { ref, onMounted, computed } from 'vue';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import Draggable from '@Holos/Draggable.vue';
import CanvasElement from '@Holos/Canvas.vue';
import PDFViewport from '@Holos/PDFViewport.vue';
import Draggable from '@Holos/PDF/Draggable.vue';
import CanvasElement from '@Holos/PDF/Canvas.vue';
import PDFViewport from '@Holos/PDF/PDFViewport.vue';
import TextFormatter from '@Holos/PDF/TextFormatter.vue';
/** Estado reactivo */
const pages = ref([{ id: 1, elements: [] }]);
@ -13,10 +14,75 @@ const elementCounter = ref(0);
const documentTitle = ref('Documento sin título');
const isExporting = ref(false);
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 */
const viewportRef = ref(null);
/** Referencias adicionales para TextFormatter */
const selectedElement = ref(null);
const activeTextElement = ref(null);
const showTextFormatter = ref(false);
const selectElement = (elementId) => {
selectedElementId.value = elementId;
const selectedEl = allElements.value.find(el => el.id === elementId);
selectedElement.value = selectedEl;
// Mostrar TextFormatter si es texto o tabla
showTextFormatter.value = selectedEl?.type === 'text' || selectedEl?.type === 'table';
// Si es texto directo, activar como activeTextElement
if (selectedEl?.type === 'text') {
activeTextElement.value = selectedEl;
} else {
activeTextElement.value = null;
}
};
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
// Actualizar referencias si es necesario
if (selectedElement.value?.id === update.id) {
selectedElement.value = { ...element };
}
if (activeTextElement.value?.id === update.id) {
activeTextElement.value = { ...element };
}
}
};
// Manejar selección de texto dentro de celdas de tabla
const handleTextSelected = (data) => {
activeTextElement.value = data.element;
showTextFormatter.value = true;
};
/** Tipos de elementos disponibles */
const availableElements = [
{
@ -109,14 +175,6 @@ const handleDragOver = (event) => {
event.preventDefault();
};
const handleCanvasClick = (clickData) => {
selectedElementId.value = null;
};
const selectElement = (elementId) => {
selectedElementId.value = elementId;
};
const deleteElement = (elementId) => {
const index = allElements.value.findIndex(el => el.id === elementId);
if (index !== -1) {
@ -128,26 +186,11 @@ 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 */
const addPage = () => {
const newPageId = Math.max(...pages.value.map(p => p.id)) + 1;
pageIdCounter.value++; // <-- Incrementar contador independiente
pages.value.push({
id: newPageId,
id: pageIdCounter.value,
elements: []
});
};
@ -211,249 +254,270 @@ const exportPDF = async () => {
isExporting.value = true;
window.Notify.info('Generando PDF...');
// Crear un nuevo documento PDF
// Crear un nuevo documento PDF con el tamaño de página seleccionado
const pdfDoc = await PDFDocument.create();
let currentPage = pdfDoc.addPage([595.28, 841.89]); // A4 size in points
let currentPageHeight = 841.89;
let yOffset = 50; // Margen superior
// Convertir dimensiones de pixels a puntos (1 px = 0.75 puntos)
const pageWidthPoints = currentPageSize.value.width * 0.75;
const pageHeightPoints = currentPageSize.value.height * 0.75;
// Obtener fuentes
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const courierFont = await pdfDoc.embedFont(StandardFonts.Courier);
// Ordenar elementos por posición (de arriba hacia abajo, de izquierda a derecha)
const sortedElements = [...allElements.value].sort((a, b) => {
if (Math.abs(a.y - b.y) < 20) {
return a.x - b.x; // Si están en la misma línea, ordenar por X
}
return a.y - b.y; // Ordenar por Y
});
// Procesar páginas del maquetador
for (let pageIndex = 0; pageIndex < pages.value.length; pageIndex++) {
const page = pages.value[pageIndex];
// Crear nueva página PDF
let currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]);
let 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
// Ordenar elementos de esta página por posición
const sortedElements = [...page.elements].sort((a, b) => {
if (Math.abs(a.y - b.y) < 20) {
return a.x - b.x;
}
return a.y - b.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;
y = currentPageHeight - yOffset;
}
// Procesar elementos de la página
for (const element of sortedElements) {
// Calcular posición en el PDF manteniendo proporciones
const scaleX = pageWidthPoints / currentPageSize.value.width;
const scaleY = pageHeightPoints / currentPageSize.value.height;
const x = Math.max(50, element.x * scaleX);
const y = currentPageHeight - (element.y * scaleY) - 50;
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(400, (element.width || 200) * 0.75);
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
const testWidth = helveticaFont.widthOfTextAtSize(testLine, 12);
switch (element.type) {
case 'text':
if (element.content && element.content.trim()) {
// Obtener formato del elemento
const formatting = element.formatting || {};
const fontSize = Math.max(8, Math.min(72, formatting.fontSize || 12));
const isBold = formatting.bold || false;
const textAlign = formatting.textAlign || 'left';
if (testWidth <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
// Convertir color hexadecimal a RGB
let textColor = rgb(0, 0, 0);
if (formatting.color) {
const hex = formatting.color.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16) / 255;
const g = parseInt(hex.substr(2, 2), 16) / 255;
const b = parseInt(hex.substr(4, 2), 16) / 255;
textColor = rgb(r, g, b);
}
}
if (currentLine) lines.push(currentLine);
// Dibujar cada línea
lines.forEach((line, index) => {
currentPage.drawText(line, {
x: x,
y: y - (index * 15),
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0),
});
});
yOffset += lines.length * 15 + 10;
}
break;
case 'code':
if (element.content) {
// Dibujar fondo para el código
const codeLines = element.content.split('\n');
const codeWidth = Math.min(450, (element.width || 300) * 0.75);
const codeHeight = (codeLines.length * 12) + 20;
currentPage.drawRectangle({
x: x - 10,
y: y - codeHeight,
width: codeWidth,
height: codeHeight,
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);
}
// Seleccionar fuente
let font = isBold ? helveticaBoldFont : helveticaFont;
if (image) {
// 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;
// NUEVO: Dividir por párrafos (saltos de línea)
const paragraphs = element.content.split('\n');
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
const lineHeight = fontSize * 1.4;
let currentY = y;
paragraphs.forEach((paragraph, paragraphIndex) => {
if (paragraph.trim() === '') {
// Párrafo vacío - solo agregar espacio
currentY -= lineHeight;
return;
}
currentPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
// Dividir párrafo en líneas que caben en el ancho
const words = paragraph.split(' ');
const lines = [];
let currentLine = '';
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
if (testWidth <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
}
if (currentLine) lines.push(currentLine);
// Dibujar cada línea del párrafo
lines.forEach((line, lineIndex) => {
let lineX = x;
const lineWidth = font.widthOfTextAtSize(line, fontSize);
// Calcular posición X según alineación
if (textAlign === 'center') {
lineX = x + (maxWidth - lineWidth) / 2;
} else if (textAlign === 'right') {
lineX = x + maxWidth - lineWidth;
}
currentPDFPage.drawText(line, {
x: Math.max(50, lineX),
y: currentY,
size: fontSize,
font: font,
color: textColor,
});
currentY -= lineHeight;
});
yOffset += displayHeight + 20;
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Dibujar placeholder para imagen
currentPage.drawRectangle({
x: x,
y: y - 60,
width: 100,
height: 60,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
// Agregar espacio extra entre párrafos
if (paragraphIndex < paragraphs.length - 1) {
currentY -= lineHeight * 0.3;
}
});
currentPage.drawText('[Imagen no disponible]', {
x: x + 5,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
yOffset += 80;
}
} 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],
});
break;
currentPage.drawText('[Imagen]', {
x: x + 25,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
case 'image':
if (element.content && element.content.startsWith('data:image')) {
try {
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);
}
yOffset += 80;
}
break;
if (image) {
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
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;
}
case 'table':
if (element.content && element.content.data) {
const tableData = element.content.data;
const cellWidth = 80;
const cellHeight = 20;
const tableWidth = tableData[0].length * cellWidth;
const tableHeight = tableData.length * cellHeight;
// Dibujar bordes de la tabla
currentPage.drawRectangle({
x: x,
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.3, 0.3, 0.3),
borderWidth: 1,
});
// Dibujar contenido de las celdas
tableData.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight) - 15;
// Dibujar borde de celda
currentPage.drawRectangle({
x: cellX,
y: y - ((rowIndex + 1) * cellHeight),
width: cellWidth,
height: cellHeight,
currentPDFPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
});
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Placeholder para imagen con error
currentPDFPage.drawRectangle({
x: x,
y: y - 60,
width: 100 * scaleX,
height: 60 * scaleY,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
borderWidth: 1,
});
// 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,
currentPDFPage.drawText('[Error al cargar imagen]', {
x: x + 5,
y: y - 35,
size: 10,
font: helveticaFont,
color: rowIndex === 0 ? rgb(0.2, 0.2, 0.8) : rgb(0, 0, 0), // Encabezados en azul
color: rgb(0.7, 0.7, 0.7),
});
});
});
}
}
break;
yOffset += tableHeight + 20;
}
break;
case 'table':
if (element.content && element.content.data && Array.isArray(element.content.data)) {
const tableData = element.content.data;
const totalCols = tableData[0]?.length || 0;
const totalRows = tableData.length;
if (totalCols > 0 && totalRows > 0) {
const availableWidth = Math.min(pageWidthPoints - 100, (element.width || 300) * scaleX);
const cellWidth = availableWidth / totalCols;
const cellHeight = 25;
const tableWidth = cellWidth * totalCols;
const tableHeight = cellHeight * totalRows;
// Dibujar borde exterior de la tabla
currentPDFPage.drawRectangle({
x: x,
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.2, 0.2, 0.2),
borderWidth: 1.5,
});
// Dibujar cada celda
tableData.forEach((row, rowIndex) => {
if (Array.isArray(row)) {
row.forEach((cell, colIndex) => {
const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight);
// Dibujar borde de celda
currentPDFPage.drawRectangle({
x: cellX,
y: cellY - cellHeight,
width: cellWidth,
height: cellHeight,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
// Fondo especial para headers
if (rowIndex === 0) {
currentPDFPage.drawRectangle({
x: cellX,
y: cellY - cellHeight,
width: cellWidth,
height: cellHeight,
color: rgb(0.95, 0.95, 1),
});
}
// Dibujar texto de la celda
if (cell && typeof cell === 'string' && cell.trim()) {
const maxChars = Math.max(1, Math.floor(cellWidth / 6));
let displayText = cell.trim();
if (displayText.length > maxChars) {
displayText = displayText.substring(0, maxChars - 3) + '...';
}
const fontSize = Math.max(8, Math.min(12, cellWidth / 8));
const font = rowIndex === 0 ? helveticaBoldFont : helveticaFont;
const textColor = rowIndex === 0 ? rgb(0.1, 0.1, 0.6) : rgb(0, 0, 0);
const textWidth = font.widthOfTextAtSize(displayText, fontSize);
const textX = cellX + (cellWidth - textWidth) / 2;
const textY = cellY - cellHeight/2 - fontSize/2;
currentPDFPage.drawText(displayText, {
x: Math.max(cellX + 2, textX),
y: Math.max(cellY - cellHeight + 5, textY),
size: fontSize,
font: font,
color: textColor,
});
}
});
}
});
}
}
break;
default:
console.warn(`Tipo de elemento no soportado: ${element.type}`);
break;
}
}
}
@ -475,7 +539,7 @@ const exportPDF = async () => {
} catch (error) {
console.error('Error al generar PDF:', error);
window.Notify.error('Error al generar el PDF');
window.Notify.error('Error al generar el PDF: ' + error.message);
} finally {
isExporting.value = false;
}
@ -504,6 +568,8 @@ const clearCanvas = () => {
pages.value = [{ id: 1, elements: [] }];
selectedElementId.value = null;
elementCounter.value = 0;
pageIdCounter.value = 1; // <-- Resetear también el contador de páginas
currentPage.value = 1;
}
};
@ -525,14 +591,14 @@ onMounted(() => {
</script>
<template>
<div class="flex h-screen bg-gray-50 dark:bg-primary-d/50">
<!-- 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="flex flex-col lg:flex-row h-screen bg-gray-50">
<!-- Panel Izquierdo - Responsive -->
<div class="w-full lg:w-64 bg-white border-r border-gray-200 flex flex-col">
<!-- Header del panel -->
<div class="p-4 border-b border-gray-200 dark:border-primary/20">
<div class="flex items-center gap-2 mb-4">
<GoogleIcon name="text_snippet" class="text-blue-600 dark:text-blue-400 text-xl" />
<h2 class="font-semibold text-gray-900 dark:text-primary-dt text-sm">
<div class="p-3 lg:p-4 border-b border-gray-200">
<div class="flex items-center gap-2 mb-3 lg:mb-4">
<GoogleIcon name="text_snippet" class="text-blue-600 text-lg lg:text-xl" />
<h2 class="font-semibold text-gray-900 text-sm">
Diseñador de Documentos
</h2>
</div>
@ -540,7 +606,7 @@ onMounted(() => {
<!-- Título del documento -->
<input
v-model="documentTitle"
class="w-full px-2 py-1 text-xs border border-gray-200 rounded mb-3 dark:bg-primary-d dark:border-primary/20 dark:text-primary-dt"
class="w-full px-2 py-1 text-xs border border-gray-200 rounded mb-3"
placeholder="Título del documento"
/>
@ -548,12 +614,8 @@ onMounted(() => {
<button
@click="exportPDF"
:disabled="isExporting"
:class="[
'w-full flex items-center justify-center gap-2 px-3 py-2 text-sm rounded transition-colors',
isExporting
? 'bg-gray-400 text-white cursor-not-allowed'
: 'bg-red-600 hover:bg-red-700 text-white'
]"
class="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm rounded transition-colors"
:class="isExporting ? 'bg-gray-400 text-white cursor-not-allowed' : 'bg-red-600 hover:bg-red-700 text-white'"
>
<GoogleIcon :name="isExporting ? 'hourglass_empty' : 'picture_as_pdf'" class="text-sm" />
{{ isExporting ? 'Generando PDF...' : 'Exportar PDF' }}
@ -561,15 +623,16 @@ onMounted(() => {
</div>
<!-- Sección Elementos -->
<div class="p-4 flex-1 overflow-y-auto">
<h3 class="text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider mb-3">
<div class="p-3 lg:p-4 flex-1 overflow-y-auto">
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
Elementos
</h3>
<p class="text-xs text-gray-400 dark:text-primary-dt/70 mb-4">
<p class="text-xs text-gray-400 mb-4 hidden lg:block">
Arrastra elementos al canvas para crear tu documento
</p>
<div class="space-y-3">
<!-- Grid responsive de elementos -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-2 lg:gap-3">
<Draggable
v-for="element in availableElements"
:key="element.type"
@ -580,58 +643,66 @@ onMounted(() => {
/>
</div>
<!-- Agregar rápido -->
<h3 class="text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider mt-6 mb-3">
Agregar rápido
</h3>
<div class="space-y-2">
<button
v-for="element in availableElements"
:key="`quick-${element.type}`"
@click="addQuickElement(element.type)"
:disabled="isExporting"
class="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-primary-dt hover:bg-gray-100 dark:hover:bg-primary/10 rounded transition-colors disabled:opacity-50"
>
<GoogleIcon name="add" class="text-gray-400 dark:text-primary-dt/70 text-sm" />
{{ element.title }}
</button>
</div>
</div>
</div>
<!-- Área Principal con Viewport -->
<div class="flex-1 flex flex-col">
<!-- 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="flex items-center gap-4">
<!-- Herramientas de formato (simuladas) -->
<div class="flex items-center gap-1 text-sm">
<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" />
<!-- Agregar rápido - Solo en desktop -->
<div class="hidden lg:block">
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mt-6 mb-3">
Agregar rápido
</h3>
<div class="space-y-2">
<button
v-for="element in availableElements"
:key="`quick-${element.type}`"
@click="addQuickElement(element.type)"
:disabled="isExporting"
class="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
>
<GoogleIcon name="add" class="text-gray-400 text-sm" />
{{ element.title }}
</button>
</div>
</div>
<div class="flex items-center gap-4">
<span class="text-xs text-gray-500 dark:text-primary-dt/70">
{{ totalElements }} elemento{{ totalElements !== 1 ? 's' : '' }} {{ pages.length }} página{{ pages.length !== 1 ? 's' : '' }}
</span>
<!-- Limpiar todo -->
<div class="pt-4 mt-4 border-t border-gray-200">
<button
v-if="totalElements > 0"
@click="clearCanvas"
:disabled="isExporting"
class="flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 rounded transition-colors disabled:opacity-50"
class="w-full flex items-center justify-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 rounded transition-colors disabled:opacity-50"
>
<GoogleIcon name="delete" class="text-sm" />
Limpiar Todo
</button>
</div>
</div>
</div>
<!-- Área Principal con Viewport -->
<div class="flex-1 flex flex-col min-h-0">
<!-- Toolbar superior básico -->
<div class="h-12 lg:h-14 bg-white border-b border-gray-200 flex items-center justify-between px-3 lg:px-4">
<div class="flex items-center gap-2 lg:gap-4">
<h2 class="font-semibold text-gray-900 text-sm truncate max-w-32 lg:max-w-none">
{{ documentTitle }}
</h2>
</div>
<div class="flex items-center gap-2 lg:gap-4">
<span class="text-xs text-gray-500 hidden sm:block">
{{ totalElements }} elemento{{ totalElements !== 1 ? 's' : '' }} {{ pages.length }} página{{ pages.length !== 1 ? 's' : '' }}
</span>
</div>
</div>
<!-- TextFormatter estático y universal -->
<TextFormatter
:selected-element="selectedElement"
:active-text-element="activeTextElement"
:visible="showTextFormatter"
@update="updateElement"
@smart-align="handleSmartAlign"
/>
<!-- PDFViewport -->
<PDFViewport
@ -644,6 +715,7 @@ onMounted(() => {
@add-page="addPage"
@delete-page="deletePage"
@page-change="(page) => currentPage = page"
@page-size-change="handlePageSizeChange"
>
<template #elements="{ page, pageIndex }">
<CanvasElement
@ -655,6 +727,7 @@ onMounted(() => {
@delete="deleteElement"
@update="updateElement"
@move="moveElement"
@text-selected="handleTextSelected"
/>
</template>
</PDFViewport>