Feat: Reverse-pages for mulit-pdf

- Added new state pdfDocs: [ ]
- Made tweaks for new state in fileHandler.ts
This commit is contained in:
divy-11
2025-10-19 18:36:57 +05:30
parent caf23b0ab9
commit 2e2c634b41
5 changed files with 30 additions and 20 deletions

View File

@@ -3,29 +3,35 @@ import { downloadFile } from '../utils/helpers.js';
import { state } from '../state.js';
import { PDFDocument as PDFLibDocument } from 'pdf-lib';
import JSZip from 'jszip';
export async function reversePages() {
if (!state.pdfDoc) {
const pdfDocs = Array.isArray(state.pdfDocs) ? state.pdfDocs : state.pdfDoc ? [state.pdfDoc] : [];
if (!pdfDocs.length) {
showAlert('Error', 'PDF not loaded.');
return;
}
showLoader('Reversing page order...');
try {
const newPdf = await PDFLibDocument.create();
const pageCount = state.pdfDoc.getPageCount();
const reversedIndices = Array.from(
{ length: pageCount },
(_, i) => pageCount - 1 - i
);
const zip = new JSZip();
for (let j = 0; j < pdfDocs.length; j++) {
const pdfDoc = pdfDocs[j];
const newPdf = await PDFLibDocument.create();
const pageCount = pdfDoc.getPageCount();
const reversedIndices = Array.from(
{ length: pageCount },
(_, i) => pageCount - 1 - i
);
const copiedPages = await newPdf.copyPages(state.pdfDoc, reversedIndices);
copiedPages.forEach((page: any) => newPdf.addPage(page));
const copiedPages = await newPdf.copyPages(pdfDoc, reversedIndices);
copiedPages.forEach((page: any) => newPdf.addPage(page));
const newPdfBytes = await newPdf.save();
downloadFile(
new Blob([new Uint8Array(newPdfBytes)], { type: 'application/pdf' }),
'reversed.pdf'
);
const newPdfBytes = await newPdf.save();
const fileName = pdfDocs.length > 1 ? `reversed_${j + 1}.pdf` : 'reversed.pdf';
zip.file(fileName, newPdfBytes);
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'reversed_pdfs.zip');
} catch (e) {
console.error(e);
showAlert('Error', 'Could not reverse the PDF pages.');