Made sort and extract pages functions conform to the new design pattern. Standardised naming of a few variables

This commit is contained in:
Saud Fatayerji
2023-11-17 00:32:09 +03:00
parent 53bf6ef4bc
commit 544a080db4
15 changed files with 312 additions and 285 deletions

View File

@@ -0,0 +1,21 @@
import { PdfFile, RepresentationType } from '../../wrappers/PdfFile.js';
import { PDFDocument } from 'pdf-lib';
export async function getPages(file: PdfFile, pageIndexes: number[]): Promise<PdfFile> {
const pdfLibDocument = await file.pdfLibDocument;
const subDocument = await PDFDocument.create();
// Check that array max number is not larger pdf pages number
if(Math.max(...pageIndexes) >= pdfLibDocument.getPageCount()) {
throw new Error(`The PDF document only has ${pdfLibDocument.getPageCount()} pages and you tried to extract page ${Math.max(...pageIndexes)}`);
}
const copiedPages = await subDocument.copyPages(pdfLibDocument, pageIndexes);
for (let i = 0; i < copiedPages.length; i++) {
subDocument.addPage(copiedPages[i]);
}
return new PdfFile(file.originalFilename, subDocument, RepresentationType.PDFLibDocument, file.filename);
}

View File

@@ -0,0 +1,121 @@
/**
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns A reversed list of page indexes.
*/
function reverseSort(pages: number|number[]): number[] {
const indexes = Array.isArray(pages) ? pages : [...Array(pages).keys()];
return indexes.reverse();
}
/**
* Sorts page indexes as if all fronts were scanned then all backs in reverse (1, n, 2, n-1, ...).
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns A duplex-sorted list of page indexes.
*/
function duplexSort(pages: number|number[]): number[] {
const indexes = Array.isArray(pages) ? pages : [...Array(pages).keys()];
// Translated to JS from the original Java function
const newPageOrder: number[] = [];
const half = Math.floor((indexes.length + 1) / 2); // This ensures proper behavior with odd numbers of pages
for (let i = 1; i <= half; i++) {
newPageOrder.push(indexes[i - 1]);
if (i <= indexes.length - half) {
// Avoid going out of bounds
newPageOrder.push(indexes[indexes.length - i]);
}
}
return newPageOrder;
}
/**
* Arranges pages for booklet printing (last, first, second, second last, ...).
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns A booklet-sorted list of page indexes.
*/
function bookletSort(totalPages: number): number[] {
const newPageOrder: number[] = [];
for (let i = 0; i < totalPages / 2; i++) {
newPageOrder.push(i);
newPageOrder.push(totalPages - i - 1);
}
return newPageOrder;
}
/**
* TODO: find out what this does
* @param pages
* @returns
*/
function sideStitchBooklet(totalPages: number): number[] {
const newPageOrder: number[] = [];
for (let i = 0; i < (totalPages + 3) / 4; i++) {
const begin = i * 4;
newPageOrder.push(Math.min(begin + 3, totalPages - 1));
newPageOrder.push(Math.min(begin, totalPages - 1));
newPageOrder.push(Math.min(begin + 1, totalPages - 1));
newPageOrder.push(Math.min(begin + 2, totalPages - 1));
}
return newPageOrder;
}
/**
* Splits and arranges pages into odd and even numbered pages.
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns An odd-even split list of page indexes.
*/
function oddEvenSplit(totalPages: number): number[] {
const newPageOrder: number[] = [];
for (let i = 1; i <= totalPages; i += 2) {
newPageOrder.push(i - 1);
}
for (let i = 2; i <= totalPages; i += 2) {
newPageOrder.push(i - 1);
}
return newPageOrder;
}
/**
* Removes the first page from the list of index selections.
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns The list of page indexes, without the first page.
*/
function removeFirst(totalPages: number): number[] {
return [...Array(totalPages-1).keys()].map(i => i+1);
}
/**
* Removes the last page from the list of index selections.
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns The list of page indexes, without the last page.
*/
function removeLast(totalPages: number): number[] {
return [...Array(totalPages-1).keys()];
}
/**
* Removes the first and last pages from the list of index selections.
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns The list of page indexes, without the first and last pages.
*/
function removeFirstAndLast(totalPages: number): number[] {
return [...Array(totalPages-2).keys()].map(i => i+1);
}
export type SortFunction = (totalPages: number) => number[];
type Sorts = {
[key: string]: SortFunction;
};
export const sorts: Sorts = Object.freeze({
"REVERSE_ORDER": reverseSort,
"DUPLEX_SORT": duplexSort,
"BOOKLET_SORT": bookletSort,
"SIDE_STITCH_BOOKLET_SORT": sideStitchBooklet,
"ODD_EVEN_SPLIT": oddEvenSplit,
"REMOVE_FIRST": removeFirst,
"REMOVE_LAST": removeLast,
"REMOVE_FIRST_AND_LAST": removeFirstAndLast,
});

View File

@@ -0,0 +1,84 @@
/**
* @param selection An array of page indexes already selected.
* @param pages A list of page indexes, or the number of total pages in the document (which will be converted into a list of page indexes).
* @returns An inverted selection array of page indexes.
*/
function invertSelection(selection: number[], pages: number|number[]): number[] {
const indexes = Array.isArray(pages) ? pages : [...Array(pages).keys()];
const pageIndexesCopy = [...indexes];
return pageIndexesCopy.filter(x => !selection.includes(x));
}
/**
* Parse the page selector string used in the 'PDF Page Organizer'
* @param specification
* @param totalPages
* @returns
*/
function parsePageIndexSpecification(specification: string, totalPages: number): number[] {
// Translated to JS from the original Java function
const pageOrderArr = specification.split(",")
const newPageOrder: number[] = [];
// loop through the page order array
pageOrderArr.forEach(element => {
if (element.toLocaleLowerCase() === "all") {
for (var i = 0; i < totalPages; i++) {
newPageOrder.push(i);
}
// As all pages are already added, no need to check further
return;
}
else if (element.match("\\d*n\\+?-?\\d*|\\d*\\+?n")) {
// Handle page order as a function
var coefficient = 0;
var constant = 0;
var coefficientExists = false;
var constantExists = false;
if (element.includes("n")) {
var parts = element.split("n");
if (!parts[0]) {
coefficient = parseInt(parts[0]);
coefficientExists = true;
}
if (parts.length > 1 && parts[1]) {
constant = parseInt(parts[1]);
constantExists = true;
}
} else if (element.includes("+")) {
constant = parseInt(element.replace("+", ""));
constantExists = true;
}
for (var i = 1; i <= totalPages; i++) {
var pageNum = coefficientExists ? coefficient * i : i;
pageNum += constantExists ? constant : 0;
if (pageNum <= totalPages && pageNum > 0) {
newPageOrder.push(pageNum - 1);
}
}
} else if (element.includes("-")) {
// split the range into start and end page
const range = element.split("-");
const start = parseInt(range[0]);
var end = parseInt(range[1]);
// check if the end page is greater than total pages
if (end > totalPages) {
end = totalPages;
}
// loop through the range of pages
for (var j = start; j <= end; j++) {
// print the current index
newPageOrder.push(j - 1);
}
} else {
// if the element is a single page
newPageOrder.push(parseInt(element) - 1);
}
});
return newPageOrder;
}