Skip to content
Patrick G edited this page Nov 24, 2016 · 10 revisions

This page has some useful snippets of code to use with epub.js v0.2. Note that this page assumes that your book was loaded into an object named book.

Table of Contents

Generating and getting page numbers

To use pagination, first you have to generate the page numbers. This will return a promise which completes after the pagination is generated:

book.generatePagination().then(function () {
    console.log("The pagination has been generated");
});

To have pagination consistent across different window sizes, you can specify a fixed size in pixels for each page:

var width = 600;
var height = 600;

book.generatePagination(width, height).then(function () {
    console.log("The pagination has been generated");
});

To get the page number of a CFI:

book.pagination.pageFromCfi(cfiGoesHere);
/* This returns a page number as an Integer */

To get the current page:

book.pagination.pageFromCfi(book.getCurrentLocationCfi());
/* This returns a page number as an Integer */

Searching the current chapter

To search the current chapter of the book for some text, you can use the following code:

book.currentChapter.find("Some Text to look for");

/*
 *  This returns an array of objects like: 
 * [{
 *     "cfi": "epubcfi(/6/18[chap-1]!4/2/30/1:24,1:31)",
 *     "excerpt": "...here is some text to look for..."
 * }, {
 *     "cfi": "epubcfi(/6/18[chap-1]!4/2/66/1:22,1:29)",
 *     "excerpt": "...I have found some more text to look for in this book..."
 * }]
 * 
 * The array can be looped over with a for loop, and used for search results. 
 * This function is case insensitive.
 * Note that this only searches the current chapter.
 * 
 */

Loading a book from a file input

This only works with browsers which support ArrayBuffer.

Add this to your HTML:

<input type="file" accept="application/epub+zip" id="bookChooser">

And this to your JavaScript:

book = null;
document.getElementById('bookChooser').addEventListener('change', function(e) {
    var firstFile = e.target.files[0];
    if (window.FileReader) {
        var reader = new FileReader();
        reader.onload = function(e) {
            book = ePub({ bookPath: e.target.result });

            book.renderTo("area"); 
            /* Replace area with the id for your div to put the book in */
        }.bind(this);

        reader.readAsArrayBuffer(firstFile);
    } else {
        alert("Your browser does not support the required features. Please use a modern browser such as Google Chrome, or Mozilla Firefox");
    }
});
Clone this wiki locally