Skip to content

Instantly share code, notes, and snippets.

@caraya
Created September 27, 2014 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caraya/477d86eecc0096078140 to your computer and use it in GitHub Desktop.
Save caraya/477d86eecc0096078140 to your computer and use it in GitHub Desktop.
generator for package.opf file in epub3 books
#!/usr/bin/env python
import mimetypes
import glob
import os
import os.path
# Initialize the mimetypes database
mimetypes.init()
# Create the package.opf file
package = open('package.opf', 'w')
# The glob below should encompass everything under
# OEBPS but I'm not certain how it'll work
package_content = glob.glob('OEBPS/**/*')
#package_content += glob.glob('OEBPS/*/*')
#package_content += glob.glob('OEBPS/*/*/*')
template_top = '''<package xmlns="http://www.idpf.org/2007/opf"
unique-identifier="book-id"
version="3.0" xml:lang="en">
<metadata >
<!-- TITLE -->
<dc:title></dc:title>
<!-- AUTHOR, PUBLISHER AND PUBLICATION DATES-->
<dc:creator></dc:creator>
<dc:publisher></dc:publisher>
<dc:date></dc:date>
<meta property="dcterms:modified"></meta>
<!-- MISC INFORMATION -->
<dc:language>en</dc:language>
<dc:identifier id="book-id"></dc:identifier>
<meta name="cover" content="img-cov" />
<manifest>
'''
template_transition = '''</manifest>
<spine toc="ncx">'''
template_bottom = '''</spine>
</package>'''
manifest = ""
spine = ""
# Write each HTML file to the ebook, collect information for the index
for i, item in enumerate(package_content):
basename = os.path.basename(item)
mime = mimetypes.guess_type(item, strict=True)
manifest += '\t<item id="file_%s" href="%s" media-type="%s"/>\n' % (i+1, basename, mime[0])
spine += '\n\t<itemref idref="file_%s" />' % (i+1)
# I don't remember my python all that well to remember
# how to print the interpolated content.
# This should do for now.
package.write(template_top)
package.write(manifest)
package.write(template_transition)
package.write(spine)
package.write(template_bottom)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment