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 { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
|
||||
import {
|
||||
downloadFile,
|
||||
formatBytes,
|
||||
readFileAsArrayBuffer,
|
||||
getPDFDocument,
|
||||
getCleanPdfFilename,
|
||||
} from '../utils/helpers.js';
|
||||
import { createIcons, icons } from 'lucide';
|
||||
import JSZip from 'jszip';
|
||||
import * as pdfjsLib from 'pdfjs-dist';
|
||||
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[] = [];
|
||||
|
||||
@@ -23,7 +33,8 @@ const updateUI = () => {
|
||||
|
||||
files.forEach((file) => {
|
||||
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');
|
||||
infoContainer.className = 'flex flex-col overflow-hidden';
|
||||
@@ -39,7 +50,8 @@ const updateUI = () => {
|
||||
infoContainer.append(nameSpan, metaSpan);
|
||||
|
||||
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.onclick = () => {
|
||||
files = [];
|
||||
@@ -50,11 +62,14 @@ const updateUI = () => {
|
||||
fileDisplayArea.appendChild(fileDiv);
|
||||
|
||||
// Fetch page count asynchronously
|
||||
readFileAsArrayBuffer(file).then(buffer => {
|
||||
readFileAsArrayBuffer(file)
|
||||
.then((buffer) => {
|
||||
return getPDFDocument(buffer).promise;
|
||||
}).then(pdf => {
|
||||
})
|
||||
.then((pdf) => {
|
||||
metaSpan.textContent = `${formatBytes(file.size)} • ${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
|
||||
}).catch(e => {
|
||||
})
|
||||
.catch((e) => {
|
||||
console.warn('Error loading PDF page count:', e);
|
||||
metaSpan.textContent = formatBytes(file.size);
|
||||
});
|
||||
@@ -81,45 +96,38 @@ async function convert() {
|
||||
}
|
||||
showLoader('Converting to TIFF...');
|
||||
try {
|
||||
const pdf = await getPDFDocument(
|
||||
await readFileAsArrayBuffer(files[0])
|
||||
).promise;
|
||||
const zip = new JSZip();
|
||||
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
|
||||
.promise;
|
||||
|
||||
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++) {
|
||||
const page = await pdf.getPage(i);
|
||||
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' });
|
||||
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 blob = await renderPage(page, i);
|
||||
if (blob.blobData) {
|
||||
zip.file(`page_${i}.` + blob.ending, blob.blobData);
|
||||
}
|
||||
}
|
||||
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
downloadFile(zipBlob, 'converted_images.zip');
|
||||
showAlert('Success', 'PDF converted to TIFFs successfully!', 'success', () => {
|
||||
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_tiffs.zip');
|
||||
}
|
||||
|
||||
showAlert(
|
||||
'Success',
|
||||
'PDF converted to TIFFs successfully!',
|
||||
'success',
|
||||
() => {
|
||||
resetState();
|
||||
});
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
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', () => {
|
||||
const fileInput = document.getElementById('file-input') as HTMLInputElement;
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
|
||||
@@ -155,7 +155,7 @@
|
||||
<div id="file-display-area" class="mt-4 space-y-2"></div>
|
||||
<div id="options-panel" class="hidden mt-6">
|
||||
<button id="process-btn" class="btn-gradient w-full">
|
||||
Download All as ZIP
|
||||
Download All
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user