python制作epub文件代码

python制作epub文件代码,已封装成类,可以直接使用。

# encoding:utf-8
# !/usr/bin/python3
import zipfile
import os.path


container_template = '''<?xml version="1.0" encoding="utf-8" standalone="no"?>
    <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
      <rootfiles>
        <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
      </rootfiles>
  </container>
    '''
content_template = '''
   <?xml version="1.0" encoding="utf-8" standalone="no"?>
   <package xmlns="http://www.idpf.org/2007/opf" 
            xmlns:dc="http://purl.org/dc/elements/1.1/" 
            unique-identifier="bookid" version="2.0">
     <metadata>
       <dc:title>Hello World: My First EPUB</dc:title>
       <dc:creator>Svoid</dc:creator>
       <dc:identifier id="bookid">urn:uuid:12345</dc:identifier>
       <meta name="cover" content="cover-image" />
     </metadata>
     <manifest>
         %(manifest)s
       <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
       <item id="content" href="content.html" media-type="application/xhtml+xml"/>
       <item id="css" href="Styles/stylesheet.css" media-type="text/css"/>
     </manifest>
     <spine toc="ncx">
         %(spine)s
       <itemref idref="cover" linear="no"/>
       <itemref idref="content"/>
     </spine>
     <guide>
       <reference href="cover.html" type="cover" title="Cover"/>
     </guide>
   </package>
   '''
nav_template='''<navPoint id="navPoint-%(id)d" playOrder="%(id)d">
      <navLabel>
        <text>%(dir)s</text>
      </navLabel>
      <content src="Text/%(html_filname)s"/>
    </navPoint>'''

toc_template = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
   "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">

<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
  <head>
    <meta name="dtb:uid" content="urn:uuid:12345"/>
    <meta name="dtb:depth" content="2"/>
    <meta name="dtb:totalPageCount" content="0"/>
    <meta name="dtb:maxPageNumber" content="0"/>
  </head>
  <docTitle>
    <text>%(title)s</text>
  </docTitle>
  <navMap>
    %(navList)s
  </navMap>
</ncx>
'''
dir_temple = '''
<div class="sgc-toc-level-1">
  <a href=%(html_filname)s>%(dir)s</a>
</div>
'''


toc_html_template = '''
    <?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Contents</title>
<link href="../sgc-toc.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="sgc-toc-title">Table of Contents</div>
%(dirList)s
</body></html>
'''

class epub:
    def __init__(self, title):
        self.title = title
        # acreate zip file
        if not os.path.exists(title):
            os.mkdir(title)
        os.chdir(title)
        self.epubFile = zipfile.ZipFile('%s.epub' % title, 'w')
        self.manifest = ''
        self.spine = ''
        self.toc_navList = ''
        self.id = 0
        self.dirList = ''
        self.manifest += '<item id="TOC.xhtml" href="Text/TOC.xhtml" media-type="application/xhtml+xml"/>'
        self.spine += '<itemref idref="TOC.xhtml"/>'
        self.create_mimetype()
        self.create_container()
        self.create_stylesheet()
    def setAutho(self, autho):
        self.autho = autho
    def setType(self, type):
        self.type = type
    def addFile(self, html_content, dir):
        # 构造文件,创建html
        html_filname = "%s.html" % dir
        html_fd = os.open(html_filname, os.O_RDWR|os.O_CREAT )
        os.write(html_fd, bytes(html_content, encoding = "utf-8"))
        os.close(html_fd)
        self.manifest += '<item id="%s" href="Text/%s" media-type="application/xhtml+xml"/>' % (html_filname, html_filname)
        self.spine += '<itemref idref="%s"/>' % (html_filname)
        self.id = self.id + 1
        self.toc_navList += nav_template % {"id": self.id, "dir": dir, "html_filname" : html_filname}

        print("html_filname:", html_filname)
        print("toc_navList:", self.toc_navList)


        self.dirList += dir_temple % {"html_filname" : html_filname, "dir": dir}
        self.epubFile.write(html_filname, 'OEBPS/Text/' + html_filname, compress_type=zipfile.ZIP_DEFLATED)

    def close(self):
        # save zip file
        self.create_toc()
        self.create_content_file()
        self.epubFile.close()
    def create_mimetype(self):
        self.epubFile.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
    def create_container(self):
        self.epubFile.writestr('META-INF/container.xml', container_template, compress_type=zipfile.ZIP_STORED)
    def create_toc(self):
        self.epubFile.writestr('OEBPS/toc.ncx', toc_template % {"title": self.title, "navList": self.toc_navList}, compress_type=zipfile.ZIP_STORED)
        self.epubFile.writestr('OEBPS/Text/TOC.xhtml', toc_html_template % {"dirList" : self.dirList}, compress_type=zipfile.ZIP_STORED)
    def create_content_file(self):
        self.epubFile.writestr('OEBPS/content.opf', content_template % {
            'manifest': self.manifest,
            'spine': self.spine, },
                      compress_type=zipfile.ZIP_STORED)

    def create_stylesheet(self):
        css_info = '''
            body {
              font-family: sans-serif;     
            }
            h1,h2,h3,h4 {
              font-family: serif;     
              color: red;
            }
        '''
        self.epubFile.writestr('OEBPS/Styles/stylesheet.css', css_info, compress_type=zipfile.ZIP_STORED)

if __name__ == '__main__':
    #path = 'E:\\python\\epub_test\\test1'
    #create_archive(path)
    epubObj = epub("nihao")
    epubObj.addFile("nihaoshijie", "nihao")
    epubObj.addFile("hello word", "hello")
    epubObj.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值