Files
ferramentas/editor.php
T

685 lines
27 KiB
PHP

<!DOCTYPE html>
<html>
<head>
<title>Editor de Documentos</title>
<link href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/downloadjs@1.4.7/download.js"></script>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
body {
display: flex;
flex-direction: column;
font-family: Arial, sans-serif;
background: #f5f5f5;
}
/* Container principal com scroll */
.editor-container {
max-width: 1600px;
margin: 0 auto;
padding: 20px;
height: calc(100vh - 20px);
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 20px;
}
/* Container da imagem ajustado */
.img-container {
position: relative;
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
height: 70vh;
min-height: 500px;
max-height: 800px;
margin: 20px 0;
overflow: hidden;
}
/* Ajustes do Cropper */
.cropper-container {
position: relative !important;
width: 100% !important;
height: 100% !important;
}
.cropper-wrap-box {
background-color: #f8f8f8;
}
/* Pontos de redimensionamento maiores e mais visíveis */
.cropper-point {
width: 25px !important;
height: 25px !important;
background-color: #4CAF50 !important;
border: 3px solid white !important;
opacity: 1 !important;
border-radius: 50% !important;
}
.cropper-point.point-se {
width: 25px !important;
height: 25px !important;
opacity: 1 !important;
}
.cropper-view-box {
outline: 2px solid #4CAF50 !important;
outline-color: rgba(74, 175, 80, 0.75) !important;
}
.cropper-line {
width: 3px !important;
height: 3px !important;
background-color: #4CAF50 !important;
opacity: 0.8 !important;
}
/* Z-index ajustados */
.cropper-face {
z-index: 2 !important;
}
.cropper-line, .cropper-point {
z-index: 3 !important;
}
/* Área de controles sempre visível */
.controls-section {
position: sticky;
bottom: 70px;
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 4;
}
.toolbar {
position: sticky;
bottom: 0;
background: #fff;
padding: 15px;
border-radius: 8px 8px 0 0;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
z-index: 5;
}
.controls {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
}
.range-control {
margin-bottom: 10px;
}
.range-control label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.range-control input[type="range"] {
width: 100%;
}
.toolbar {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
text-align: center;
background: #fff;
border-radius: 4px;
}
.toolbar button {
padding: 10px 20px;
margin: 0 8px;
font-weight: 500;
transition: all 0.3s ease;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.toolbar button:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
background: #45a049;
}
#preview {
display: block;
max-width: 100%;
max-height: 100%;
margin: auto;
}
.cropper-container {
width: 100% !important;
height: 100% !important;
}
.cropper-wrap-box {
background-color: #f8f8f8;
}
.cropper-view-box {
outline: 2px solid #4CAF50;
outline-color: rgba(74, 175, 80, 0.75);
}
.cropper-point {
width: 15px !important;
height: 15px !important;
background-color: #4CAF50;
opacity: 0.9;
border-radius: 50%;
}
.cropper-point.point-se {
width: 20px !important;
height: 20px !important;
background-color: #4CAF50;
}
.cropper-line {
background-color: #4CAF50;
opacity: 0.4;
}
.thumbnails {
height: 130px;
padding: 15px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: flex;
gap: 10px;
overflow-x: auto;
flex-shrink: 0; /* Impede encolhimento */
}
.thumbnail {
width: 110px;
height: 100px;
margin-right: 15px;
border-radius: 4px;
transition: all 0.3s ease;
object-fit: cover;
cursor: pointer;
border: 2px solid transparent;
}
.thumbnail:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
.thumbnail.active {
border-color: #4CAF50;
}
#preview-container {
position: relative;
width: 100%;
height: 100%;
}
#preview-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.cropper-point {
width: 12px !important;
height: 12px !important;
background-color: #4CAF50 !important;
opacity: 0.8 !important;
}
/* Cursores específicos para cada ponto */
.cropper-point.point-e { cursor: e-resize !important; }
.cropper-point.point-n { cursor: n-resize !important; }
.cropper-point.point-w { cursor: w-resize !important; }
.cropper-point.point-s { cursor: s-resize !important; }
.cropper-point.point-ne { cursor: ne-resize !important; }
.cropper-point.point-nw { cursor: nw-resize !important; }
.cropper-point.point-sw { cursor: sw-resize !important; }
.cropper-point.point-se { cursor: se-resize !important; }
/* Linhas da caixa de recorte */
.cropper-line {
background-color: #4CAF50 !important;
opacity: 0.3 !important;
}
/* Área de recorte */
.cropper-view-box {
outline: 2px solid #4CAF50 !important;
outline-color: rgba(74, 175, 80, 0.75) !important;
}
/* Área fora do recorte */
.cropper-modal {
background-color: rgba(0, 0, 0, 0.5) !important;
}
/* Container do Cropper */
.cropper-container {
margin: auto;
max-height: calc(100vh - 350px) !important;
}
</style>
</head>
<body>
<div class="editor-container">
<div class="thumbnails" id="thumbnails">
<!-- Miniaturas serão inseridas aqui -->
</div>
<div class="img-container">
<div id="preview-container">
<img id="preview" src="">
<canvas id="preview-canvas"></canvas>
</div>
</div>
<div class="controls-section">
<div class="controls">
<div class="range-control">
<label>Brilho</label>
<input type="range" min="-100" max="100" value="0" id="brightness" oninput="adjustImage()">
<span id="brightnessValue">0</span>
</div>
<div class="range-control">
<label>Contraste</label>
<input type="range" min="-100" max="100" value="0" id="contrast" oninput="adjustImage()">
<span id="contrastValue">0</span>
</div>
<div class="range-control">
<label>Saturação</label>
<input type="range" min="-100" max="100" value="0" id="saturation" oninput="adjustImage()">
<span id="saturationValue">0</span>
</div>
<div class="range-control">
<label>Matiz</label>
<input type="range" min="-180" max="180" value="0" id="hue" oninput="adjustImage()">
<span id="hueValue">0</span>
</div>
</div>
</div>
<div class="toolbar">
<button onclick="resetImage()">Resetar</button>
<button onclick="rotateCCW()">Girar Esquerda</button>
<button onclick="rotateCW()">Girar Direita</button>
<button onclick="cropImage()">Recortar</button>
<button onclick="applyCrop()">Aplicar Recorte</button>
<button onclick="autoAdjust()">Otimização Automática</button>
<button onclick="combineImages()" style="background: #FF9800;">Unir Imagens</button>
<button onclick="saveImage()" style="background: #2196F3;">Salvar</button>utton onclick="applyCrop()">Aplicar Recorte</button>
</div>div>
</div> </div>
<script src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.js"></script>src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.js"></script>
<script>
let cropper = null;
let currentImage = null; let currentImage = null;
function initCropper(url) {
return new Promise((resolve) => {
const preview = document.getElementById('preview');cument.getElementById('preview');
preview.src = url;preview.src = url;
if (cropper) {
cropper.destroy();();
cropper = null; cropper = null;
} }
preview.onload = function() {
cropper = new Cropper(preview, {opper(preview, {
viewMode: 2,
dragMode: 'crop',
aspectRatio: NaN,N,
autoCrop: true,
autoCropArea: 0.98,
cropBoxResizable: true,
cropBoxMovable: true,
zoomable: false,
rotatable: true,e,
scalable: false,
ready: function() {
// Garantir que o cropper está inicializado
if (!this.cropper) return; toggleDragModeOnDblclick: true,
// Mostrar área de recorte
const cropBox = this.cropper.getCropBoxData();
const container = this.cropper.getContainerData(); });
};
}); crop box
}
function cropImage() {
if (!cropper) return;
height: container.height * 0.8
if (cropper.getData().width === 0) { });
// Se não houver área de recorte, criar uma
const containerData = cropper.getContainerData();
const minSize = Math.min(containerData.width, containerData.height);.images[currentImageIndex].filters };
erInputs();
// Criar área de recorte no centro resolve();
cropper.setCropBoxData({ }
left: (containerData.width - minSize * 0.8) / 2, });
top: (containerData.height - minSize * 0.8) / 2, };
width: minSize * 0.8, });
height: minSize * 0.8 }
});
}
if (!cropper) return;
// Alternar entre modos crop e move
if (cropper.options.dragMode === 'crop') {
cropper.setDragMode('move');cropper.setDragMode('crop');
// Aplicar o recorte atual
const canvas = cropper.getCroppedCanvas();= document.querySelector('.cropper-crop-box');
if (canvas) {
const croppedImageUrl = canvas.toDataURL('image/jpeg');cropBox.style.display = 'block';
cropper.replace(croppedImageUrl);
}
} else {a();
cropper.setDragMode('crop');const current = cropper.getCropBoxData();
}
h < 50) {
// Atualizar a UI
const cropBox = document.querySelector('.cropper-crop-box');
if (cropBox) {
cropBox.style.display = 'block';
} height: container.height * 0.8
});
// Forçar atualização do cropper}
cropper.clear();
setTimeout(() => {
cropper.crop();r-point').forEach(point => {
}, 50);
}
function applyCrop() {
if (!cropper) return;';
const canvas = cropper.getCroppedCanvas({
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high' if (point.classList.contains('point-w')) point.style.cursor = 'w-resize';
}); });
}
if (canvas) { }
const croppedImageUrl = canvas.toDataURL('image/jpeg');
cropper.destroy(); {
initCropper(croppedImageUrl);cropper) return;
}
}.rotate(90);
async function rotateCW() { console.error('Erro ao rotacionar:', error);
if (!cropper) return; }
try { }
await cropper.rotate(90);
} catch (error) {) {
console.error('Erro ao rotacionar:', error);cropper) return;
}
}.rotate(-90);
async function rotateCCW() { console.error('Erro ao rotacionar:', error);
if (!cropper) return; }
try { }
await cropper.rotate(-90);
} catch (error) {
console.error('Erro ao rotacionar:', error);currentImageIndex = index;
}
}
function switchImage(index) { thumb.className = 'thumbnail' + (i === index ? ' active' : '');
currentImageIndex = index; });
// Atualizar miniaturas
document.querySelectorAll('.thumbnail').forEach((thumb, i) => {s[index].url)
thumb.className = 'thumbnail' + (i === index ? ' active' : '');
});iltros após inicialização
// Carregar nova imagem.images[index].filters };
initCropper(images[index].url)
.then(() => { applyCurrentFilters();
// Restaurar filtros após inicialização }
if (cropper) { });
currentFilters = { ...images[index].filters }; }
updateFilterInputs();
applyCurrentFilters();
}= 0;
}); {
}0,
let images = [];tion: 100,
let currentImageIndex = 0; hue: 0
let currentFilters = { };
brightness: 100,
contrast: 100,load = function() {
saturation: 100,
hue: 0tem('allImages')) || [];
};console.log('Imagens carregadas:', allImages);
window.onload = function() {
try {s.map(img => ({
const allImages = JSON.parse(localStorage.getItem('allImages')) || [];
console.log('Imagens carregadas:', allImages);filters: { ...currentFilters }
if (allImages.length > 0) {
images = allImages.map(img => ({rl = localStorage.getItem('tempImage');
url: img.url,
filters: { ...currentFilters }
})); filters: { ...currentFilters }
} else { }];
const baseUrl = localStorage.getItem('tempImage'); }
images = [{
url: baseUrl,
filters: { ...currentFilters }t.getElementById('thumbnails');
}];thumbnailsContainer.innerHTML = '';
}
// Criar miniaturas.createElement('img');
const thumbnailsContainer = document.getElementById('thumbnails');
thumbnailsContainer.innerHTML = '';= 0 ? ' active' : '');
);
images.forEach((image, index) => { thumbnailsContainer.appendChild(thumb);
const thumb = document.createElement('img'); });
thumb.src = image.url;
thumb.className = 'thumbnail' + (index === 0 ? ' active' : '');gem
thumb.onclick = () => switchImage(index);mages[0].url);
thumbnailsContainer.appendChild(thumb);
});
alert('Erro ao carregar imagens: ' + error.message);
// Inicializar primeira imagem }
initCropper(images[0].url); };
} catch (error) {
console.error('Erro ao inicializar editor:', error);
alert('Erro ao carregar imagens: ' + error.message);100;
}
};rs.saturation - 100;
document.getElementById('hue').value = currentFilters.hue;
function updateFilterInputs() {
document.getElementById('brightness').value = currentFilters.brightness - 100;100;
document.getElementById('contrast').value = currentFilters.contrast - 100;
document.getElementById('saturation').value = currentFilters.saturation - 100;rs.saturation - 100;
document.getElementById('hue').value = currentFilters.hue; document.getElementById('hueValue').textContent = currentFilters.hue;
}
document.getElementById('brightnessValue').textContent = currentFilters.brightness - 100;
document.getElementById('contrastValue').textContent = currentFilters.contrast - 100; {
document.getElementById('saturationValue').textContent = currentFilters.saturation - 100;
document.getElementById('hueValue').textContent = currentFilters.hue;100,
}
ation').value) + 100,
function adjustImage() { hue: parseInt(document.getElementById('hue').value)
currentFilters = { };
brightness: parseInt(document.getElementById('brightness').value) + 100,
contrast: parseInt(document.getElementById('contrast').value) + 100,
saturation: parseInt(document.getElementById('saturation').value) + 100,ex].filters = { ...currentFilters };
hue: parseInt(document.getElementById('hue').value) applyCurrentFilters();
}; }
// Salvar filtros para a imagem atualers() {
images[currentImageIndex].filters = { ...currentFilters };if (!cropper) return;
applyCurrentFilters();
}
if (!canvas || canvas.width === 0 || canvas.height === 0) return;
function applyCurrentFilters() {
if (!cropper) return;
teElement('canvas');
const canvas = cropper.getCroppedCanvas();
if (!canvas || canvas.width === 0 || canvas.height === 0) return;tempCanvas.height = canvas.height;
try {
const tempCanvas = document.createElement('canvas');ss}%)
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;)
hue-rotate(${currentFilters.hue}deg)`;
const ctx = tempCanvas.getContext('2d');
ctx.filter = `brightness(${currentFilters.brightness}%)
contrast(${currentFilters.contrast}%) ce(tempCanvas.toDataURL('image/jpeg'));
saturate(${currentFilters.saturation}%)
hue-rotate(${currentFilters.hue}deg)`; console.error('Erro ao aplicar filtros:', error);
}
ctx.drawImage(canvas, 0, 0); }
cropper.replace(tempCanvas.toDataURL('image/jpeg'));
} catch (error) {ction combineImages() {
console.error('Erro ao aplicar filtros:', error);
}.jspdf;
}sPDF();
let currentY = 0;
async function combineImages() {
try {
const { jsPDF } = window.jspdf;
const pdf = new jsPDF();reateElement('canvas');
let currentY = 0;
canvas.height = img.height;
for (let image of images) {
const img = await createImage(image.url);
const canvas = document.createElement('canvas');ss}%)
canvas.width = img.width;
canvas.height = img.height;)
hue-rotate(${image.filters.hue}deg)`;
const ctx = canvas.getContext('2d');
ctx.filter = `brightness(${image.filters.brightness}%) ctx.drawImage(img, 0, 0);
contrast(${image.filters.contrast}%)
saturate(${image.filters.saturation}%) {
hue-rotate(${image.filters.hue}deg)`; pdf.addPage();
}
ctx.drawImage(img, 0, 0);
if (currentY > 0) { pdf.addImage(imgData, 'JPEG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height, '', 'FAST');
pdf.addPage(); }
}
const imgData = canvas.toDataURL('image/jpeg', 1.0);utput('datauristring');
pdf.addImage(imgData, 'JPEG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height, '', 'FAST'); initCropper(pdfData);
}
// Preview do PDF combinado
const pdfData = pdf.output('datauristring'); alert('Erro ao combinar imagens: ' + error.message);
initCropper(pdfData); }
}
} catch (error) {
console.error('Erro ao combinar imagens:', error);
alert('Erro ao combinar imagens: ' + error.message); reject) => {
}
}solve(img);
reject;
function createImage(url) { img.src = url;
return new Promise((resolve, reject) => { });
const img = new Image(); }
img.onload = () => resolve(img);
img.onerror = reject;e() {
img.src = url;
});
}
0,
function resetImage() {
if (cropper) {tion: 100,
cropper.reset(); hue: 0
currentFilters = {
brightness: 100,dex].filters = { ...currentFilters };
contrast: 100,
saturation: 100, applyCurrentFilters();
hue: 0 }
}; }
images[currentImageIndex].filters = { ...currentFilters };
updateFilterInputs();
applyCurrentFilters();a aqui
} alert('Função em desenvolvimento');
} }
function autoAdjust() {Image() {
// Implementar otimização automática aqui
alert('Função em desenvolvimento');Editor não inicializado corretamente');
} return;
}
async function saveImage() {
if (!cropper) {
alert('Editor não inicializado corretamente');
return;per.getCroppedCanvas({
}
try {
// Obter canvas com filtros aplicados
const canvas = cropper.getCroppedCanvas({ imageSmoothingQuality: 'high',
maxWidth: 4096, });
maxHeight: 4096,
fillColor: '#fff',
imageSmoothingEnabled: true, throw new Error('Não foi possível gerar a imagem');
imageSmoothingQuality: 'high', }
});
if (!canvas) {w.jspdf;
throw new Error('Não foi possível gerar a imagem');
}: canvas.width > canvas.height ? 'l' : 'p',
// Criar PDF format: [canvas.width, canvas.height]
const { jsPDF } = window.jspdf; });
const pdf = new jsPDF({
orientation: canvas.width > canvas.height ? 'l' : 'p',
unit: 'px',
format: [canvas.width, canvas.height] pdf.addImage(imgData, 'JPEG', 0, 0, canvas.width, canvas.height);
});
// Adicionar imagem ao PDF const pdfBlob = pdf.output('blob');
const imgData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(imgData, 'JPEG', 0, 0, canvas.width, canvas.height);
// Converter PDF para Blob);
const pdfBlob = pdf.output('blob'); formData.append('doc_type', localStorage.getItem('tempDocType'));
const formData = new FormData();ait fetch('index.php?page=save_edited', {
formData.append('image', pdfBlob, 'documento.pdf');,
formData.append('client_id', localStorage.getItem('tempClientId')); body: formData
formData.append('doc_type', localStorage.getItem('tempDocType')); });
const response = await fetch('index.php?page=save_edited', {
method: 'POST', throw new Error(`HTTP error! status: ${response.status}`);
body: formData }
});
response.json();
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);{
}entSaved',
: result
const result = await response.json();*');
if (result.success) {
window.parent.postMessage({ throw new Error(result.message || 'Erro ao salvar');
type: 'documentSaved', }
data: result
}, '*');
} else {
throw new Error(result.message || 'Erro ao salvar'); alert('Erro ao processar: ' + error.message);
} }
} catch (error) {cript>
console.error('Erro:', error);
alert('Erro ao processar: ' + error.message);</html>
</html></body> </script> } }