Ejemplo n.º 1
0
 def build_menu(self):
     print('[Main Thread] Building Menu...')
     self.menu = [[epub.Section('目次'), []]]
     for element in self.menu_raw:
         try:
             if element['class'] == ['widget-toc-episode']:
                 url = 'https://kakuyomu.jp' + element.find('a', class_='widget-toc-episode-episodeTitle')['href']
                 title = element.find('a', class_='widget-toc-episode-episodeTitle').find('span',
                                                                                          class_='widget-toc-episode-titleLabel js-vertical-composition-item').string
                 filename, epub_page = build_page(self.fetch_pages[url], url)
                 self.book.add_item(epub_page)
                 self.book.spine.append(epub_page)
                 try:
                     self.menu[-1][-1][-1][-1].append(epub.Link(filename + '.xhtml', title, filename))
                 except (TypeError, AttributeError, IndexError):
                     self.menu[-1][-1].append(epub.Link(filename + '.xhtml', title, filename))
             elif element['class'] == ['widget-toc-chapter', 'widget-toc-level1', 'js-vertical-composition-item']:
                 title = element.find('span').string
                 if self.menu[0][0].title == '目次':
                     self.menu[0][0] = epub.Section(title)
                 else:
                     self.menu.append([epub.Section(title), []])
             elif element['class'] == ['widget-toc-chapter', 'widget-toc-level2', 'js-vertical-composition-item']:
                 title = element.find('span').string
                 self.menu[-1][-1].append([epub.Section(title), []])
         except TypeError:
             pass
     self.book.toc = self.menu
Ejemplo n.º 2
0
def toc_from_headings(html: str,
                      filename: str = "",
                      chapter_title: str = "Sheet") -> list:
    """Accept a chapter of HTML, and extract a table of contents segment.

    Parameters
    ----------
    html
      The HTML block to be parsed.
    filename
      The name of this file to be used for hrefs. E.g.
      "index.html#heading_1".

    Returns
    -------
    toc
      A sequence of table-of-contents links.

    """
    # Parse the HTML
    parser = HeadingParser()
    parser.feed(html)
    headings = parser.headings
    # Parse into a table of contents
    if len(headings) == 0:
        # No headings found, so just the chapter link
        toc = epub.Link(href=filename, title=chapter_title, uid=filename)
    else:
        # Add a section for the chapter as a whole
        toc = (epub.Section(href=filename, title=chapter_title), [])
        sections_stack = [toc]
        # Parse all the headings
        for idx, heading in enumerate(headings):
            # Determine where we are in the tree
            href = f"{filename}#{heading['id']}"
            parent_section = sections_stack[-1]
            is_last = idx == (len(headings) - 1)
            is_leaf = is_last or heading["level"] >= headings[idx + 1]["level"]
            # Add a leaf or branch depending on the heading structure
            if is_leaf:
                parent_section[1].append(
                    epub.Link(href=href,
                              title=heading["title"],
                              uid=href.replace("#", ":")))
            else:
                new_section = (epub.Section(href=href,
                                            title=heading["title"]), [])
                parent_section[1].append(new_section)
                sections_stack.append(new_section)
            # Walk back up the stack
            if not is_last:
                for idx in range(
                        max(0, heading["level"] - headings[idx + 1]["level"])):
                    sections_stack.pop()

    return toc
Ejemplo n.º 3
0
def epub_write_test():
    book = epub.EpubBook()
    
    # set metadata
    book.set_identifier('id123456')
    book.set_title('Sample book')
    book.set_language('en')
    
    book.add_author('Author Authorowski')
    book.add_author('Danko Bananko', file_as='Gospodin Danko Bananko', role='ill', uid='coauthor')
    
    # create chapter
    c1 = epub.EpubHtml(title='Intro', file_name='chap_01.xhtml', lang='hr')
    c1.content=u'<h1>Intro heading</h1><p>Zaba je skocila u baru.</p>'
    # add chapter
    book.add_item(c1)

    c2 = epub.EpubHtml(title='Chap 1', file_name='chap_02.xhtml', lang='hr')
    c2.content=u'<h1>Chap 1</h1><p>This is chap 1 content.</p>'
    book.add_item(c2)
    
    c3 = epub.EpubHtml(title='Chap 2', file_name='chap_03.xhtml', lang='hr')
    c3.content=u'<h1>Chap 2</h1><p>This is chap 2 content.</p>'
    book.add_item(c3)
    
    c4 = epub.EpubHtml(title='Chap 3', file_name='chap_04.xhtml', lang='hr')
    c4.content=u'<h1>Chap 3</h1><p>This is chap 3 content.</p>'
    book.add_item(c4)
    
    # define Table Of Contents
    #book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),
    #             (epub.Section('Simple book'),
    #             (c1, ))
    #            )
    book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),
                epub.Link('chap_02.xhtml', 'Chap 1', 'Chap 1'),
                epub.Link('chap_03.xhtml', 'Chap 2', 'Chap 2'),
                epub.Link('chap_04.xhtml', 'Chap 3', 'Chap 3')
                )
    
    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    
    # define CSS style
    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
    
    # add CSS file
    book.add_item(nav_css)
    
    # basic spine
    book.spine = ['nav', c1, c2, c3, c4]
    
    # write to the file
    epub.write_epub('test.epub', book, {})
Ejemplo n.º 4
0
def html2epub(part_list, dst, **kwargs):

    book = epub.EpubBook()
    book = add_bookinfo(book, **kwargs)

    c_list = []
    toc = []
    for i in range(len(part_list)):
        with io.open(part_list[i], 'r', encoding='utf-8') as f:
            c_soup = BeautifulSoup(f.read(), 'html5lib')
        c = epub.EpubHtml(
            title=u'{0}-part{1}'.format(kwargs['bookname'], i + 1),
            file_name='Text/part{0}.xhtml'.format(i + 1),
        )
        c.content = unicode(c_soup)
        book.add_item(c)
        c_list.append(c)
        toc.append(
            epub.Link(
                'Text/part{0}.xhtml'.format(i + 1),
                'part{0}'.format(i + 1),
                'part{0}'.format(i + 1),
            ))

    book.toc = toc

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav(file_name='Text/nav.xhtml'))
    book.spine = ['nav'] + c_list

    epub.write_epub(dst, book, {})

    return book
Ejemplo n.º 5
0
def main():
    link = 'https://ranobes.com/ranobe/39855-the-book-eating-magician.html'

    info = getRanobesInfo(get_html(link))
    start_link = info['first_chapter']
    book = epub.EpubBook()
    cover = downloadCover(info['poster_url'])
    book.set_cover("image.jpg", open(cover, 'rb').read())
    book.set_identifier('sample123456')
    book.set_title(info['title'])
    book.set_language(lang)
    book.add_author(info['author'])
    num_chapter = 1
    lstChapter = ['nav']
    navMap = list()
    while start_link:
        html = get_html(start_link)
        chapter, start_link = generateChapter(html, num_chapter, lng=lang)
        book.add_item(chapter)
        lstChapter.append(chapter)
        navMap.append(
            epub.Link('{}.html'.format(num_chapter), chapter.title, 'intro'))
        num_chapter += 1
        print('\rgenerate chapter {} is done!'.format(num_chapter), end='\r')

    print()
    book.toc = navMap
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = lstChapter
    epub.write_epub('/tmp/{}.epub'.format(info['title']), book, {})
Ejemplo n.º 6
0
 def build_menu(self):
     print('[Main Thread] Building Menu...')
     self.menu = [['メニュー']]
     for element in self.menu_raw:
         try:
             if element.name == 'div':
                 url = 'https://www.alphapolis.co.jp' + element.find(
                     'a')['href']
                 title = element.find('span', class_='title').get_text()
                 filename, epub_page = build_page(self.fetch_pages[url],
                                                  url)
                 self.book.add_item(epub_page)
                 self.book.spine.append(epub_page)
                 self.menu[-1].append(
                     epub.Link(filename + '.xhtml', title, filename))
             elif element.name == 'h3':
                 title = element.string
                 if title:
                     if self.menu[-1] == ['メニュー']:
                         self.menu[-1] = [title]
                     else:
                         self.menu.append([title])
         except TypeError:
             pass
     self.book.toc = tuple([build_section(sec) for sec in self.menu])
Ejemplo n.º 7
0
def create_epub(headers, path):
    """Generate .epub file with news.

    1. Sets the file's metadata.
    2. Creates chapters using values of all tags for each individual news.
    3. Creates navigation.
    4. Write all data to the file in .epub format.
    This file is saved to the directory specified in "output-path" or to
    the directory of executable file if the argument "output-path" wasn't
    provided.
    """
    feed, titles, dates, links, texts = headers[:5]
    book = epub.EpubBook()
    book.set_identifier('Breaking_news')
    book.set_title(feed)
    book.set_language('en')
    book.add_author('User')
    spine = ['nav']
    news_limit = len(titles)
    for i in range(news_limit):
        news = epub.EpubHtml(title=titles[i], file_name='{}.xhtml'.format(i))
        tags = u'<h1>{}</h1><p>{}</p><p>{}</p><p>{}</p>'
        news.content = tags.format(titles[i], dates[i], links[i], texts[i])
        book.add_item(news)
        book.toc.append(epub.Link('{}.xhtml'.format(i), titles[i], titles[i]))
        spine.append(news)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = spine
    script_dir = os.path.dirname(__file__)
    if path:
        file_path = os.path.join(path, 'news.epub')
    else:
        file_path = os.path.join(script_dir, 'news.epub')
    epub.write_epub(file_path, book, {})
Ejemplo n.º 8
0
def create_ebook(chapters, author = "Author Authorowski", book_id = "unknown_id", title = "Title unknown"):
    book = epub.EpubBook()
    book.set_identifier(book_id)
    book.set_title(title)
    book.set_language("ru")
    book.add_author(author)

    spine = []
    for chapter in chapters:
        file_name = "chapter_{}.xhtml".format(chapter["id"])
        c = epub.EpubHtml(title=chapter["title"], file_name=file_name, lang="ru")
        c.content = chapter["content"]
        book.add_item(c)
        spine.append(c)
        # toc.append(c)

    book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'),
                    (
                        epub.Section('Chapters'),
                        spine,
                    )
                )
    book.spine = spine
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    epub.write_epub('test.epub', book, {})

    return
Ejemplo n.º 9
0
def generate_epub(posts):
    book = epub.EpubBook()
    book.set_title('Mr. Money Mustache Blog')
    book.set_language('en')
    book.add_author('Mr. Money Mustache')

    spine_list = ['nav']
    toc = []

    for index, post in enumerate(posts):

        # create chapter
        file_name = '%04d.xhtml' % index
        chapter = epub.EpubHtml(title=post.title, file_name=file_name)
        chapter.content = post.content

        # add chapter
        book.add_item(chapter)

        spine_list.append(chapter)
        toc.append(epub.Link(file_name, post.title, file_name))

    # create table of contents
    book.toc = toc

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    book.spine = spine_list

    # write to the file
    epub.write_epub(os.path.join(DIST_DIR, 'mmm.epub'), book, {})
Ejemplo n.º 10
0
 def create_toc(self, chapterinfo):
     self.chapterinfo = chapterinfo
     for i in self.chapterinfo:
         self.book.add_item(i)
     # define Table Of Contents
     self.book.toc = (epub.Link('intro.xhtml', '目錄',
                                'intro'), (epub.Section('本文'),
                                           tuple(self.chapterinfo)))
Ejemplo n.º 11
0
    def to_epub(self, style=None):
        """Generate `EpubBook` from result of `get_articles`"""
        if not style:
            style = STYLE

        logging.info('Creating book using %s style' % style)
        articles = self.get_articles()

        book = epub.EpubBook()
        book.set_title(self.__class__.name)

        # Create HTML file for each article
        chapters = []
        for i, article in enumerate(articles):
            chapter = epub.EpubHtml(uid=str(i),
                                    title=article.title,
                                    file_name=('%d.xhtml' % i))
            chapter.content = '<html><head>' + \
                '<link rel="stylesheet" href="style/default.css" />' + \
                '</head><body>' + \
                ('<h1>%s</h1>' % article.title) + \
                article.content + '</body></html>'
            chapters.append(chapter)
            book.add_item(chapter)

        # Add generic book metadata
        book.toc = map(
            lambda c: epub.Link(c.get_name(), c.title, str(c.get_id())),
            chapters)
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())

        # Add stylesheet
        # Use path if file exists
        if os.path.exists(style):
            style_path = style
            logging.debug('Using custom style %s' % style)
        # Otherwise use preset style
        else:
            style_name = style if style.endswith('.css') else style + '.css'
            style_path = os.path.join(STYLES_PATH, style_name)

            if not os.path.exists(style_path):
                raise Exception('%s is not a preset style' % style)

            logging.debug('Using preset style %s' % style)

        with open(style_path) as f:
            nav_css = epub.EpubItem(uid="style_nav",
                                    file_name="style/default.css",
                                    media_type="text/css",
                                    content=f.read())

        book.add_item(nav_css)

        book.spine = ['nav'] + chapters

        return book
Ejemplo n.º 12
0
def handler(event, context):

	awsCred = {}
	awsCred['accessKeyId'] = ''
	awsCred['secretAccessKey'] = ''
	awsCred['bucket'] = ''
	strFolder = 'docs'

	strFolderPath = '/tmp/'

	img = Image.new("RGB", (128, 128), "white")
	draw = ImageDraw.Draw(img)
	draw.text((10,10),"Hello world!",(0,0,0))
	img.save(strFolderPath+'demo.jpg')
	uploadToS3(strFolder,strFolderPath+'demo.jpg',awsCred)

	c = canvas.Canvas(strFolderPath+"demo.pdf")
	c.drawString(100,750,"Hello world!")
	c.save()
	uploadToS3(strFolder,strFolderPath+'demo.pdf',awsCred)

	document = Document()
	document.add_heading('Hello world!', level=1)
	document.add_page_break()
	document.save(strFolderPath+'demo.docx')
	uploadToS3(strFolder,strFolderPath+'demo.docx',awsCred)

	workbook = xlsxwriter.Workbook(strFolderPath+'demo.xlsx')
	worksheet = workbook.add_worksheet()
	worksheet.write('A1', 'Hello')
	worksheet.write('A2', 'World!')
	workbook.close()
	uploadToS3(strFolder,strFolderPath+'demo.xlsx',awsCred)

	prs = Presentation()
	title_slide_layout = prs.slide_layouts[0]
	slide = prs.slides.add_slide(title_slide_layout)
	title = slide.shapes.title
	title.text = "Hello, World!"
	prs.save(strFolderPath+'demo.pptx')
	uploadToS3(strFolder,strFolderPath+'demo.pptx',awsCred)

	book = epub.EpubBook()
	book.set_identifier('id123456')
	book.set_title('Hello world!')
	book.set_language('en')
	book.add_author('Author Authorowski')
	c1 = epub.EpubHtml(title='Hello world', file_name='chap_01.xhtml', lang='hr')
	c1.content=u'<h1>Hello world</h1><p>Hello world.</p>'
	book.add_item(c1)
	book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),
	             (epub.Section('Simple book'),
	             (c1, ))
	            )
	epub.write_epub(strFolderPath+'demo.epub', book, {})
	uploadToS3(strFolder,strFolderPath+'demo.epub',awsCred)
Ejemplo n.º 13
0
        def child_tocs(child):
            if child.id:
                us = epub.Link(fname + '#' + child.id, child.title, child.id)
            else:
                us = epub.Section(self.item_heading(child))

            if child.children:
                children = [child_tocs(c) for c in child.children]
                return [us, children]
            else:
                return us
Ejemplo n.º 14
0
def build_page(book: epub.EpubBook, file, filename):
    tex = open(file, "rb").read()
    title, content = epub_html.compile(tex)
    page = epub.EpubHtml(title=title,
                         file_name=filename + ".xhtml",
                         content=content,
                         lang='zh')
    page.add_link(href='./style/style.css', rel='stylesheet', type='text/css')
    link = epub.Link(filename + ".xhtml", title, "chap_" + filename)
    book.add_item(page)
    book.spine.append(page)
    return link
Ejemplo n.º 15
0
  def create_epub(self):
    book = epub.EpubBook()

    # set metadata
    book.set_title(self.serial_name+'-'+self.book_number+' '+self.book_subtitle)
    book.set_language('zh-tw')

    book.add_author(self.writer)

    # create and add chapter 
    chapter_list = []
    toc = []
    for chapter_idx, chapter_file_info in enumerate(self.txt_file_list):
      chapter_title = list(chapter_file_info.keys())[0]
      chapter_path = chapter_file_info[chapter_title]

      chapter_title = chapter_title.replace(self.book_number, '')
      chapter_title = chapter_title.replace(self.book_subtitle, '').lstrip()
      # print(chapter_idx, chapter_title, chapter_path)
      html_file_name = 'chap_'+str(chapter_idx+1)+'.xhtml'
      epubChapter = epub.EpubHtml(title=chapter_title, file_name=html_file_name)
      content = '<h1>'+chapter_title+'</h1><p>'+open(chapter_path, 'rb').read().decode('utf-8').replace('\n', '<br/>')+'</p>'
      # content = '<h1>chapter_title</h1><p>aaaa</p>'
      epubChapter.content = content.encode()
      chapter_list.append(epubChapter)
      book.add_item(epubChapter)
      toc.append(epub.Link(html_file_name, chapter_title, 'chap-'+str(chapter_idx+1)))

    # define Table Of Contents
    book.toc = tuple(toc)

    # # add cover image
    # book.set_cover("image.jpg", open('12.jpg', 'rb').read())

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # basic spine
    # 把書訂起來
    book.spine = ['nav']+chapter_list

    # write to the file
    epub_folder = os.path.join('./', 'books', self.serial_name, 'epub')
    if not os.path.isdir(epub_folder):
      os.makedirs(epub_folder)
    
    epub_file_path = os.path.join(epub_folder, self.epub_file_name+'.epub')
    epub.write_epub(epub_file_path, book, {})
Ejemplo n.º 16
0
    def finalize(self):
        # Define Table of Content
        self.book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'),
                         (epub.Section('Chapters'), self.all_chapters))
        # Add default NCX and NAV
        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        # Add basic spine
        myspine = []
        if self.has_cover:
            myspine.append('cover')
        myspine.extend([self.intro_ch, 'nav'])
        myspine.extend(self.all_chapters)
        self.book.spine = myspine
Ejemplo n.º 17
0
def add_chapter(book, chapter_id, title, content):
    chapter_file_name = chapter_id + '.xhtml'

    print('title: %s' % title)

    chapter = epub.EpubHtml(
        title=title,
        file_name=chapter_file_name,
        lang=LANG,
        content=content,
    )

    book.add_item(chapter)
    book.toc.append(epub.Link(chapter_file_name, title, chapter_id))
    book.spine.append(chapter)
Ejemplo n.º 18
0
 def build_chapters(self):
     logger.info("Building chapters epub...")
     chapters_epub = []
     for chapter in self.chapters:
         chapter_epub = epub.EpubHtml(title=chapter.title,
                                      file_name=f'{uuid.uuid4().hex}.xhtml',
                                      lang='en')
         chapter_epub.content = chapter.build_chapter()
         self.epub.add_item(chapter_epub)
         self.epub.toc += (epub.Link(chapter_epub.file_name,
                                     chapter_epub.title,
                                     uuid.uuid4().hex), )
         chapters_epub.append(chapter_epub)
         logger.info(f"Epub for chapter {chapter} done!")
     return chapters_epub
Ejemplo n.º 19
0
def generate_epub(parent_dir, id, sectionId, title, content):
    content = normalize_content(content)

    book = epub.EpubBook()
    book.FOLDER_NAME = 'OEBPS'

    # add metadata
    book.set_identifier(str(uuid.uuid4()))
    book.set_title(title)
    book.set_language('zh')

    book.add_author('lcell')

    # defube style
    #style = '''p { text-indent: 2em; }'''
    style = ''

    default_css = epub.EpubItem(uid="style_default",
                                file_name="style/default.css",
                                media_type="text/css",
                                content=style)
    book.add_item(default_css)

    c1 = epub.EpubHtml(title=title, file_name='1.xhtml', lang='zh')
    c1.content = content
    c1.add_item(default_css)

    # add chapters to the book
    book.add_item(c1)

    # create table of contents
    book.toc = [epub.Link('1.xhtml', title, 'content')]

    # add navigation files
    book.add_item(epub.EpubNcx())
    #book.add_item(epub.EpubNav())

    # create spine
    book.spine = [c1]

    # create epub file
    dir = output_dir + parent_dir + '/' + unicode(sections[int(sectionId)],
                                                  'utf8')
    if not os.path.exists(dir):
        os.makedirs(dir)
    file_path = dir + '/' + str(id) + '-' + title + '.epub'
    #file_path = title + '.epub'
    epub.write_epub(file_path, book, {})
Ejemplo n.º 20
0
    def make_toc_li(li: BeautifulSoup, toc: TocList):
        href = li.a['href']
        link = epub.Link(
            href=href,
            title=str(li.a.string),
            uid=uids[href],
        )
        spine.append(uids[href])
        not_added_html_files.discard(href)

        if li.ul:
            sub_toc = []
            toc.append((link, sub_toc))
            make_toc_ul(li.ul, sub_toc)
        else:
            toc.append(link)
Ejemplo n.º 21
0
def set_book_cover(ebook, book_id, new_book_id, file_path):
    try:
        logger.info('setting cover for book old book_id:%s new_book_id:%s ',
                    book_id, new_book_id)
        ebook.set_cover('image.jpg', open(file_path, 'rb').read())
        chapter_name = 'Cover'
        file_name = 'cover.xhtml'
        chapter = epub.EpubHtml(title=chapter_name, file_name=file_name)
        chapter.content = '<p><img src="image.jpg" alt="Cover Image"/></p>'
        ebook.add_item(chapter)
        ebook.spine.append('cover')
        ebook.spine.append(chapter)
        ebook.toc.append(epub.Link(file_name, chapter_name, 'intro'))
    except Exception as e:
        logger.info(e)
        print e
Ejemplo n.º 22
0
def write(file_name, title, author, chapters):
    # Ebook
    book = epub.EpubBook()

    # set metadata
    book.set_identifier('id123456')
    book.set_title(title)
    book.set_language('en')
    book.add_author(author)
    book.add_author('Anonymous',
                    file_as='Anonymous',
                    role='ill',
                    uid='coauthor')

    toc = []
    spine = ['nav']
    # For each chapter add chapter to the book, TOC and spine
    for chapter in chapters:
        book.add_item(chapter)
        toc.append(epub.Link(chapter.file_name, chapter.title, chapter.title))
        spine.append(chapter)

    # define Table Of Contents
    book.toc = tuple(toc)

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # define CSS style
    style = 'pre{white-space:pre-wrap;background:#f7f9fa;padding:10px 15px;color:#263238;line-height:1.6;font-size:13px;border-radius:3px margin-top: 0;margin-bottom:1em;overflow:auto}b,strong{font-weight:bolder}#title{font-size:16px;color:#212121;font-weight:600;margin-bottom:10px}hr{height:10px;border:0;box-shadow:0 10px 10px -10px #8c8b8b inset}'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)

    # add CSS file
    book.add_item(nav_css)

    # basic spine
    book.spine = spine

    # write to the file
    epub.write_epub(file_name, book, {})

    print(Back.GREEN + Fore.BLACK + " File " + Back.YELLOW + f" {file_name} " +
          Back.GREEN + " Successfully Written ")
Ejemplo n.º 23
0
def createEpub(bodies, titles, info):
    book = epub.EpubBook()

    # set metadata
    # book.set_identifier('id123456')
    book.set_title(info['title'])
    book.set_language('en')
    book.add_metadata('DC', 'description', info['desc'])
    book.add_author(info['author'])

    # Create blank TOC and a spine
    book.toc = []
    book.spine = ['nav']

    # create chapters
    for i in range(len(bodies)):
        chapter = epub.EpubHtml(title=titles[i],
                                file_name='chap_{}.xhtml'.format(i + 1),
                                lang='en')
        chapter.content = bodies[i]

        # add chapter
        book.add_item(chapter)

        # add chapter to table of contents and spine
        book.toc.append(
            epub.Link('chap_{}.xhtml'.format(i + 1), '{}'.format(titles[i]),
                      '{}'.format(i + 1)))

        book.spine.append(chapter)

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # define CSS style
    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)

    # add CSS file
    book.add_item(nav_css)

    # write to the file
    epub.write_epub('files/' + info['title'] + '.epub', book, {})
Ejemplo n.º 24
0
def write_book(my_book):
    book = epub.EpubBook()
    book.set_identifier(my_book['identifier'])
    book.set_title(my_book['title'])
    book.set_language('it')
    book.add_author(my_book['author'])
    book.add_metadata('DC', 'description', 'This is description for my book')
    book.add_metadata(None, 'meta', '', {'name': 'key', 'content': 'value'})

    # intro chapter
    c1 = epub.EpubHtml(title='Introduction',
                       file_name='intro.xhtml',
                       lang='it')
    c1.set_content(
        u'<html><body><h1>Introduction</h1><p>Introduction paragraph.</p></˓→body></html>'
    )
    # about chapter
    c2 = epub.EpubHtml(title='About this book', file_name='about.xhtml')
    c2.set_content('<h1>About this book</h1><p>This is a book.</p>')

    book.add_item(c1)
    book.add_item(c2)

    chaps = my_book['content']
    for index, chap in enumerate(chaps, start=1):
        chapter = epub.EpubHtml(
            title='chapter {index}'.format(**locals()),
            file_name='chapter_{index}.xhtml'.format(**locals()))
        chapter.set_content(
            '<h1>Capitolo {index}</h1><p>{chap}</p>'.format(**locals()))
        book.add_item(chapter)

    style = 'body { font-family: Times, Times New Roman, serif; }'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)
    book.add_item(nav_css)

    book.toc = (epub.Link('intro.xhtml', 'Introduction',
                          'intro'), (epub.Section('Languages'), (c1, c2)))

    book.spine = ['nav', c1, c2]
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    epub.write_epub('test.epub', book)
Ejemplo n.º 25
0
    def addRecipeText(self, uniqueId, title, text):
        """ Adds the recipe text as a chapter.
        """
        uniqueName = self.getFileForRecipeID(uniqueId, ext="")
        fileName = self.getFileForRecipeID(uniqueId)
        self.recipeCount += 1

        c1 = epub.EpubHtml(title=title, file_name=fileName, lang=self.lang)
        c1.content = text.encode('utf-8')
        c1.add_item(self.recipeCss)

        # add chapter
        self.ebook.add_item(c1)
        self.spine.append(c1)

        # define Table Of Contents
        self.toc.append(epub.Link(fileName, title, uniqueName))
Ejemplo n.º 26
0
def create_epub(isbn=None,
                title=None,
                author=None,
                content='blah blah blah',
                fp=None):

    book = epub.EpubBook()

    # set metadata
    book.set_identifier(isbn)
    book.set_title(title)
    book.set_language('en')

    book.add_author(author)

    # create chapter
    c1 = epub.EpubHtml(title='Intro', file_name='chap_01.xhtml', lang='hr')
    c1.content = '<h1>Intro heading</h1><p>' + content + '</p>'

    # add chapter
    book.add_item(c1)

    # define Table Of Contents
    book.toc = (epub.Link('chap_01.xhtml', 'Introduction',
                          'intro'), (epub.Section('Simple book'), (c1, )))

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # define CSS style
    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid='style_nav',
                            file_name='style/nav.css',
                            media_type='text/css',
                            content=style)

    # add CSS file
    book.add_item(nav_css)

    # basic spine
    book.spine = ['nav', c1]

    # write to the file
    epub.write_epub(fp, book, {})
Ejemplo n.º 27
0
def create_epub(letters):
    book = epub.EpubBook()
    # set metadata
    book.set_identifier('Jernkorset2020-06-09')
    book.set_title('Jernkorset')
    book.set_language('da')
    book.add_author('Jørgen Dalager')
    book.add_author('Christian Dalager')
    chaps = []

    c1 = epub.EpubHtml(title='Introduktion', file_name='intro.xhtml', lang='da')
    c1.content=u'<html><head></head><body><h1>Jernkorset</h1><p>Denne brevsamling består af 666 breve fra perioden 1911 til 1918, primært fra men også til Peter Mærsk, der under første verdenskrig kæmpede på tysk side som en del af det danske mindretal i sønderjylland.</p></body></html>'
    book.add_item(c1)

    
    for i,letter in enumerate(letters):
        c = epub.EpubHtml(title = letter['LetterHeading'],file_name=f'chap_{i+1}.xhtml')
        html = f'<h1>{letter["LetterHeading"]}</h1>'
        html = html + f'<p>Fra: {letter["Sender"]}<br/>Til: {letter["Recipient"]}</p>'
        html = html + ''.join([f'<p>{p}</p>' for p in letter['Text'].split('\n')])
        if(letter['Location']):
            html = html + f'<p><a href="https://www.google.com/maps/@{letter["Location"]},11z">Se {letter["Place"]} på Google Maps</a></p>'
        c.content = html
        book.add_item(c)
        chaps.append(c)

    book.toc = (epub.Link('intro.xhtml', 'Introduktion', 'intro'),
                 (epub.Section('Brevene'),
                 (tuple(chaps)))
                )


    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)

    # add CSS file
    book.add_item(nav_css)

    # basic spine
    book.spine = ['nav',c1] + chaps

    epub.write_epub('Jernkorset.epub', book, {})
    def save2epub(self, input):
        """
        文件名称数组
        """
        book = epub.EpubBook()
        book.set_title(self.name)
        book.set_language('cn')
        book.add_author('jsp')
        # basic spine
        book.spine = ['nav']  # 内容
        btoc = []  # 章节
        index = 0
        for html in input:
            content = BeautifulSoup(open(html, 'r', encoding='UTF-8'),
                                    "html.parser")
            sbook = self.name
            stitle = content.body.center.h1.string
            # print(stitle)
            c1 = epub.EpubHtml(title=stitle, file_name=html)
            c1.content = "<h1>'+{1}+'</h1><p>{0}</p>".format(
                content.body.div, stitle)
            # print(c1.content)
            book.add_item(c1)
            book.spine.append(c1)
            btoc.append(c1)
            index += 1
            print(index)

        # 生成目录
        book.toc = (
            epub.Link('intro.xhtml', '封面', 'intro'),  # 目录
            (epub.Section('目录'), btoc))  # 卷标 章节
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())
        # define CSS style
        style = 'BODY {color: white;}'
        nav_css = epub.EpubItem(uid="style_nav",
                                file_name="style/nav.css",
                                media_type="text/css",
                                content=style)
        # add CSS file
        book.add_item(nav_css)
        # write to the file
        epub.write_epub(self.name + '.epub', book, {})
Ejemplo n.º 29
0
Archivo: core.py Proyecto: x4d3/lirix
def write_epub(songs):
    

    book = epub.EpubBook()
    
    # set metadata
    book.set_identifier('id123456')
    book.set_title('Sample book')
    book.set_language('en')
    
    book.add_author('Author Authorowski')
    book.add_author('Danko Bananko', file_as='Gospodin Danko Bananko', role='ill', uid='coauthor')
    
    for song in songs:
    
        # create chapter
        c1 = epub.EpubHtml(title=song.artist, file_name='chap_01.xhtml', lang='en')
        c1.content=u'<h1>Intro heading</h1><p>Žaba je skočila u baru.</p>'
        
        # add chapter
        book.add_item(c1)
        
        # define Table Of Contents
        book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),
                    (epub.Section('Simple book'),
                     (c1, ))
        )
        
    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    
    # define CSS style
    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
    
    # add CSS file
    book.add_item(nav_css)
    
    # basic spine
    book.spine = ['nav', c1]
    
    # write to the file
    epub.write_epub('test.epub', book, {})
Ejemplo n.º 30
0
def m(book):
    p_green("[I] Saving in epub...")
    p_green("[I] Meta and information generation...")
    characters = book["characters"]
    bookr = epub.EpubBook()
    id_gen = "wattpad" + str(book["id"])
    bookr.set_identifier(id_gen)
    bookr.set_title(book["title"])
    bookr.set_language(book["description"])
    bookr.add_author(book["authors"])
    bookr.add_item(epub.EpubNcx())
    bookr.add_item(epub.EpubNav())
    bookr.set_cover("cover.jpg", book["cover"])
    book_spine = ['cover', 'nav']
    p_green("[I] Characters generation...")
    book_characters = []
    count_characters = 1
    for one_char in characters:
        print('[{c_num}/{c_all}] Generation "{chapter_title}": {chapter_id}'.
              format(c_num=str(count_characters),
                     c_all=str(len(characters) + 1),
                     chapter_title=one_char["title"],
                     chapter_id=one_char["id"]))
        capt = chapter_gen(one_char["text"])
        captr = epub.EpubHtml(title=one_char["title"],
                              file_name='chap_' + str(count_characters) +
                              '.xhtml',
                              lang='hr')
        count_characters += 1
        captr.content = capt["text"]
        book_spine.append(captr)
        book_characters.append(captr)
        bookr.add_item(captr)
    bookr.toc = (epub.Link('chap_01.xhtml', 'Introduction',
                           'intro'), (epub.Section('Simple book'),
                                      tuple(book_characters)))
    p_green("[I] Saving to epub...")
    save_name = os.getcwd() + "/downloads/" + str(
        book["id"]) + " - " + save_file.rename_valid_f(book["title"]) + ".epub"
    bookr.spine = book_spine
    epub.write_epub(save_name, bookr, {})
    p_green("[I] Saved to epub")