Generate EPUB books from HTML with a simple API in Node.js or the browser.
See JSZip Support table for which engines are supported. In addition, browsers need to support fetch
as well as DOMParser
and XMLSerializer
to replace node-fetch
and htmlparser2
(plus ecosystem).
This EPUB library will generate the needed files, as well as download all referenced images. Note that all fonts and all images respectively are downloaded in parallel in batches, so please keep that in mind when adjusting fetchTimeout
.
Note that in the browser, only images on servers with CORS enabled can be downloaded.
On the server (with Node.js), image paths can also start with file://
, in which case they are read directly from disc. The part after file://
must be a valid path for your system, as read by fs.readFile
.
Install the lib and add it as a dependency (recommended), run in your project directory:
npm install epub-gen-memory --save
Then put this in your code:
import epub from 'epub-gen-memory';
epub(options).then(
content => console.log("Ebook Generated Successfully!"),
err => console.error("Failed to generate Ebook because of ", err)
);
See JSZip documentation on how to get the zip to the user. For a nodejs example please see the tests.
In environments where SharedArrayBuffer
is not available, you might want to instead import from epub-gen-memory/sabstub
, which includes a non-functional stub:
import epub from 'epub-gen-memory/sabstub';
The package also includes a browserifyd bundle (UMD) as epub-gen-memory/bundle
. It is possible to use the bundle if you want to build for the browser. The bundle is also available from a CDN: UNPKG (latest, latest 1.x). The bundle also includes the proper return type for the browser (Promise<Blob>
instead of Promise<Buffer>
).
import epub from 'epub-gen-memory/bundle';
Note: This library was written in TypeScript and thus uses ESM exports, but it was compiled to CommonJS, so you can also use the following:
const epub = require('epub-gen-memory').default;
import epub, { EPub, optionsDefaults, chapterDefaults } from 'epub-gen-memory';
import type { Options, Content, Chapter, Font } from 'epub-gen-memory';
optionsOrTitle
:Options | string
if string, then equivalent to{ title: <optionsOrTitle> }
(see below)content
:Chapter[]
(see below)- varargs:
version
:3 | 2
,verbose
:boolean
(in any order or not at all) - Returns:
Promise<Buffer>
- Browser Returns:
Promise<Blob>
contructor(options: Options, content: Chapter[])
render(): Promise<EPub>
genEpub(): Promise<Buffer>
(BrowserPromise<Blob>
)generateAsync(options: JSZipGeneratorOptions): Promise<...>
see JSZip.generateAsync
protected:
generateTemplateFiles(): Promise<void>
downloadAllFonts(): Promise<void>
downloadAllImages(): Promise<void>
makeCover(): Promise<void>
version
:number
(default3
) Epub version- Returns:
Options
defaults
index
:number
of the chapter- Returns:
Chapter
defaults
title
:string
Title of the bookauthor
:string | string[]
(optional, default['anonymous']
)
Name of the author for the book, e.g."Alice"
or["Alice", "Bob"]
publisher
:string
(optional, defaultanonymous
)
Publisher namedescription
:string
(optional)
Book descriptioncover
:string | File
(optional)
Book cover image URL, e.g."http://abc.com/book-cover.jpg"
orFile
object containing image bytestocTitle
:string
(optional, defaultTable of Contents
)
Title of the Table of ContentstocInTOC
:boolean
(optional, defaulttrue
)
Whether to show the TOC entry in the reader's Table of Contents; only for EPUB2numberChaptersInTOC
:boolean
(optional, defaulttrue
)
Automatically number entries in TOCprependChapterTitles
:boolean
(optional, defaulttrue
)
Automatically put the title of the chapter before the contentdate
:string
(optional, default today)
Publication datelang
:string
(optional, defaulten
)
Language code of the bookcss
:string
(optional)
CSS string, replaces our default styles, e.g:"body{background: #000}"
fonts
:Font[]
(optional)
Array of fonts to include, see belowversion
:number
(optional, default3
)
Version of the generated EPUB,3
for the latest version (http://idpf.org/epub/30) or2
for the previous version (http://idpf.org/epub/201)fetchTimeout
:number
(optional, default20000
)
Timeout time for requests, in milliseconds; Browsers need to supportAbortController
and signals for this to workretryTimes
:number
(optional, default3
)
How many times to retry fetching resourcesbatchSize
:number
(optional, default100
)
The size of the batches to use when downloading filesignoreFailedDownloads
:boolean
(optional, defaultfalse
)
Instead of throwing, emit a warning and write an empty file if a font or image fails to downloadverbose
:boolean | ((type, ...args) => void)
(optional, defaultfalse
)
Whether to log progress messages; If a function is provided, the first argument will either be'log'
or'warn'
Within each chapter object:
title
:string
(optional, defaultChapter [number]
)
Chapter titleauthor
:string | string[]
(optional)
Chapter author, generates info below chapter titlecontent
:string
HTML String of the chapter content, image sources are downloadedexcludeFromToc
:boolean
(optional, defaultfalse
)
Don't list chapter in Table of ContentsbeforeToc
:boolean
(optional, defaultfalse
)
List chapter before Table of Contents headingfilename
:string
(optional)
Custom name for chapter fileurl
:string
(optional)
External link below chapter title
Within each font object:
filename
:string
Name under which the font should be downloaded, including file extensionurl
:string
URL where to find font, for best compatibility usettf
(TrueType) fonts
You can then use the fonts as such (assuming you have a font with filename Merriweather.ttf
):
@font-face {
font-family: "Merriweather";
font-style: normal;
font-weight: normal;
src : url(./fonts/Merriweather.ttf);
}
Only includes major changes
- Fixed file names
Internal chapter files are no longer given invalid names if the chapter title includes non-alphanumeric characters
- Optionally disable input validation
In the browser, by default, validation is not bundled due to size. To force use/not use, see the fileslib/util/predicates{-nop}.ts
. - Support
File
for cover
Useful in the browser to allow user-uploaded files without temporary storage
From Lewis Carroll "Alice's Adventures in Wonderland", based on text at https://www.cs.cmu.edu/~rgs/alice-table.html and images from http://www.alice-in-wonderland.net/resources/pictures/alices-adventures-in-wonderland.
Please see the tests for the code used. EPUBs are generated next to the built test files.
This library is based on the work of @cyrilis.