Skip to content

Instantly share code, notes, and snippets.

@cyrilis
Created November 8, 2016 13:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyrilis/8d48eef37fbc108869ac32eb3ef97bca to your computer and use it in GitHub Desktop.
Save cyrilis/8d48eef37fbc108869ac32eb3ef97bca to your computer and use it in GitHub Desktop.

How to use the zip command to create an EPUB file

I have been working on my Markdown to EPUB conversion utility, and have decided to use the zip command which is available on both Windows and Linux machines.

An EPUB file is essentially a zip file containing the following files and folders, where index.xhtml is the file created by the Markdown conversion. The content.opf file contains all the EPUB meta information (title, description etc) and a manifest or list of very file that is part of the publication.

|  mimetype
|
+--META-INF
|    container.xml
|
\–OEBPS
    |  content.opf
    |  toc.ncx
    |
    +--images
    |    cover.png
    +--text
         index.xhtml

To generate an EPUB for the above file / folder structure, you would simply zip the contents up into a .zip file, and then rename it to .epub – however when I initially tried this, I was getting errors when I uploaded the EPUB file to the on-line EPUB validator service. The errors where a bit cryptic like:

"Extra field length for first filename must be 0, but was 129!"

After a little research it turns out that EPUB files don’t like the extra file attributes that the zip command adds by default. You can switch them off by using the -X switch. Also the mimetype file needs to be the first file in the compressed zip file and shouldn’t be compressed. This can be achieved by using the -0 switch, which instructs the zip to only store the file.

So my build process is split into the following 3 parts:

zip -X -0 gbe.epub.zip mimetype
zip -X -9 -r gbe.epub.zip * -x mimetype
rename gbe.epub.zip gbe.epub

The first line stores the mimetype file into the zip file first, the second line includes into the sub-directories (-r) adding all the files with the maximum compression (-9) excluding the mimetype file (-x mimetype) as that’s already been added. The last line renames the zip file to the resulting EPUB file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment