Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created November 15, 2023 12:58
Show Gist options
  • Save smitroshin/af306d9632ead07064df67651651e3ff to your computer and use it in GitHub Desktop.
Save smitroshin/af306d9632ead07064df67651651e3ff to your computer and use it in GitHub Desktop.
Get PDF page count from a PDF Blob
/**
* Get PDF page count from a PDF Blob
*
* Source: https://stackoverflow.com/a/58089003
*/
export const getPdfPageCount = (pdfFile: Blob) =>
new Promise<number>((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(pdfFile);
reader.addEventListener("loadend", function () {
if (!this.result) {
resolve(0);
return;
}
const count = (this.result as string).match(/\/Type[\s]*\/Page[^s]/g)?.length;
if (!count) {
resolve(0);
return;
}
resolve(count);
});
reader.addEventListener("error", function () {
reject("Failed to read PDF file during read of page count");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment