Spaces:
Running
Running
Download script.js from andum89y7/pdf-alchemist-pro: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/andum89y7/pdf-alchemist-pro/resolve/main/script.js
- Command line
-
hf download hf://spaces/andum89y7/pdf-alchemist-pro/script.js
-
curl -L -o script.js https://huggingface.co/spaces/andum89y7/pdf-alchemist-pro/resolve/main/script.js
15.9 kB
| // PDF Alchemist Pro - Main Application Logic | |
| // Global State | |
| const AppState = { | |
| pdfDoc: null, | |
| currentPage: 1, | |
| totalPages: 0, | |
| zoom: 1.0, | |
| rotation: 0, | |
| scale: 1.5, | |
| tool: 'select', // select, text, draw, highlight, erase | |
| pages: [], | |
| history: [], | |
| darkMode: false, | |
| filename: 'document.pdf' | |
| }; | |
| // Initialize PDF.js worker | |
| pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'; | |
| // DOM Elements | |
| const dropZone = document.getElementById('drop-zone'); | |
| const fileInput = document.getElementById('file-input'); | |
| // Event Listeners | |
| document.addEventListener('DOMContentLoaded', () => { | |
| setupDragAndDrop(); | |
| setupKeyboardShortcuts(); | |
| loadDefaultPDF(); | |
| }); | |
| // Drag and Drop | |
| function setupDragAndDrop() { | |
| ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { | |
| document.body.addEventListener(eventName, preventDefaults, false); | |
| }); | |
| function preventDefaults(e) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| } | |
| document.body.addEventListener('dragenter', () => { | |
| dropZone.classList.remove('hidden'); | |
| }); | |
| dropZone.addEventListener('dragleave', (e) => { | |
| if (e.target === dropZone) { | |
| dropZone.classList.add('hidden'); | |
| } | |
| }); | |
| dropZone.addEventListener('drop', (e) => { | |
| dropZone.classList.add('hidden'); | |
| const files = e.dataTransfer.files; | |
| if (files.length && files[0].type === 'application/pdf') { | |
| loadPDF(files[0]); | |
| } | |
| }); | |
| } | |
| // File Handling | |
| function openFileDialog() { | |
| fileInput.click(); | |
| fileInput.onchange = (e) => { | |
| if (e.target.files.length) { | |
| loadPDF(e.target.files[0]); | |
| } | |
| }; | |
| } | |
| async function loadPDF(file) { | |
| try { | |
| showLoading(true); | |
| AppState.filename = file.name; | |
| const arrayBuffer = await file.arrayBuffer(); | |
| const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise; | |
| AppState.pdfDoc = pdf; | |
| AppState.totalPages = pdf.numPages; | |
| AppState.currentPage = 1; | |
| AppState.pages = []; | |
| // Render all pages | |
| await renderAllPages(); | |
| updateUI(); | |
| showLoading(false); | |
| } catch (error) { | |
| console.error('Error loading PDF:', error); | |
| alert('Error loading PDF file. Please try again.'); | |
| showLoading(false); | |
| } | |
| } | |
| async function loadDefaultPDF() { | |
| // Create a blank PDF page as placeholder | |
| const canvas = document.getElementById('main-canvas'); | |
| if (canvas) { | |
| const ctx = canvas.getContext('2d'); | |
| canvas.width = 600; | |
| canvas.height = 800; | |
| ctx.fillStyle = '#f8fafc'; | |
| ctx.fillRect(0, 0, canvas.width, canvas.height); | |
| ctx.strokeStyle = '#cbd5e1'; | |
| ctx.strokeRect(50, 50, canvas.width - 100, canvas.height - 100); | |
| ctx.fillStyle = '#64748b'; | |
| ctx.font = '20px Inter'; | |
| ctx.textAlign = 'center'; | |
| ctx.fillText('Drop a PDF file here or click Open', canvas.width / 2, canvas.height / 2); | |
| } | |
| } | |
| async function renderAllPages() { | |
| const container = document.getElementById('pages-container'); | |
| if (!container) return; | |
| container.innerHTML = ''; | |
| for (let i = 1; i <= AppState.totalPages; i++) { | |
| const pageDiv = document.createElement('div'); | |
| pageDiv.className = 'pdf-page mb-4 relative'; | |
| pageDiv.id = `page-${i}`; | |
| const canvas = document.createElement('canvas'); | |
| canvas.className = 'shadow-lg mx-auto block'; | |
| const page = await AppState.pdfDoc.getPage(i); | |
| const viewport = page.getViewport({ scale: AppState.scale * AppState.zoom }); | |
| canvas.height = viewport.height; | |
| canvas.width = viewport.width; | |
| const renderContext = { | |
| canvasContext: canvas.getContext('2d'), | |
| viewport: viewport | |
| }; | |
| await page.render(renderContext).promise; | |
| // Add text layer for selection | |
| const textLayer = document.createElement('div'); | |
| textLayer.className = 'textLayer'; | |
| textLayer.style.height = `${viewport.height}px`; | |
| textLayer.style.width = `${viewport.width}px`; | |
| const textContent = await page.getTextContent(); | |
| const textLayerRender = { | |
| textContent: textContent, | |
| container: textLayer, | |
| viewport: viewport, | |
| textDivs: [] | |
| }; | |
| await pdfjsLib.renderTextLayer(textLayerRender).promise; | |
| pageDiv.appendChild(canvas); | |
| pageDiv.appendChild(textLayer); | |
| container.appendChild(pageDiv); | |
| // Add to thumbnail sidebar | |
| addThumbnail(canvas, i); | |
| } | |
| updateStatusBar(); | |
| } | |
| function addThumbnail(canvas, pageNum) { | |
| const thumbnailContainer = document.getElementById('thumbnail-container'); | |
| if (!thumbnailContainer) return; | |
| const thumb = document.createElement('div'); | |
| thumb.className = `thumbnail mb-3 rounded-lg overflow-hidden bg-white shadow-sm ${pageNum === 1 ? 'active' : ''}`; | |
| thumb.onclick = () => scrollToPage(pageNum); | |
| const thumbCanvas = document.createElement('canvas'); | |
| const scale = 0.2; | |
| thumbCanvas.width = canvas.width * scale; | |
| thumbCanvas.height = canvas.height * scale; | |
| const ctx = thumbCanvas.getContext('2d'); | |
| ctx.drawImage(canvas, 0, 0, thumbCanvas.width, thumbCanvas.height); | |
| const label = document.createElement('div'); | |
| label.className = 'text-center text-xs py-1 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 font-medium'; | |
| label.textContent = pageNum; | |
| thumb.appendChild(thumbCanvas); | |
| thumb.appendChild(label); | |
| thumbnailContainer.appendChild(thumb); | |
| } | |
| // Navigation | |
| function scrollToPage(pageNum) { | |
| const page = document.getElementById(`page-${pageNum}`); | |
| if (page) { | |
| page.scrollIntoView({ behavior: 'smooth', block: 'start' }); | |
| AppState.currentPage = pageNum; | |
| updateThumbnails(); | |
| updateStatusBar(); | |
| } | |
| } | |
| function nextPage() { | |
| if (AppState.currentPage < AppState.totalPages) { | |
| scrollToPage(AppState.currentPage + 1); | |
| } | |
| } | |
| function prevPage() { | |
| if (AppState.currentPage > 1) { | |
| scrollToPage(AppState.currentPage - 1); | |
| } | |
| } | |
| function updateThumbnails() { | |
| const thumbnails = document.querySelectorAll('.thumbnail'); | |
| thumbnails.forEach((thumb, index) => { | |
| if (index + 1 === AppState.currentPage) { | |
| thumb.classList.add('active'); | |
| } else { | |
| thumb.classList.remove('active'); | |
| } | |
| }); | |
| } | |
| // Zoom Controls | |
| function zoomIn() { | |
| AppState.zoom = Math.min(AppState.zoom + 0.25, 3.0); | |
| refreshZoom(); | |
| } | |
| function zoomOut() { | |
| AppState.zoom = Math.max(AppState.zoom - 0.25, 0.25); | |
| refreshZoom(); | |
| } | |
| function resetZoom() { | |
| AppState.zoom = 1.0; | |
| refreshZoom(); | |
| } | |
| function refreshZoom() { | |
| const pages = document.querySelectorAll('.pdf-page'); | |
| pages.forEach(page => { | |
| page.style.transform = `scale(${AppState.zoom})`; | |
| page.style.transformOrigin = 'top center'; | |
| }); | |
| updateStatusBar(); | |
| } | |
| // Rotation | |
| function rotateClockwise() { | |
| AppState.rotation = (AppState.rotation + 90) % 360; | |
| renderAllPages(); | |
| } | |
| function rotateCounterClockwise() { | |
| AppState.rotation = (AppState.rotation - 90) % 360; | |
| if (AppState.rotation < 0) AppState.rotation += 360; | |
| renderAllPages(); | |
| } | |
| // Tools | |
| function setTool(toolName) { | |
| AppState.tool = toolName; | |
| // Update UI | |
| document.querySelectorAll('.tool-btn').forEach(btn => { | |
| btn.classList.remove('tool-active'); | |
| }); | |
| const activeBtn = document.querySelector(`[data-tool="${toolName}"]`); | |
| if (activeBtn) { | |
| activeBtn.classList.add('tool-active'); | |
| } | |
| // Update cursor | |
| const canvas = document.getElementById('pages-container'); | |
| if (canvas) { | |
| switch(toolName) { | |
| case 'text': | |
| canvas.style.cursor = 'text'; | |
| break; | |
| case 'draw': | |
| canvas.style.cursor = 'crosshair'; | |
| break; | |
| case 'highlight': | |
| canvas.style.cursor = 'text'; | |
| break; | |
| default: | |
| canvas.style.cursor = 'default'; | |
| } | |
| } | |
| } | |
| // Text Addition | |
| function showTextModal() { | |
| document.getElementById('text-modal').classList.remove('hidden'); | |
| document.getElementById('text-content').focus(); | |
| } | |
| function addTextToPDF() { | |
| const text = document.getElementById('text-content').value; | |
| if (text.trim()) { | |
| // In a full implementation, this would add text to the PDF layer | |
| // For now, we'll add an overlay | |
| addTextOverlay(text); | |
| closeModal('text-modal'); | |
| document.getElementById('text-content').value = ''; | |
| } | |
| } | |
| function addTextOverlay(text) { | |
| const currentPageDiv = document.getElementById(`page-${AppState.currentPage}`); | |
| if (!currentPageDiv) return; | |
| const overlay = document.createElement('div'); | |
| overlay.className = 'absolute bg-white/90 dark:bg-gray-800/90 p-2 rounded border border-primary-500 shadow-lg cursor-move'; | |
| overlay.style.left = '50px'; | |
| overlay.style.top = '50px'; | |
| overlay.style.minWidth = '100px'; | |
| overlay.style.zIndex = '1000'; | |
| overlay.contentEditable = true; | |
| overlay.textContent = text; | |
| // Make draggable | |
| let isDragging = false; | |
| let currentX; | |
| let currentY; | |
| let initialX; | |
| let initialY; | |
| let xOffset = 0; | |
| let yOffset = 0; | |
| overlay.addEventListener('mousedown', dragStart); | |
| function dragStart(e) { | |
| if (e.target === overlay) { | |
| initialX = e.clientX - xOffset; | |
| initialY = e.clientY - yOffset; | |
| isDragging = true; | |
| } | |
| } | |
| document.addEventListener('mousemove', dragMove); | |
| document.addEventListener('mouseup', dragEnd); | |
| function dragMove(e) { | |
| if (isDragging) { | |
| e.preventDefault(); | |
| currentX = e.clientX - initialX; | |
| currentY = e.clientY - initialY; | |
| xOffset = currentX; | |
| yOffset = currentY; | |
| overlay.style.transform = `translate(${currentX}px, ${currentY}px)`; | |
| } | |
| } | |
| function dragEnd() { | |
| initialX = currentX; | |
| initialY = currentY; | |
| isDragging = false; | |
| } | |
| currentPageDiv.appendChild(overlay); | |
| overlay.focus(); | |
| } | |
| // Export/PDF Creation | |
| async function showExportModal() { | |
| document.getElementById('export-modal').classList.remove('hidden'); | |
| document.getElementById('export-filename').value = AppState.filename || 'edited-document.pdf'; | |
| } | |
| async function exportPDF() { | |
| try { | |
| const filename = document.getElementById('export-filename').value || 'document.pdf'; | |
| // Create a new PDF document | |
| const { PDFDocument } = PDFLib; | |
| const newPdfDoc = await PDFDocument.create(); | |
| // Copy pages from existing PDF if available | |
| if (AppState.pdfDoc) { | |
| const existingPdfBytes = await fetch(AppState.pdfDoc._pdfInfo.url).then(res => res.arrayBuffer()).catch(() => null); | |
| if (existingPdfBytes) { | |
| const existingPdf = await PDFDocument.load(existingPdfBytes); | |
| const pages = await newPdfDoc.copyPages(existingPdf, existingPdf.getPageIndices()); | |
| pages.forEach(page => newPdfDoc.addPage(page)); | |
| } | |
| } | |
| // If no existing PDF, create blank page | |
| if (newPdfDoc.getPageCount() === 0) { | |
| newPdfDoc.addPage(); | |
| } | |
| const pdfBytes = await newPdfDoc.save(); | |
| const blob = new Blob([pdfBytes], { type: 'application/pdf' }); | |
| saveAs(blob, filename); | |
| closeModal('export-modal'); | |
| } catch (error) { | |
| console.error('Export error:', error); | |
| alert('Error exporting PDF. Please try again.'); | |
| } | |
| } | |
| // Modal Controls | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).classList.add('hidden'); | |
| } | |
| // UI Updates | |
| function updateUI() { | |
| updateStatusBar(); | |
| updateThumbnails(); | |
| } | |
| function updateStatusBar() { | |
| const pageCount = document.getElementById('page-count'); | |
| const currentPage = document.getElementById('current-page-input'); | |
| const zoomLevel = document.getElementById('zoom-level'); | |
| if (pageCount) pageCount.textContent = AppState.totalPages; | |
| if (currentPage) currentPage.value = AppState.currentPage; | |
| if (zoomLevel) zoomLevel.textContent = `${Math.round(AppState.zoom * 100)}%`; | |
| } | |
| function showLoading(show) { | |
| let loader = document.getElementById('global-loader'); | |
| if (!loader && show) { | |
| loader = document.createElement('div'); | |
| loader.id = 'global-loader'; | |
| loader.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] flex items-center justify-center'; | |
| loader.innerHTML = '<div class="spinner"></div>'; | |
| document.body.appendChild(loader); | |
| } else if (loader && !show) { | |
| loader.remove(); | |
| } | |
| } | |
| // Keyboard Shortcuts | |
| function setupKeyboardShortcuts() { | |
| document.addEventListener('keydown', (e) => { | |
| // Only if not in input | |
| if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return; | |
| if (e.ctrlKey || e.metaKey) { | |
| switch(e.key) { | |
| case 'o': | |
| e.preventDefault(); | |
| openFileDialog(); | |
| break; | |
| case 's': | |
| e.preventDefault(); | |
| showExportModal(); | |
| break; | |
| case '+': | |
| case '=': | |
| e.preventDefault(); | |
| zoomIn(); | |
| break; | |
| case '-': | |
| e.preventDefault(); | |
| zoomOut(); | |
| break; | |
| case '0': | |
| e.preventDefault(); | |
| resetZoom(); | |
| break; | |
| } | |
| } else { | |
| switch(e.key) { | |
| case 'ArrowRight': | |
| case 'ArrowDown': | |
| nextPage(); | |
| break; | |
| case 'ArrowLeft': | |
| case 'ArrowUp': | |
| prevPage(); | |
| break; | |
| case 't': | |
| setTool('text'); | |
| break; | |
| case 's': | |
| setTool('select'); | |
| break; | |
| case 'h': | |
| setTool('highlight'); | |
| break; | |
| } | |
| } | |
| }); | |
| } | |
| // Theme Toggle | |
| function toggleTheme() { | |
| AppState.darkMode = !AppState.darkMode; | |
| const html = document.documentElement; | |
| if (AppState.darkMode) { | |
| html.classList.add('dark'); | |
| html.classList.remove('light'); | |
| } else { | |
| html.classList.remove('dark'); | |
| html.classList.add('light'); | |
| } | |
| localStorage.setItem('theme', AppState.darkMode ? 'dark' : 'light'); | |
| } | |
| // Initialize theme from localStorage | |
| if (localStorage.getItem('theme') === 'dark' || | |
| (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) { | |
| AppState.darkMode = true; | |
| document.documentElement.classList.add('dark'); | |
| } | |
| // Sidebar Toggle | |
| function toggleSidebar() { | |
| const sidebar = document.querySelector('sidebar-component'); | |
| if (sidebar) { | |
| sidebar.classList.toggle('hidden'); | |
| } | |
| } | |
| // Properties Panel Toggle | |
| function toggleProperties() { | |
| const panel = document.querySelector('properties-panel'); | |
| if (panel) { | |
| panel.classList.toggle('hidden'); | |
| panel.classList.toggle('lg:block'); | |
| } | |
| } |