Add direct image download to pdf-to-tiff
This commit is contained in:
@@ -1,11 +1,21 @@
|
|||||||
import { showLoader, hideLoader, showAlert } from '../ui.js';
|
import { showLoader, hideLoader, showAlert } from '../ui.js';
|
||||||
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
|
import {
|
||||||
|
downloadFile,
|
||||||
|
formatBytes,
|
||||||
|
readFileAsArrayBuffer,
|
||||||
|
getPDFDocument,
|
||||||
|
getCleanPdfFilename,
|
||||||
|
} from '../utils/helpers.js';
|
||||||
import { createIcons, icons } from 'lucide';
|
import { createIcons, icons } from 'lucide';
|
||||||
import JSZip from 'jszip';
|
import JSZip from 'jszip';
|
||||||
import * as pdfjsLib from 'pdfjs-dist';
|
import * as pdfjsLib from 'pdfjs-dist';
|
||||||
import UTIF from 'utif';
|
import UTIF from 'utif';
|
||||||
|
import { PDFPageProxy } from 'pdfjs-dist';
|
||||||
|
|
||||||
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
|
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
|
||||||
|
'pdfjs-dist/build/pdf.worker.min.mjs',
|
||||||
|
import.meta.url
|
||||||
|
).toString();
|
||||||
|
|
||||||
let files: File[] = [];
|
let files: File[] = [];
|
||||||
|
|
||||||
@@ -23,7 +33,8 @@ const updateUI = () => {
|
|||||||
|
|
||||||
files.forEach((file) => {
|
files.forEach((file) => {
|
||||||
const fileDiv = document.createElement('div');
|
const fileDiv = document.createElement('div');
|
||||||
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
|
fileDiv.className =
|
||||||
|
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
|
||||||
|
|
||||||
const infoContainer = document.createElement('div');
|
const infoContainer = document.createElement('div');
|
||||||
infoContainer.className = 'flex flex-col overflow-hidden';
|
infoContainer.className = 'flex flex-col overflow-hidden';
|
||||||
@@ -39,7 +50,8 @@ const updateUI = () => {
|
|||||||
infoContainer.append(nameSpan, metaSpan);
|
infoContainer.append(nameSpan, metaSpan);
|
||||||
|
|
||||||
const removeBtn = document.createElement('button');
|
const removeBtn = document.createElement('button');
|
||||||
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
|
removeBtn.className =
|
||||||
|
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
|
||||||
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
|
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
|
||||||
removeBtn.onclick = () => {
|
removeBtn.onclick = () => {
|
||||||
files = [];
|
files = [];
|
||||||
@@ -50,11 +62,14 @@ const updateUI = () => {
|
|||||||
fileDisplayArea.appendChild(fileDiv);
|
fileDisplayArea.appendChild(fileDiv);
|
||||||
|
|
||||||
// Fetch page count asynchronously
|
// Fetch page count asynchronously
|
||||||
readFileAsArrayBuffer(file).then(buffer => {
|
readFileAsArrayBuffer(file)
|
||||||
|
.then((buffer) => {
|
||||||
return getPDFDocument(buffer).promise;
|
return getPDFDocument(buffer).promise;
|
||||||
}).then(pdf => {
|
})
|
||||||
|
.then((pdf) => {
|
||||||
metaSpan.textContent = `${formatBytes(file.size)} • ${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
|
metaSpan.textContent = `${formatBytes(file.size)} • ${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
|
||||||
}).catch(e => {
|
})
|
||||||
|
.catch((e) => {
|
||||||
console.warn('Error loading PDF page count:', e);
|
console.warn('Error loading PDF page count:', e);
|
||||||
metaSpan.textContent = formatBytes(file.size);
|
metaSpan.textContent = formatBytes(file.size);
|
||||||
});
|
});
|
||||||
@@ -81,45 +96,38 @@ async function convert() {
|
|||||||
}
|
}
|
||||||
showLoader('Converting to TIFF...');
|
showLoader('Converting to TIFF...');
|
||||||
try {
|
try {
|
||||||
const pdf = await getPDFDocument(
|
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
|
||||||
await readFileAsArrayBuffer(files[0])
|
.promise;
|
||||||
).promise;
|
|
||||||
const zip = new JSZip();
|
|
||||||
|
|
||||||
|
if (pdf.numPages === 1) {
|
||||||
|
const page = await pdf.getPage(1);
|
||||||
|
const blob = await renderPage(page, 1);
|
||||||
|
downloadFile(
|
||||||
|
blob.blobData,
|
||||||
|
getCleanPdfFilename(files[0].name) + '.' + blob.ending
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const zip = new JSZip();
|
||||||
for (let i = 1; i <= pdf.numPages; i++) {
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
const page = await pdf.getPage(i);
|
const page = await pdf.getPage(i);
|
||||||
const viewport = page.getViewport({ scale: 2.0 });
|
const blob = await renderPage(page, i);
|
||||||
const canvas = document.createElement('canvas');
|
if (blob.blobData) {
|
||||||
const context = canvas.getContext('2d');
|
zip.file(`page_${i}.` + blob.ending, blob.blobData);
|
||||||
canvas.height = viewport.height;
|
|
||||||
canvas.width = viewport.width;
|
|
||||||
|
|
||||||
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
|
|
||||||
|
|
||||||
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height);
|
|
||||||
const rgba = imageData.data;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const tiffData = UTIF.encodeImage(new Uint8Array(rgba), canvas.width, canvas.height);
|
|
||||||
const tiffBlob = new Blob([tiffData], { type: 'image/tiff' });
|
|
||||||
zip.file(`page_${i}.tiff`, tiffBlob);
|
|
||||||
} catch (encodeError: any) {
|
|
||||||
console.warn(`TIFF encoding failed for page ${i}, using PNG fallback:`, encodeError);
|
|
||||||
// Fallback to PNG if TIFF encoding fails (e.g., PackBits compression issues)
|
|
||||||
const pngBlob = await new Promise<Blob | null>((resolve) =>
|
|
||||||
canvas.toBlob(resolve, 'image/png')
|
|
||||||
);
|
|
||||||
if (pngBlob) {
|
|
||||||
zip.file(`page_${i}.png`, pngBlob);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||||
downloadFile(zipBlob, 'converted_images.zip');
|
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_tiffs.zip');
|
||||||
showAlert('Success', 'PDF converted to TIFFs successfully!', 'success', () => {
|
}
|
||||||
|
|
||||||
|
showAlert(
|
||||||
|
'Success',
|
||||||
|
'PDF converted to TIFFs successfully!',
|
||||||
|
'success',
|
||||||
|
() => {
|
||||||
resetState();
|
resetState();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
showAlert(
|
showAlert(
|
||||||
@@ -131,6 +139,59 @@ async function convert() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function renderPage(
|
||||||
|
page: PDFPageProxy,
|
||||||
|
pageNumber: number
|
||||||
|
): Promise<{ blobData: Blob | null; ending: string }> {
|
||||||
|
const viewport = page.getViewport({ scale: 2.0 });
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
const context = canvas.getContext('2d');
|
||||||
|
canvas.height = viewport.height;
|
||||||
|
canvas.width = viewport.width;
|
||||||
|
|
||||||
|
await page.render({
|
||||||
|
canvasContext: context!,
|
||||||
|
viewport: viewport,
|
||||||
|
canvas,
|
||||||
|
}).promise;
|
||||||
|
|
||||||
|
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height);
|
||||||
|
const rgba = imageData.data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tiffData = UTIF.encodeImage(
|
||||||
|
new Uint8Array(rgba),
|
||||||
|
canvas.width,
|
||||||
|
canvas.height
|
||||||
|
);
|
||||||
|
const tiffBlob = new Blob([tiffData], { type: 'image/tiff' });
|
||||||
|
return {
|
||||||
|
blobData: tiffBlob,
|
||||||
|
ending: 'tiff',
|
||||||
|
};
|
||||||
|
} catch (encodeError: any) {
|
||||||
|
console.warn(
|
||||||
|
`TIFF encoding failed for page ${pageNumber}, using PNG fallback:`,
|
||||||
|
encodeError
|
||||||
|
);
|
||||||
|
// Fallback to PNG if TIFF encoding fails (e.g., PackBits compression issues)
|
||||||
|
const pngBlob = await new Promise<Blob | null>((resolve) =>
|
||||||
|
canvas.toBlob(resolve, 'image/png')
|
||||||
|
);
|
||||||
|
if (pngBlob) {
|
||||||
|
return {
|
||||||
|
blobData: pngBlob,
|
||||||
|
ending: 'png',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
blobData: null,
|
||||||
|
ending: 'tiff',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
const fileInput = document.getElementById('file-input') as HTMLInputElement;
|
const fileInput = document.getElementById('file-input') as HTMLInputElement;
|
||||||
const dropZone = document.getElementById('drop-zone');
|
const dropZone = document.getElementById('drop-zone');
|
||||||
|
|||||||
@@ -155,7 +155,7 @@
|
|||||||
<div id="file-display-area" class="mt-4 space-y-2"></div>
|
<div id="file-display-area" class="mt-4 space-y-2"></div>
|
||||||
<div id="options-panel" class="hidden mt-6">
|
<div id="options-panel" class="hidden mt-6">
|
||||||
<button id="process-btn" class="btn-gradient w-full">
|
<button id="process-btn" class="btn-gradient w-full">
|
||||||
Download All as ZIP
|
Download All
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user