const binding = require('./build/Release/pdf_oxide');
class PdfDocument {
constructor(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string');
}
this._handle = binding.openDocument(path);
this._closed = false;
}
static openFromBuffer(data) {
if (!Buffer.isBuffer(data) && !(data instanceof Uint8Array)) {
throw new TypeError('data must be a Buffer or Uint8Array');
}
const doc = Object.create(PdfDocument.prototype);
doc._handle = binding.openFromBuffer(data);
doc._closed = false;
return doc;
}
static openWithPassword(path, password) {
if (typeof path !== 'string') throw new TypeError('path must be a string');
if (typeof password !== 'string') throw new TypeError('password must be a string');
const doc = Object.create(PdfDocument.prototype);
doc._handle = binding.openWithPassword(path, password);
doc._closed = false;
return doc;
}
getPageCount() {
this._checkClosed();
return binding.getPageCount(this._handle);
}
getVersion() {
this._checkClosed();
return binding.getVersion(this._handle);
}
hasStructureTree() {
this._checkClosed();
return binding.hasStructureTree(this._handle);
}
extractText(pageIndex) {
this._checkClosed();
if (!Number.isInteger(pageIndex) || pageIndex < 0) {
throw new RangeError('pageIndex must be a non-negative integer');
}
return binding.extractText(this._handle, pageIndex);
}
toMarkdown(pageIndex) {
this._checkClosed();
if (!Number.isInteger(pageIndex) || pageIndex < 0) {
throw new RangeError('pageIndex must be a non-negative integer');
}
return binding.toMarkdown(this._handle, pageIndex);
}
toHtml(pageIndex) {
this._checkClosed();
if (!Number.isInteger(pageIndex) || pageIndex < 0) {
throw new RangeError('pageIndex must be a non-negative integer');
}
return binding.toHtml(this._handle, pageIndex);
}
toPlainText(pageIndex) {
this._checkClosed();
if (!Number.isInteger(pageIndex) || pageIndex < 0) {
throw new RangeError('pageIndex must be a non-negative integer');
}
return binding.toPlainText(this._handle, pageIndex);
}
toMarkdownAll() {
this._checkClosed();
return binding.toMarkdownAll(this._handle);
}
close() {
if (!this._closed && this._handle) {
binding.closeDocument(this._handle);
this._closed = true;
this._handle = null;
}
}
isClosed() {
return this._closed;
}
[Symbol.dispose]() {
this.close();
}
_checkClosed() {
if (this._closed) {
throw new Error('Document is closed');
}
}
}
const LogLevel = {
OFF: 0,
ERROR: 1,
WARN: 2,
INFO: 3,
DEBUG: 4,
TRACE: 5,
};
function setLogLevel(level) {
if (typeof level !== 'number' || level < 0 || level > 5) {
throw new RangeError('level must be a number between 0 (Off) and 5 (Trace)');
}
binding.setLogLevel(level);
}
function getLogLevel() {
return binding.getLogLevel();
}
module.exports = { PdfDocument, LogLevel, setLogLevel, getLogLevel };