Skip to content

Instantly share code, notes, and snippets.

@khotyn
Created June 12, 2012 12:31
Show Gist options
  • Save khotyn/2917232 to your computer and use it in GitHub Desktop.
Save khotyn/2917232 to your computer and use it in GitHub Desktop.
A simple tool named Varamyr written in Python to add some css to the epub file so books written in Chinese can be read in Nook.
from xml.dom.minidom import getDOMImplementation, parse, parseString
import zipfile
import sys
font = """\n<style type='text/css'>\n
@page {\n
margin-bottom: 5pt;\n
margin-top: 5pt\n
}\n
@font-face {\n
font-family: \"DroidFont\", serif, sans-serif;\n
font-weight: normal;\n
font-style: normal;\n
src: url(res:///system/fonts/DroidSansFallback.ttf)\n
}\n
@font-face {\n
font-family: \"DroidFont\", serif, sans-serif;\n
font-weight: bold;\n
font-style: normal;\n
src: url(res:///system/fonts/DroidSansFallback.ttf)\n
}\n
@font-face {\n
font-family: \"DroidFont\", serif, sans-serif;\n
font-weight: normal;\n
font-style: italic;\n
src: url(res:///system/fonts/DroidSansFallback.ttf)\n
}\n
@font-face {\n
font-family: \"DroidFont\", serif, sans-serif;\n
font-weight: bold;\n
font-style: italic;\n
src: url(res:///system/fonts/DroidSansFallback.ttf)\n
}\n</style>"""
if len(sys.argv) <= 1:
print 'Please specify the epub file to convert'
exit()
originFilePath = sys.argv[1]
targetFilePath = originFilePath[:originFilePath.rfind('.')] + '-varamyr' + originFilePath[originFilePath.rfind('.'):]
print 'Converting ' + originFilePath + ' to ' + targetFilePath
itemList = []
def getHTML(entry):
if entry.endswith('opf'):
[itemList.append(item.getAttribute('href')) for item in parseString(zf.read(entry)).getElementsByTagName('item') if item.getAttribute('media-type') == ('application/xhtml+xml')]
def getData(entry):
data = zf.read(entry)
return (data[:data.find('<head>') + len('<head>')] + font + data[data.find('<head>') + len('<head>'):] if '<head>' in data else data) if entry[entry.rfind('/') + 1:] in itemList else data
zf = zipfile.ZipFile(originFilePath)
newZf = zipfile.ZipFile(targetFilePath, mode='w')
[getHTML(entry) for entry in zf.namelist()]
[newZf.writestr(entry, getData(entry)) for entry in zf.namelist()]
newZf.close()
print 'Converting Completed!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment