@pixdif/pdf-parser
Version:
57 lines (56 loc) • 1.78 kB
JavaScript
import { Parser } from '@pixdif/parser';
import PdfOutline from './base/PdfOutline.js';
import PdfPage from './base/PdfPage.js';
import { getDocument, } from './util/pdfjs.js';
export default class PdfParser extends Parser {
document;
async openFile() {
if (!this.document) {
this.document = await getDocument(this.filePath).promise;
}
}
async closeFile() {
if (!this.document) {
throw new Error('The PDF document is not open yet.');
}
await this.document.cleanup(false);
await this.document.destroy();
delete this.document;
}
async getPageNum() {
if (this.document) {
return this.document.numPages;
}
return 0;
}
async getPage(index) {
if (!this.document) {
throw new Error('The PDF file is not open yet.');
}
if (index < 0 || index >= await this.getPageNum()) {
throw new Error(`Invalid page index: ${index}`);
}
const pageIndex = index + 1;
const page = await this.document.getPage(pageIndex);
return new PdfPage(this.document, `Page ${pageIndex}`, page);
}
async getOutline() {
const outline = await this.document?.getOutline();
if (!outline) {
return [];
}
return outline.map(this.wrapOutline);
}
wrapOutline = ({ title, items, }) => {
if (!this.document) {
throw new Error('The PDF file is not open yet.');
}
const children = items && items.length > 0 ? items.map(this.wrapOutline) : undefined;
return new PdfOutline(this.document, {
title,
children,
offset: 0,
limit: 0,
});
};
}