refactor: apply eslint

This commit is contained in:
sbplat
2024-01-04 20:17:54 -05:00
parent 5fd505d4f4
commit 9c1588d150
53 changed files with 647 additions and 636 deletions

View File

@@ -1,3 +1,3 @@
declare module '#pdfcpu' {
declare module "#pdfcpu" {
export function oneToOne(wasmArray: string[], snapshot: Uint8Array): Promise<Uint8Array>;
}

View File

@@ -1,10 +1,10 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { Sorts } from './common/pageIndexesSorting.js';
import { getPages } from './common/getPagesByIndex.js';
import { parsePageIndexSpecification } from './common/pageIndexesUtils.js';
import { PdfFile } from "../wrappers/PdfFile.js";
import { Sorts } from "./common/pageIndexesSorting.js";
import { getPages } from "./common/getPagesByIndex.js";
import { parsePageIndexSpecification } from "./common/pageIndexesUtils.js";
export type ArrangePagesParamsType = {
export interface ArrangePagesParamsType {
file: PdfFile;
arrangementConfig: string; // a member of Sorts, or a page index specification
}
@@ -22,6 +22,6 @@ export async function arrangePages(params: ArrangePagesParamsType) {
}
const newFile = await getPages(file, sortIndexes);
newFile.filename += "arrangedPages"
newFile.filename += "arrangedPages";
return newFile;
}

View File

@@ -1,7 +1,7 @@
import { PdfFile } from '../../wrappers/PdfFile';
import { PdfFile } from "../../wrappers/PdfFile";
import { PDFPageProxy } from "pdfjs-dist/types/src/display/api.js";
import { Image, ImageKind } from 'image-js';
import { Image, ImageKind } from "image-js";
import { getImagesOnPage, PDFJSImage } from "./getImagesOnPage.js";
@@ -45,8 +45,8 @@ async function areImagesBlank(page: PDFPageProxy, threshold: number): Promise<bo
// TODO: Fix this function
async function isImageBlank(image: PDFJSImage, threshold: number): Promise<boolean> {
var img = new Image(image.width, image.height, image.data, { kind: "RGB" as ImageKind }); // TODO: Maybe respect image.kind and convert accordingly, needs to be tested with a pdf with alpha-image
var grey = img.grey();
var mean = grey.getMean();
const img = new Image(image.width, image.height, image.data, { kind: "RGB" as ImageKind }); // TODO: Maybe respect image.kind and convert accordingly, needs to be tested with a pdf with alpha-image
const grey = img.grey();
const mean = grey.getMean();
return mean[0] <= threshold;
}

View File

@@ -1,7 +1,7 @@
import jsQR from "jsqr";
import { PdfFile } from '../../wrappers/PdfFile.js';
import { PdfFile } from "../../wrappers/PdfFile.js";
import { getImagesOnPage, PDFJSImage } from "./getImagesOnPage.js";
export async function detectQRCodePages(file: PdfFile) {
@@ -24,7 +24,7 @@ export async function detectQRCodePages(file: PdfFile) {
}
}
if(pagesWithQR.length == 0) {
console.warn("Could not find any QR Codes in the provided PDF.")
console.warn("Could not find any QR Codes in the provided PDF.");
}
return pagesWithQR;
}

View File

@@ -1,20 +1,20 @@
import { PDFPageProxy } from "pdfjs-dist/types/src/display/api.js";
import * as PDFJS from 'pdfjs-dist';
import * as PDFJS from "pdfjs-dist";
export type PDFJSImage = {
export interface PDFJSImage {
width: number;
height: number;
interpolate?: any;
kind: number; // TODO: Document what this is, maybe hasAlpha?
data: Uint8ClampedArray;
};
}
export async function getImagesOnPage(page: PDFPageProxy): Promise<PDFJSImage[]> {
const ops = await page.getOperatorList();
const images: PDFJSImage[] = [];
for (var j=0; j < ops.fnArray.length; j++) {
for (let j=0; j < ops.fnArray.length; j++) {
if (ops.fnArray[j] == PDFJS.OPS.paintImageXObject) {
const image = page.objs.get(ops.argsArray[j][0]) as PDFJSImage;
images.push(image);

View File

@@ -1,6 +1,6 @@
import { PdfFile, RepresentationType } from '../../wrappers/PdfFile.js';
import { PDFDocument } from 'pdf-lib';
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;

View File

@@ -55,11 +55,11 @@ function bookletSort(totalPages: number): number[] {
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));
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;
}
@@ -72,10 +72,10 @@ function sideStitchBooklet(totalPages: number): number[] {
function oddEvenSplit(totalPages: number): number[] {
const newPageOrder: number[] = [];
for (let i = 1; i <= totalPages; i += 2) {
newPageOrder.push(i - 1);
newPageOrder.push(i - 1);
}
for (let i = 2; i <= totalPages; i += 2) {
newPageOrder.push(i - 1);
newPageOrder.push(i - 1);
}
return newPageOrder;
}
@@ -108,9 +108,7 @@ function removeFirstAndLast(totalPages: number): number[] {
}
export type SortFunction = (totalPages: number) => number[];
type Sorts = {
[key: string]: SortFunction;
};
type Sorts = Record<string, SortFunction>;
export const Sorts: Sorts = Object.freeze({
"REVERSE_ORDER": reverseSort,
"DUPLEX_SORT": duplexSort,

View File

@@ -18,7 +18,7 @@ export function invertSelection(selection: number[], pages: number|number[]): nu
*/
export function parsePageIndexSpecification(specification: string, totalPages: number): number[] {
// Translated to JS from the original Java function
const pageOrderArr = specification.split(",")
const pageOrderArr = specification.split(",");
const newPageOrder: number[] = [];
// loop through the page order array
@@ -32,13 +32,13 @@ export function parsePageIndexSpecification(specification: string, totalPages: n
}
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;
let coefficient = 0;
let constant = 0;
let coefficientExists = false;
let constantExists = false;
if (element.includes("n")) {
var parts = element.split("n");
const parts = element.split("n");
if (!parts[0]) {
coefficient = parseInt(parts[0]);
coefficientExists = true;
@@ -53,7 +53,7 @@ export function parsePageIndexSpecification(specification: string, totalPages: n
}
for (var i = 1; i <= totalPages; i++) {
var pageNum = coefficientExists ? coefficient * i : i;
let pageNum = coefficientExists ? coefficient * i : i;
pageNum += constantExists ? constant : 0;
if (pageNum <= totalPages && pageNum > 0) {
@@ -64,13 +64,13 @@ export function parsePageIndexSpecification(specification: string, totalPages: n
// split the range into start and end page
const range = element.split("-");
const start = parseInt(range[0]);
var end = parseInt(range[1]);
let 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++) {
for (let j = start; j <= end; j++) {
// print the current index
newPageOrder.push(j - 1);
}

View File

@@ -1,46 +1,46 @@
import { PdfFile } from '../../wrappers/PdfFile';
import { PdfFile } from "../../wrappers/PdfFile";
export async function sortPdfArray(
files: PdfFile[],
sortType: "orderProvided"|"byFileName"|"byDateModified"|"byDateCreated"|"byPDFTitle" = "orderProvided"
): Promise<PdfFile[]> {
files: PdfFile[],
sortType: "orderProvided"|"byFileName"|"byDateModified"|"byDateCreated"|"byPDFTitle" = "orderProvided"
): Promise<PdfFile[]> {
const docCache = await PdfFile.cacheAsPdfLibDocuments(files);
switch(sortType) {
case "byFileName":
files.sort((a, b) => {
if (!a || !b) return 0;
const ad = a.filename, bd = b.filename;
if (!ad || !bd) return 0;
return ad.localeCompare(bd);
});
break;
case "byDateModified":
files.sort((a, b) => {
const ad = docCache.get(a)?.getModificationDate()?.getTime();
const bd = docCache.get(b)?.getModificationDate()?.getTime();
if (!ad || !bd) return 0;
return ad > bd ? 1 : -1
});
break;
case "byDateCreated":
files.sort((a, b) => {
const ad = docCache.get(a)?.getCreationDate()?.getTime();
const bd = docCache.get(b)?.getCreationDate()?.getTime();
if (!ad || !bd) return 0;
return ad > bd ? 1 : -1
});
break;
case "byPDFTitle":
files.sort((a, b) => {
const ad = docCache.get(a)?.getTitle();
const bd = docCache.get(b)?.getTitle();
if (!ad || !bd) return 0;
return ad.localeCompare(bd);
});
break;
case "byFileName":
files.sort((a, b) => {
if (!a || !b) return 0;
const ad = a.filename, bd = b.filename;
if (!ad || !bd) return 0;
return ad.localeCompare(bd);
});
break;
case "byDateModified":
files.sort((a, b) => {
const ad = docCache.get(a).getModificationDate().getTime();
const bd = docCache.get(b).getModificationDate().getTime();
if (!ad || !bd) return 0;
return ad > bd ? 1 : -1;
});
break;
case "byDateCreated":
files.sort((a, b) => {
const ad = docCache.get(a).getCreationDate().getTime();
const bd = docCache.get(b).getCreationDate().getTime();
if (!ad || !bd) return 0;
return ad > bd ? 1 : -1;
});
break;
case "byPDFTitle":
files.sort((a, b) => {
const ad = docCache.get(a).getTitle();
const bd = docCache.get(b).getTitle();
if (!ad || !bd) return 0;
return ad.localeCompare(bd);
});
break;
}
return files;

View File

@@ -1,5 +1,5 @@
import { PdfFile } from '../../wrappers/PdfFile.js';
import { PdfFile } from "../../wrappers/PdfFile.js";
import { getPages } from "./getPagesByIndex";
export async function splitPagesByIndex(file: PdfFile, splitAfterPageIndexes: number[]): Promise<PdfFile[]> {
@@ -22,4 +22,4 @@ export async function splitPagesByIndex(file: PdfFile, splitAfterPageIndexes: nu
pagesArray = [];
return subDocuments;
};
}

View File

@@ -1,9 +1,9 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { getPages } from './common/getPagesByIndex.js';
import { parsePageIndexSpecification } from './common/pageIndexesUtils'
import { PdfFile } from "../wrappers/PdfFile.js";
import { getPages } from "./common/getPagesByIndex.js";
import { parsePageIndexSpecification } from "./common/pageIndexesUtils";
export type ExtractPagesParamsType = {
export interface ExtractPagesParamsType {
file: PdfFile;
pageIndexes: string | number[];
}
@@ -11,13 +11,13 @@ export async function extractPages(params: ExtractPagesParamsType): Promise<PdfF
const { file, pageIndexes } = params;
const pdfLibDocument = await file.pdfLibDocument;
var indexes = pageIndexes;
let indexes = pageIndexes;
if (!Array.isArray(indexes)) {
indexes = parsePageIndexSpecification(indexes, pdfLibDocument.getPageCount());
}
const newFile = await getPages(file, indexes);
newFile.filename += "_extractedPages"
newFile.filename += "_extractedPages";
return newFile;
}

View File

@@ -7,20 +7,20 @@ import * as pdfcpuWrapper from "#pdfcpu"; // This is updated by tsconfig.json/pa
import Joi from "joi";
import { JoiPDFFileSchema } from "../wrappers/PdfFileJoi";
import i18next from 'i18next';
i18next.loadNamespaces('impose', (err, t) => { if (err) throw err; });
import i18next from "i18next";
i18next.loadNamespaces("impose", (err, t) => { if (err) throw err; });
export class Impose extends Operator {
static type: string = "impose";
static type = "impose";
/**
* Validation & Localisation
*/
protected static inputSchema = JoiPDFFileSchema.label(i18next.t('inputs.pdffile.name')).description(i18next.t('inputs.pdffile.description'));
protected static inputSchema = JoiPDFFileSchema.label(i18next.t("inputs.pdffile.name")).description(i18next.t("inputs.pdffile.description"));
protected static valueSchema = Joi.object({
nup: Joi.number().integer().valid(2, 3, 4, 8, 9, 12, 16).required()
.label(i18next.t('values.nup.friendlyName', { ns: 'impose' })).description(i18next.t('values.nup.description', { ns: 'impose' }))
.label(i18next.t("values.nup.friendlyName", { ns: "impose" })).description(i18next.t("values.nup.description", { ns: "impose" }))
.example("3").example("4"),
format: Joi.string().valid(...[
// ISO 216:1975 A
@@ -62,16 +62,16 @@ export class Impose extends Operator {
"JIS-B7", "JIS-B8", "JIS-B9", "JIS-B10", "JIS-B11", "JIS-B12",
"Shirokuban4", "Shirokuban5", "Shirokuban6", "Kiku4", "Kiku5", "AB", "B40", "Shikisen"
].flatMap(size => [size, size + "P", size + "L"])).required()
.label(i18next.t('values.format.friendlyName', { ns: 'impose' })).description(i18next.t('values.format.description', { ns: 'impose' }))
.label(i18next.t("values.format.friendlyName", { ns: "impose" })).description(i18next.t("values.format.description", { ns: "impose" }))
.example("A4").example("A3L")
});
protected static outputSchema = JoiPDFFileSchema.label(i18next.t('outputs.pdffile.name')).description(i18next.t('outputs.pdffile.description'));
protected static outputSchema = JoiPDFFileSchema.label(i18next.t("outputs.pdffile.name")).description(i18next.t("outputs.pdffile.description"));
static schema = Joi.object({
input: Impose.inputSchema,
values: Impose.valueSchema.required(),
output: Impose.outputSchema
}).label(i18next.t('friendlyName', { ns: 'impose' })).description(i18next.t('description', { ns: 'impose' }));
}).label(i18next.t("friendlyName", { ns: "impose" })).description(i18next.t("description", { ns: "impose" }));
/**
@@ -89,7 +89,7 @@ export class Impose extends Operator {
"nup",
"-c",
"disable",
'f:' + this.actionValues.format,
"f:" + this.actionValues.format,
"/output.pdf",
String(this.actionValues.nup),
"input.pdf",
@@ -104,10 +104,10 @@ export class Impose extends Operator {
input.filename + "_imposed"
);
progressCallback({ curFileProgress: 1, operationProgress: index/max })
progressCallback({ curFileProgress: 1, operationProgress: index/max });
console.log("ImposeResult: ", result);
return result;
})
});
}
}

View File

@@ -45,7 +45,7 @@ export async function nToOne <I, O>(inputs: I[], callback: (input: I[]) => Promi
/** This function should be used if the Operation takes one file as input and may output multiple files */
export async function oneToN <I, O>(inputs: I[], callback: (input: I, index: number, max: number) => Promise<O[]>): Promise<O[]> {
let output: O[] = []
let output: O[] = [];
for (let i = 0; i < inputs.length; i++) {
output = output.concat(await callback(inputs[i], i, inputs.length));
}
@@ -55,6 +55,6 @@ export async function oneToN <I, O>(inputs: I[], callback: (input: I, index: num
/** This function should be used if the Operation takes one file as input and outputs only one file */
export async function oneToOne <I, O>(inputs: I[], callback: (input: I, index: number, max: number) => Promise<O>): Promise<O[]> {
return oneToN(inputs, async (input, index, max) => {
return [await callback(input, index, max)]
return [await callback(input, index, max)];
});
}

View File

@@ -1,8 +1,8 @@
import { PDFDocument } from 'pdf-lib';
import { PdfFile, RepresentationType } from '../wrappers/PdfFile';
import { PDFDocument } from "pdf-lib";
import { PdfFile, RepresentationType } from "../wrappers/PdfFile";
export type MergeParamsType = {
export interface MergeParamsType {
files: PdfFile[];
}
@@ -15,6 +15,6 @@ export async function mergePDFs(params: MergeParamsType): Promise<PdfFile> {
copiedPages.forEach((page) => mergedPdf.addPage(page));
}
const newName = "("+params.files.map(input => input.filename).join("_and_") + ")_merged"
const newName = "("+params.files.map(input => input.filename).join("_and_") + ")_merged";
return new PdfFile("mergedPDF", mergedPdf, RepresentationType.PDFLibDocument, newName);
};
}

View File

@@ -1,10 +1,10 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { detectEmptyPages } from './common/detectEmptyPages.js';
import { getPages } from './common/getPagesByIndex.js';
import { invertSelection } from './common/pageIndexesUtils.js';
import { PdfFile } from "../wrappers/PdfFile.js";
import { detectEmptyPages } from "./common/detectEmptyPages.js";
import { getPages } from "./common/getPagesByIndex.js";
import { invertSelection } from "./common/pageIndexesUtils.js";
export type RemoveBlankPagesParamsType = {
export interface RemoveBlankPagesParamsType {
file: PdfFile;
whiteThreashold: number;
}
@@ -15,9 +15,9 @@ export async function removeBlankPages(params: RemoveBlankPagesParamsType) {
const emptyPages = await detectEmptyPages(file, whiteThreashold);
console.debug("Empty Pages: ", emptyPages);
const pagesToKeep = invertSelection(emptyPages, pageCount)
const pagesToKeep = invertSelection(emptyPages, pageCount);
const newFile = await getPages(file, pagesToKeep);
newFile.filename += "_removedBlanks"
newFile.filename += "_removedBlanks";
return newFile;
}

View File

@@ -1,9 +1,9 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { getPages } from './common/getPagesByIndex.js';
import { invertSelection, parsePageIndexSpecification } from './common/pageIndexesUtils.js';
import { PdfFile } from "../wrappers/PdfFile.js";
import { getPages } from "./common/getPagesByIndex.js";
import { invertSelection, parsePageIndexSpecification } from "./common/pageIndexesUtils.js";
export type RemovePagesParamsType = {
export interface RemovePagesParamsType {
file: PdfFile;
pageSelector: string;
}
@@ -16,6 +16,6 @@ export async function removePages(params: RemovePagesParamsType) {
const pagesToKeep = invertSelection(pageSelection, pageCount);
const newFile = await getPages(file, pagesToKeep);
newFile.filename += "_removedPages"
newFile.filename += "_removedPages";
return newFile;
}

View File

@@ -1,8 +1,8 @@
import { degrees } from 'pdf-lib';
import { PdfFile, RepresentationType } from '../wrappers/PdfFile';
import { degrees } from "pdf-lib";
import { PdfFile, RepresentationType } from "../wrappers/PdfFile";
export type RotateParamsType = {
export interface RotateParamsType {
file: PdfFile;
rotation: number|number[];
}
@@ -15,19 +15,19 @@ export async function rotatePages(params: RotateParamsType): Promise<PdfFile> {
if (Array.isArray(rotation)) {
if (rotation.length != pages.length) {
throw new Error(`Number of given rotations '${rotation.length}' is not the same as the number of pages '${pages.length}'`)
throw new Error(`Number of given rotations '${rotation.length}' is not the same as the number of pages '${pages.length}'`);
}
for (let i=0; i<rotation.length; i++) {
const oldRotation = pages[i].getRotation().angle
pages[i].setRotation(degrees(oldRotation + rotation[i]))
const oldRotation = pages[i].getRotation().angle;
pages[i].setRotation(degrees(oldRotation + rotation[i]));
}
} else {
pages.forEach(page => {
// Change page size
const oldRotation = page.getRotation().angle
page.setRotation(degrees(oldRotation + rotation))
const oldRotation = page.getRotation().angle;
page.setRotation(degrees(oldRotation + rotation));
});
}
return new PdfFile(file.originalFilename, pdfDoc, RepresentationType.PDFLibDocument, file.filename+"_rotated");
};
}

View File

@@ -1,8 +1,8 @@
import { PDFPage } from 'pdf-lib';
import { PdfFile, RepresentationType } from '../wrappers/PdfFile';
import { PDFPage } from "pdf-lib";
import { PdfFile, RepresentationType } from "../wrappers/PdfFile";
export type ScaleContentParamsType = {
export interface ScaleContentParamsType {
file: PdfFile;
scaleFactor: number|number[];
}
@@ -15,17 +15,17 @@ export async function scaleContent(params: ScaleContentParamsType): Promise<PdfF
if (Array.isArray(scaleFactor)) {
if (scaleFactor.length != pages.length) {
throw new Error(`Number of given scale factors '${scaleFactor.length}' is not the same as the number of pages '${pages.length}'`)
throw new Error(`Number of given scale factors '${scaleFactor.length}' is not the same as the number of pages '${pages.length}'`);
}
for (let i=0; i<scaleFactor.length; i++) {
scalePage(pages[i], scaleFactor[i]);
}
} else {
pages.forEach(page => scalePage(page, scaleFactor));
pages.forEach(page => { scalePage(page, scaleFactor) });
}
return new PdfFile(file.originalFilename, pdfDoc, RepresentationType.PDFLibDocument, file.filename+"_scaledContent");
};
}
function scalePage(page: PDFPage, scaleFactor: number) {
const width = page.getWidth();

View File

@@ -1,24 +1,24 @@
import Joi from 'joi';
import { PDFPage } from 'pdf-lib';
import { PdfFile, RepresentationType, JoiPDFFileSchema } from '../wrappers/PdfFileJoi';
import Joi from "joi";
import { PDFPage } from "pdf-lib";
import { PdfFile, RepresentationType, JoiPDFFileSchema } from "../wrappers/PdfFileJoi";
const whSchema = Joi.string().custom((value, helpers) => {
console.log("value.pageSize", typeof value)
console.log("value.pageSize", typeof value);
try {
const obj = JSON.parse(value);
if (!obj.width && !obj.height) {
return helpers.error('any.required', { message: 'At least one of width/height must be present' });
return helpers.error("any.required", { message: "At least one of width/height must be present" });
}
if (typeof obj.width != 'number' && typeof obj.width != 'undefined') {
return helpers.error('any.invalid', { message: 'Width must be a number if present' });
if (typeof obj.width != "number" && typeof obj.width != "undefined") {
return helpers.error("any.invalid", { message: "Width must be a number if present" });
}
if (typeof obj.height != 'number' && typeof obj.height != 'undefined') {
return helpers.error('any.invalid', { message: 'Height must be a number if present' });
if (typeof obj.height != "number" && typeof obj.height != "undefined") {
return helpers.error("any.invalid", { message: "Height must be a number if present" });
}
return obj;
} catch (error) {
return helpers.error('any.invalid', { message: 'Value must be a valid JSON' });
return helpers.error("any.invalid", { message: "Value must be a valid JSON" });
}
});
@@ -28,7 +28,7 @@ export const ScalePageSchema = Joi.object({
});
export type ScalePageParamsType = {
export interface ScalePageParamsType {
file: PdfFile;
pageSize: { width?:number,height?:number }|{ width?:number,height?:number }[];
}
@@ -41,17 +41,17 @@ export async function scalePage(params: ScalePageParamsType): Promise<PdfFile> {
if (Array.isArray(pageSize)) {
if (pageSize.length != pages.length) {
throw new Error(`Number of given sizes '${pageSize.length}' is not the same as the number of pages '${pages.length}'`)
throw new Error(`Number of given sizes '${pageSize.length}' is not the same as the number of pages '${pages.length}'`);
}
for (let i=0; i<pageSize.length; i++) {
resize(pages[i], pageSize[i]);
}
} else {
pages.forEach(page => resize(page, pageSize));
pages.forEach(page => { resize(page, pageSize) });
}
return new PdfFile(file.originalFilename, pdfDoc, RepresentationType.PDFLibDocument, file.filename+"_scaledPages");
};
}
function resize(page: PDFPage, newSize: {width?:number,height?:number}) {
const calculatedSize = calculateSize(page, newSize);
@@ -74,7 +74,7 @@ function calculateSize(page: PDFPage, newSize: {width?:number,height?:number}):
const ratio = oldSize.height / oldSize.width;
return { width: newSize.width, height: newSize.width * ratio };
}
return { width: newSize.width!, height: newSize.height! };
return { width: newSize.width, height: newSize.height };
}
export const PageSize = Object.freeze({

View File

@@ -1,10 +1,10 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { PdfFile } from "../wrappers/PdfFile.js";
import { splitPagesByIndex } from "./common/splitPagesByIndex.js";
import { detectEmptyPages } from "./common/detectEmptyPages.js";
import { detectQRCodePages } from "./common/detectQRCodePages.js";
export type SplitPageByPresetParamsType = {
export interface SplitPageByPresetParamsType {
file: PdfFile;
type: "BAR_CODE"|"QR_CODE"|"BLANK_PAGE";
whiteThreashold?: number;
@@ -16,22 +16,22 @@ export async function splitPagesByPreset(params: SplitPageByPresetParamsType): P
let splitAtPages: number[];
switch (type) {
case "BAR_CODE":
// TODO: Implement
throw new Error("This split-type has not been implemented yet");
case "BAR_CODE":
// TODO: Implement
throw new Error("This split-type has not been implemented yet");
case "QR_CODE":
splitAtPages = await detectQRCodePages(file);
break;
case "QR_CODE":
splitAtPages = await detectQRCodePages(file);
break;
case "BLANK_PAGE":
if (!whiteThreashold)
throw new Error("White threshold not provided");
splitAtPages = await detectEmptyPages(file, whiteThreashold);
break;
case "BLANK_PAGE":
if (!whiteThreashold)
throw new Error("White threshold not provided");
splitAtPages = await detectEmptyPages(file, whiteThreashold);
break;
default:
throw new Error("An invalid split-type was provided.");
default:
throw new Error("An invalid split-type was provided.");
}
console.debug("Split At Pages: ", splitAtPages);
@@ -41,4 +41,4 @@ export async function splitPagesByPreset(params: SplitPageByPresetParamsType): P
newFiles[i].filename += "_split-"+i;
}
return newFiles;
};
}

View File

@@ -1,9 +1,9 @@
import { PdfFile } from '../wrappers/PdfFile.js';
import { parsePageIndexSpecification } from './common/pageIndexesUtils'
import { splitPagesByIndex } from './common/splitPagesByIndex.js';
import { PdfFile } from "../wrappers/PdfFile.js";
import { parsePageIndexSpecification } from "./common/pageIndexesUtils";
import { splitPagesByIndex } from "./common/splitPagesByIndex.js";
export type SplitPdfByIndexParamsType = {
export interface SplitPdfByIndexParamsType {
file: PdfFile;
pageIndexes: string | number[];
}
@@ -11,7 +11,7 @@ export async function splitPdfByIndex(params: SplitPdfByIndexParamsType): Promis
const { file, pageIndexes } = params;
const pdfLibDocument = await file.pdfLibDocument;
var indexes = pageIndexes;
let indexes = pageIndexes;
if (!Array.isArray(indexes)) {
indexes = parsePageIndexSpecification(indexes, pdfLibDocument.getPageCount());

View File

@@ -1,7 +1,7 @@
import { PdfFile } from '../wrappers/PdfFile';
import { PdfFile } from "../wrappers/PdfFile";
export type UpdateMetadataParams = {
export interface UpdateMetadataParams {
file: PdfFile,
deleteAll?: boolean, // Delete all metadata if set to true
author?: string, // The author of the document
@@ -21,34 +21,34 @@ export async function updateMetadata(params: UpdateMetadataParams): Promise<PdfF
if (params.deleteAll) {
pdfDoc.setAuthor("");
pdfDoc.setCreationDate(new Date(0))
pdfDoc.setCreator("")
pdfDoc.setKeywords([])
pdfDoc.setModificationDate(new Date(0))
pdfDoc.setProducer("")
pdfDoc.setSubject("")
pdfDoc.setTitle("")
pdfDoc.setCreationDate(new Date(0));
pdfDoc.setCreator("");
pdfDoc.setKeywords([]);
pdfDoc.setModificationDate(new Date(0));
pdfDoc.setProducer("");
pdfDoc.setSubject("");
pdfDoc.setTitle("");
}
if(params.author)
pdfDoc.setAuthor(params.author);
if(params.creationDate)
pdfDoc.setCreationDate(params.creationDate)
pdfDoc.setCreationDate(params.creationDate);
if(params.creator)
pdfDoc.setCreator(params.creator)
pdfDoc.setCreator(params.creator);
if(params.keywords)
pdfDoc.setKeywords(params.keywords.split(","))
pdfDoc.setKeywords(params.keywords.split(","));
if(params.modificationDate)
pdfDoc.setModificationDate(params.modificationDate)
pdfDoc.setModificationDate(params.modificationDate);
if(params.producer)
pdfDoc.setProducer(params.producer)
pdfDoc.setProducer(params.producer);
if(params.subject)
pdfDoc.setSubject(params.subject)
pdfDoc.setSubject(params.subject);
if(params.title)
pdfDoc.setTitle(params.title)
pdfDoc.setTitle(params.title);
// TODO add trapped and custom metadata. May need another library
params.file.filename += "_updatedMetadata";
return params.file;
};
}

View File

@@ -1,13 +1,13 @@
import i18next from "i18next"
import resourcesToBackend from 'i18next-resources-to-backend';
import i18next from "i18next";
import resourcesToBackend from "i18next-resources-to-backend";
i18next
.use(resourcesToBackend((language, namespace) => import(`./${namespace}/${language}.json`)))
.init({
// debug: true,
ns: ['common'], // Preload this namespace, no need to add the others
defaultNS: 'common',
fallbackLng: 'en',
ns: ["common"], // Preload this namespace, no need to add the others
defaultNS: "common",
fallbackLng: "en",
interpolation: {
escapeValue: false,
}

View File

@@ -4,7 +4,7 @@ import { Operator } from "../functions";
import { Impose } from "../functions/impose";
export const Operators = {
Impose: Impose
}
};
// TODO: Convert this to a map or similar
export function getOperatorByName(name: string): typeof Operator | undefined {
@@ -13,7 +13,7 @@ export function getOperatorByName(name: string): typeof Operator | undefined {
// Loop over each default export
Object.entries(Operators).some(([className, exportedClass]) => {
// Check if the exported item is a class
if (typeof exportedClass === 'function' && exportedClass.prototype) {
if (typeof exportedClass === "function" && exportedClass.prototype) {
if (exportedClass.type === name) {
foundClass = exportedClass;
return true; // Stop the iteration
@@ -28,4 +28,4 @@ export function getOperatorByName(name: string): typeof Operator | undefined {
export function listOperatorNames(): string[] {
// TODO: Implement this
return [];
}
}

View File

@@ -4,8 +4,8 @@ import { PdfFile } from "../wrappers/PdfFile";
export function organizeWaitOperations(actions: Action[]) {
// Initialize an object to store the counts and associated "done" operations
const waitCounts: {[key: string]: number} = {};
const doneOperations: {[key: string]: Action} = {};
const waitCounts: Record<string, number> = {};
const doneOperations: Record<string, Action> = {};
// Function to count "type: wait" operations and associate "done" operations per id
function countWaitOperationsAndDone(actions: Action[]) {
@@ -43,10 +43,8 @@ export function organizeWaitOperations(actions: Action[]) {
return result;
}
export type ResultType = {
[key: string]: {
export type ResultType = Record<string, {
waitCount: number,
doneOperation: Action,
input: PdfFile[]
}
}
}>;

View File

@@ -34,27 +34,27 @@ export async function traverseOperations(operations: Action[], input: PdfFile[],
async function computeOperation(action: Action, input: PdfFile[], progressCallback: (state: Progress) => void): Promise<void> {
console.log("Input: ", input);
switch (action.type) {
case "done": // Skip this, because it is a valid node.
break;
case "wait":
const waitOperation = waitOperations[(action as WaitAction).values.id];
case "done": // Skip this, because it is a valid node.
break;
case "wait":
const waitOperation = waitOperations[(action as WaitAction).values.id];
waitOperation.input.concat(input); // TODO: May have unexpected concequences. Needs further testing!
waitOperation.input.concat(input); // TODO: May have unexpected concequences. Needs further testing!
waitOperation.waitCount--;
if(waitOperation.waitCount == 0 && waitOperation.doneOperation.actions) {
await nextOperation(waitOperation.doneOperation.actions, waitOperation.input, progressCallback);
}
break;
default:
const operator = getOperatorByName(action.type);
if(operator) {
let operation = new operator(action);
input = await operation.run(input, progressCallback);
await nextOperation(action.actions, input, progressCallback);
}
else
throw new Error(`${action.type} not implemented yet.`);
waitOperation.waitCount--;
if(waitOperation.waitCount == 0 && waitOperation.doneOperation.actions) {
await nextOperation(waitOperation.doneOperation.actions, waitOperation.input, progressCallback);
}
break;
default:
const operator = getOperatorByName(action.type);
if(operator) {
const operation = new operator(action);
input = await operation.run(input, progressCallback);
await nextOperation(action.actions, input, progressCallback);
}
else
throw new Error(`${action.type} not implemented yet.`);
}
}
}

View File

@@ -17,7 +17,7 @@ export function validateOperations(actions: Action[]): { valid: boolean, reason?
const operator = getOperatorByName(action.type);
if(!operator) {
return { valid: false, reason: `action.type ${action.type} does not exist` }
return { valid: false, reason: `action.type ${action.type} does not exist` };
}
const validationResult = operator.schema.validate({values: action.values});
@@ -44,7 +44,7 @@ export function validateOperations(actions: Action[]): { valid: boolean, reason?
}
}
else if (action.type === "done") {
return { valid: false, reason: `There shouldn't be a done action here.` };
return { valid: false, reason: "There shouldn't be a done action here." };
}
else {
const receivingOperator = getOperatorByName(childAction.type);

View File

@@ -1,7 +1,7 @@
import * as PDFJS from 'pdfjs-dist';
import type { PDFDocumentProxy as PDFJSDocument } from 'pdfjs-dist/types/src/display/api';
import { PDFDocument as PDFLibDocument } from 'pdf-lib';
import Joi from 'joi';
import * as PDFJS from "pdfjs-dist";
import type { PDFDocumentProxy as PDFJSDocument } from "pdfjs-dist/types/src/display/api";
import { PDFDocument as PDFLibDocument } from "pdf-lib";
import Joi from "joi";
export enum RepresentationType {
Uint8Array,
@@ -17,25 +17,25 @@ export class PdfFile {
get uint8Array() : Promise<Uint8Array> {
switch (this.representationType) {
case RepresentationType.Uint8Array:
return new Promise((resolve) => {
resolve(this.representation as Uint8Array);
});
case RepresentationType.PDFLibDocument:
return new Promise(async (resolve) => {
var uint8Array = await (this.representation as PDFLibDocument).save();
this.uint8Array = uint8Array;
resolve(uint8Array);
});
case RepresentationType.PDFJSDocument:
return new Promise(async (resolve) => {
var uint8Array = await (this.representation as PDFJSDocument).getData();
this.uint8Array = uint8Array;
resolve(uint8Array);
});
default:
console.error("unhandeled PDF type: " + typeof this.representation as string);
throw Error("unhandeled PDF type");
case RepresentationType.Uint8Array:
return new Promise((resolve) => {
resolve(this.representation as Uint8Array);
});
case RepresentationType.PDFLibDocument:
return new Promise(async (resolve) => {
const uint8Array = await (this.representation as PDFLibDocument).save();
this.uint8Array = uint8Array;
resolve(uint8Array);
});
case RepresentationType.PDFJSDocument:
return new Promise(async (resolve) => {
const uint8Array = await (this.representation as PDFJSDocument).getData();
this.uint8Array = uint8Array;
resolve(uint8Array);
});
default:
console.error("unhandeled PDF type: " + typeof this.representation );
throw Error("unhandeled PDF type");
}
}
set uint8Array(value: Uint8Array) {
@@ -45,19 +45,19 @@ export class PdfFile {
get pdfLibDocument() : Promise<PDFLibDocument> {
switch (this.representationType) {
case RepresentationType.PDFLibDocument:
return new Promise((resolve) => {
resolve(this.representation as PDFLibDocument);
});
default:
return new Promise(async (resolve) => {
var uint8Array = await this.uint8Array;
var pdfLibDoc = await PDFLibDocument.load(uint8Array, {
updateMetadata: false,
});
this.pdfLibDocument = pdfLibDoc;
resolve(pdfLibDoc);
case RepresentationType.PDFLibDocument:
return new Promise((resolve) => {
resolve(this.representation as PDFLibDocument);
});
default:
return new Promise(async (resolve) => {
const uint8Array = await this.uint8Array;
const pdfLibDoc = await PDFLibDocument.load(uint8Array, {
updateMetadata: false,
});
this.pdfLibDocument = pdfLibDoc;
resolve(pdfLibDoc);
});
}
}
set pdfLibDocument(value: PDFLibDocument) {
@@ -67,16 +67,16 @@ export class PdfFile {
get pdfJsDocument() : Promise<PDFJSDocument> {
switch (this.representationType) {
case RepresentationType.PDFJSDocument:
return new Promise((resolve) => {
resolve(this.representation as PDFJSDocument);
});
default:
return new Promise(async (resolve) => {
const pdfjsDoc = await PDFJS.getDocument(await this.uint8Array).promise;
this.pdfJsDocument = pdfjsDoc;
resolve(pdfjsDoc);
});
case RepresentationType.PDFJSDocument:
return new Promise((resolve) => {
resolve(this.representation as PDFJSDocument);
});
default:
return new Promise(async (resolve) => {
const pdfjsDoc = await PDFJS.getDocument(await this.uint8Array).promise;
this.pdfJsDocument = pdfjsDoc;
resolve(pdfjsDoc);
});
}
}
set pdfJsDocument(value: PDFJSDocument) {

View File

@@ -23,5 +23,5 @@ export const JoiPDFFileSchema = Joi.custom((value: Express.Multer.File[] /* <- a
}, "pdffile validation");
function isPdfFileArray(value: any[]): value is PdfFile[] { // "is" is a ts-typeguard - https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
return value.every((e) => e instanceof PdfFile)
return value.every((e) => e instanceof PdfFile);
}