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, {})
def generateEPUB(filename, title, info, chapters, settings): # Create empty ePUB file book = epub.EpubBook() bookDir = path.join(settings['BooksDirectory'], info['title']) # Metadata book.set_title(title) book.set_language('en') book.add_author(info['author']) # Cover book.set_cover('cover.jpg', open(path.join(bookDir, 'cover.jpg'), 'rb').read()) # Empty Table of contents toc = {} # Chapter for chp in chapters: # Create chapter newChapter = epub.EpubHtml(title=chp['name'], file_name=chp['name'] + '.xhtml', lang='en') newChapter.content = open( path.join(bookDir, '{0}.{1}.html'.format(chp['volume'], chp['name'])), 'r').read() # Add to book book.add_item(newChapter) # Add to table of contents if toc.get(chp['volume']) is None: toc[chp['volume']] = [] toc[chp['volume']].append(newChapter) # Create table of contents book.toc = [(epub.Section(key), toc[key]) for key in toc.keys()] # Flatten Table of contents and create spine book.spine = ['nav'] + [chp for vol in toc.values() for chp in vol] book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) epub.write_epub(filename, book)
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)
def write_epub(epub_obj, series_name, volume_name, chapters, output_dir): epub_obj.set_identifier(series_name + volume_name) epub_obj.set_title(series_name + " " + volume_name) epub_obj.toc = chapters epub_obj.add_item(epub.EpubNav()) epub_obj.add_item(epub.EpubNcx()) epub_obj.spine = chapters epub_obj.add_item( epub.EpubItem(uid="style_default", file_name="style/default.css", media_type="text/css", content='BODY { text-align: justify;}')) try: epub.write_epub(f"{output_dir}[{series_name}] {volume_name}.epub", epub_obj) except: print(traceback.format_exc())
def bind_epub_book(app, chapters, volume=''): book_title = (app.crawler.novel_title + ' ' + volume).strip() logger.debug('Binding epub: %s', book_title) # Create book book = epub.EpubBook() book.set_language('en') book.set_title(book_title) book.add_author(app.crawler.novel_author) book.set_identifier(app.output_path + volume) book.set_direction('rtl' if app.crawler.is_rtl else 'default') # Create intro page cover_image = make_cover_image(app) if cover_image: book.add_item(cover_image) # end if intro_page = make_intro_page(app, cover_image) book.add_item(intro_page) # Create book spine try: book.set_cover('image.jpg', open(app.book_cover, 'rb').read()) book.spine = ['cover', intro_page, 'nav'] except Exception: book.spine = [intro_page, 'nav'] logger.warn('No cover image') # end if # Create chapters make_chapters(book, chapters) book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # Save epub file epub_path = os.path.join(app.output_path, 'epub') file_name = app.good_file_name if not app.no_append_after_filename: file_name += ' ' + volume # end if file_path = os.path.join(epub_path, file_name + '.epub') logger.debug('Writing %s', file_path) os.makedirs(epub_path, exist_ok=True) epub.write_epub(file_path, book, {}) print('Created: %s.epub' % file_name) return file_path
def create_book(sections): """Receive the sections list and create the epub file.""" print('Creating ebook...') book = epub.EpubBook() # set metadata book.set_identifier('gpp') book.set_title('Game Programming Patterns') book.set_language('en') book.add_author('Robert Nystrom') # create chapters chapters = [] for section_index, section in enumerate(sections): for link_index, link in enumerate(section): title = link['title'] if link_index > 0: title = ' - {}'.format(title) chapter = epub.EpubHtml(title=title, file_name=link['file_name'], media_type='application/xhtml+xml', content=link['content']) book.add_item(chapter) chapters.append(chapter) for image_item in link['images_items']: book.add_item(image_item) # book's Table of contents book.toc = chapters # add default NCX and Nav file book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # book's spine book.spine = chapters if not os.path.isdir(EPUB_PATH): os.mkdir(EPUB_PATH) file_path = os.path.join(EPUB_PATH, 'game-programming-patterns.epub') epub.write_epub(file_path, book, {}) print('Book created: {}'.format(file_path))
def save_book(self, title: str, author: str, bin_mode: bool = False, save_path: str = '', index: int = None): # fix issue #8 def remove_special_symbols(s: str, refill: str = '_') -> str: symbols = """"';:<>./\\+`~!@#$%^&*""" for symbol in symbols: s = s.replace(symbol, refill) return s # noinspection PyStringFormat def generate_filename(index_: int): return '%s - %s%s.epub' % (*[ remove_special_symbols(s) if not self.raw_book_name else s for s in [title, author] ], '' if index is None else f'({index_})') if bin_mode is True: stream = io.BytesIO() epub.write_epub(stream, self.book) stream.seek(0) return stream.read() if index is None: self.book.toc = self.toc # 添加目录信息 self.book.add_item(epub.EpubNcx()) self.book.add_item(epub.EpubNav()) # 创建主线,即从头到尾的阅读顺序 self.book.spine = self.spine path = os.path.join(save_path, generate_filename(index_=index)) if os.path.exists(path): if index is None: logger.warning(f"{path} exists, saving to another file...") self.save_book(title, author, bin_mode=bin_mode, save_path=save_path, index=(index + 1 if index is not None else 1)) else: epub.write_epub(path, self.book) logger.warning(f"saved to {generate_filename(index_=index)}")
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, {})
def download_epub(story, output='', message=True): """ Download a story to ePub. :type message: bool """ if output == '': output = "%s_by_%s" % (story.title, story.author) output = output.replace(' ', '-') if output[-5:].lower() != ".epub": output += ".epub" if message: print 'Downloading \'%s\' to %s...' % (story.title, output) # actual book build book = epub.EpubBook() # set metadata book.set_identifier(str(story.id)) book.set_title(story.title) book.set_language('en') book.add_author(story.author) # create chapters toc = [] section = [] spine = ['nav'] for chapter in story.get_chapters(): if message: print 'Adding Chapter %d: %s' % (chapter.number, chapter.title) # add chapters c = epub.EpubHtml(title=chapter.title, file_name='chapter_%d.xhtml' % (chapter.number), lang='en') #c.add_link(href='style/default.css', rel='stylesheet', type='text/css') c.content = chapter.raw_text book.add_item(c) spine.append(c) # no idea what this does toc.append(c) # add the chapter to the table of contents book.toc = toc book.add_item(epub.EpubNcx()) # add some other stuff book.add_item(epub.EpubNav()) book.spine = spine if message: print 'Compiling ePub...' # write epub epub.write_epub(output, book)
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 create_epub(file, blog_id, title, html_content, author, href, published, updated): html_chapter = epub.EpubHtml(title=title, file_name=f"html.xhtml", lang='en') html_chapter.content = html_content meta_content = f""" <h1>Meta Data</h1> <p>Author: {author}</p> <p>Url: {href}</p> <p>Published: {published}</p> <p>Updated: {updated}</p> """ meta_chapter = epub.EpubHtml(title='Meta Data', file_name=f"meta.xhtml", lang='en') meta_chapter.content = meta_content chapters = [html_chapter, meta_chapter] book = epub.EpubBook() # add metadata book.set_identifier(blog_id) book.set_title(title) book.set_language('en') book.add_author(author) # add chapters to the book for chapter in chapters: book.add_item(chapter) # create table of contents book.toc = chapters # add navigation files book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # create spine book.spine = chapters # create epub file epub.write_epub(file, book, {})
def finalizeBook(self, outputFileName): # 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 self.book.add_item(nav_css) self.book.add_item(epub.EpubNcx()) self.book.add_item(epub.EpubNav()) self.book.spine = ['nav', *self.chapters] epub.write_epub(outputFileName, self.book, {})
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, {})
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, {})
def create_epub(self, workdir): self.epub_book.set_cover("cover.jpg", self.book.get_binary_content("cover.jpg"), False) for chapter in self.book.get_book_chapters(): self.add_chapter(chapter) for image in self.book.get_images(): self.add_image(image) for style in self.book.get_styles(): self.add_style(style) self.epub_book.add_item(epub.EpubNcx()) self.epub_book.add_item(epub.EpubNav()) self.epub_book.toc = EpubManager.convert_toc(self.book.get_toc()) self.write_to_file(workdir)
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")
def convert_to_epub(rss): """Convert rss feed to epub book.""" logging.info('Converting to epub') feed_title = rss.get('parsed', {}).get('feed', {}).get('title', 'unknown') book = epub.EpubBook() book.set_identifier('123') book.set_title(feed_title) book.add_author(feed_title) book.spine = ['nav'] toc = [] html_format = ('<h3>{title}</h3>' '<h5>Date: {date}</h5>' '<h5>Link: <a href={link}>{link}</a></h5>' '{raw_description}') for index, topic in enumerate(rss['topics']): file_name = '{}.xhtml'.format(index) chapter = epub.EpubHtml(title=topic['title'], file_name=file_name) topic['raw_description'] = load_images(book, topic['raw_description']) chapter.content = html_format.format(**topic) book.add_item(chapter) book.spine.append(chapter) toc.append(epub.Section(topic['title'])) toc.append(chapter) book.toc = tuple(toc) book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) path = rss['args'].output_path if not path: path = os.path.join(os.getcwd(), 'rss_news.epub') epub.write_epub(path, book, {}) if not os.path.isfile(path): raise Exception('Cannot create file with that path')
def save(): # Add Navigation Files book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # Defines CSS Style style = 'p { text-align : left; }' nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style) # Adds CSS File book.add_item(nav_css) # Location Where File Will Be Saved # Default Location Will Be The Place Where This Script Is Located # To Change, # 1 - Add The Location Inside The Empty pathToLocation # Example 1 - Windows : # pathToLocation = 'C:\\Users\\Adam\\Documents\\' # Notice The Extra \ To Be Added Along With Every Original - This Is Compulsory For Every \ # Example 2 - Unix/POSIX Based(OS X, Linux, Free BSD etc) : # pathToLocation = '/home/Adam/Documents/' # Notice That No Extra / Are Added Along With Original # OR # 2 - Move This Script To, And Run From The Location To Be Saved pathToLocation = '' downloadDetails = '"' + title + '_' + str(start) + '_' + str( counter) + '.epub"' saveLocation = pathToLocation + downloadDetails print("Saving . . .") # Saves Your EPUB File epub.write_epub(saveLocation, book, {}) # Location File Got Saved if pathToLocation == '': print("Saved at", os.getcwd(), 'as', downloadDetails) # Example : Saved at /home/Adam/Documents as "The Strongest System_0_3.epub" else: print("Saved at", saveLocation)
def create_book_from_chapters( book_author: str, book_id: str, book_title: str, reddit_chapters: Iterable[Submission]) -> EpubBook: book = epub.EpubBook() book.set_identifier(book_id) book.set_title(book_title) book.add_author(book_author) book.set_language('en') cover = epub.EpubHtml(title=book_title, file_name='cover.xhtml', lang='en') cover.content = "<div><h1>{0}</h1>" \ "<h2><a href=\"https://www.reddit.com/user/{1}\">{1}</a></h2>" \ "{2}</div>".format(book_title, book_author, "Created with the reddit2epub python package") book.add_item(cover) book_chapters = [] # check for title prefix for i, sub in enumerate(reddit_chapters): # create chapter c1 = epub.EpubHtml(title=sub.title, file_name='chap_{}.xhtml'.format(i), lang='en') c1.content = """<h1>{0}</h1> <a href="{1}">Original</a> {2} <a href="{1}">Original</a> """.format(sub.title, sub.shortlink, sub.selftext_html) # add chapter book.add_item(c1) book_chapters.append(c1) # define Table Of Contents book.toc = (book_chapters) # add default NCX and Nav file book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # basic spine spine = [cover, 'nav'] spine.extend(book_chapters) # is used to generate the toc at the start book.spine = spine return book
def EnterQuestion(self, url): html = self.__useragent(url) soup = BeautifulSoup(html) questiontitle = soup.title.string print(questiontitle) i = 0 for div in soup.findAll('div', {'class': ' zm-editable-content clearfix'}): i += 1 filename = 'chap_' + str(i) + '.xhtml' print(filename) c1 = epub.EpubHtml(title=filename, file_name=filename, lang='zh') c1.content = div self.book.add_item(c1) self.book.toc = (epub.Link(filename, filename, 'intro'), (epub.Section('Simple book'), (c1, ))) self.book.add_item(epub.EpubNcx()) self.book.add_item(epub.EpubNav()) self.book.spine = ['nav', c1]
def write(self): r""" 输出电子书 :return: 无 """ if self.with_catalog: self.book.toc = self.chapters self.book.add_item(epub.EpubNcx()) self.book.add_item(epub.EpubNav()) if self.with_catalog: self.book.spine = ["nav"] + self.chapters else: self.book.spine = self.chapters remove_strs = r'\/:*?"<>|' write_title = self.title for s in list(remove_strs): write_title = write_title.replace(s, "#") epub.write_epub('./output/%s.epub' % write_title, self.book, {})
def _create_epub(book_title, book_id, bookpath, text): book = epub.EpubBook() book.set_language('en') book.set_identifier(book_id) book.set_title(book_title) content = epub.EpubHtml(title='News', file_name='content.xhtml') content.set_content(text) book.add_item(content) book.toc = (content,) book.spine = [content] book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) if os.path.isdir(bookpath): epub.write_epub(os.path.join(bookpath, book_id+".epub"), book) elif not os.path.exists(bookpath) or os.path.isfile(bookpath) or os.path.islink(bookpath): epub.write_epub(bookpath, book)
def createGrimoireEpub(destinyGrimoireDefinition, book=epub.EpubBook()): book.set_identifier('destinyGrimoire') book.set_title('Destiny Grimoire') book.set_language('en') book.add_author('Bungie') book.set_cover("cover.jpg", open('resources/cover.jpg', 'rb').read()) book.add_item( epub.EpubItem(uid="style_default", file_name="style/default.css", media_type="text/css", content=DEFAULT_PAGE_STYLE)) dowloadGrimoireImages(destinyGrimoireDefinition) book.toc = addThemeSetsToEbook(book, destinyGrimoireDefinition) book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) epub.write_epub(DEFAULT_BOOK_FILE, book)
def createEpub(self): # Add each chapter object to the book for chap in self.chapters: chap.add_item( default_style ) # Links the css file to each chapter html page in epub self.book.add_item(chap) # Give the table of content the list of chapter objects self.book.toc = (self.chapters) # add navigation files self.book.add_item(epub.EpubNcx()) self.book.add_item(epub.EpubNav()) # add css file nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style) self.book.add_item(nav_css) # create spine, add cover page as first page self.book.spine = ['cover', 'nav'] + self.chapters #Make a valid file name using novel name and chapter information valid_chars = "-_.() %s%s" % ( string.ascii_letters, string.digits ) #Characters allowed in a file name [Characters such as $%"" are not allowed as file names in windows] file = self.novel_name + '.epub' file = ''.join(c for c in file if c in valid_chars) # folder = ''.join(c for c in self.novel_name if c in valid_chars) #check if the folder exists or not # if not os.path.exists(self.storage_path): # os.mkdir(self.storage_path + '/' + folder) # create epub file epub.write_epub(self.storage_path + '/' + file, self.book, {}) print("Wrote Epub to: " + self.storage_path + '/' + file)
def convert_url(self, url): parser_resp = self.parser_client.get_article(url).json() epub_book = epub.EpubBook() epub_book.set_title(parser_resp['title']) epub_book.add_author(parser_resp['author']) content_html = epub.EpubHtml(title=parser_resp['title'], file_name='content.xhtml', content="<h1>{}</h1>\n{}".format( parser_resp['title'], parser_resp['content'])) epub_book.add_item(content_html) epub_book.add_item(epub.EpubNcx()) epub_book.add_item(epub.EpubNav()) # A spine determines the order in which content will be shown epub_book.spine = [content_html] epub.write_epub("{}.epub".format(slugify(parser_resp['title'])), epub_book, dict(plugins=[DownloadImagesPlugin()]))
def make_book(BookName, author, chapters, uuid, filename): book = epub.EpubBook() book.set_identifier(uuid) book.set_title(BookName) book.set_language("en") book.add_author(author) for a in chapters: book.add_item(a) style = 'body { font-family: Times, Times New Roman, serif; } h1 {font-size: 16; font-style: bold;}' 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 = tuple(chapters) book.spine = ['nav'] + chapters book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) epub.write_epub(filename, book)
def main(): print("请输入起点中文网小说URL") print("(形如: https://book.qidian.com/info/<小说id>#Catalog)") novel_url = input("请输入: ") r = s.get(novel_url) soup = BeautifulSoup(r.content, features="html.parser") book_cover_src = soup.find('a', {'id': 'bookImg'}).find('img')['src'] book_info = soup.find('div', {'class': 'book-info'}) book_title = book_info.find('em').string book_author = book_info.find('a').string # get all volumes = soup.find_all('div', {'class': 'volume'}) for volume in volumes: handle_volume(volume) # set title book.set_title(book_title) # set author book.add_author(book_author) # set cover download_image(book_cover_src, "book_cover.jpg") book.set_cover('cover.jpg', open('book_cover.jpg', 'rb').read()) # set book language book.set_language('zh_Hans') # set book's TOC book.toc = epubTOC # add navigation files book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # save book epub.write_epub('book.epub', book) print(book_title + "-" + book_author, end=" ") print("successfully saved to book.epub") print("you can use kindlegen tool to convert epub to mobi") print("for example: `bin/kindlegen book.epub`") print( "(choose executable file in bin/ directory depending on your operating system.)" )
def main(book_link): index = BeautifulSoup( requests.get(book_link, headers=headers).text, 'html.parser') title = get_book_title(index) author = get_author(index) chapters = get_charpters(index) cover_image = get_cover_image(title) book = epub.EpubBook() book.set_identifier(uuid.uuid4().urn) book.set_title(title) book.add_author(author) book.add_metadata( 'DC', 'contributor', 'http://www.digglife.net', {'id': 'contributor'}) book.add_metadata('DC', 'publisher', home, {'id': 'publisher'}) book.add_metadata('DC', 'source', book_link, {'id': 'url'}) book.set_language('zh') if cover_image: book.set_cover('cover.jpg', cover_image, create_page=False) items = [] for i, c in enumerate(chapters): time.sleep(5) link, text = c chapter_html = BeautifulSoup(requests.get(link).text, 'html.parser') chapter_title, chapter_contents = generate_chapter_contents( chapter_html) chapter_epub = make_epub_html( 'chapter_{}.xhtml'.format(i), chapter_title, chapter_contents) book.add_item(chapter_epub) items.append(chapter_epub) book.add_item(epub.EpubNcx()) nav = epub.EpubNav() book.add_item(nav) book.toc = items book.spine = [nav] + items epub.write_epub('{}.epub'.format(title), book)
def make_epub(conf: dict, out: Path): b_title = conf["book"]["title"] book.set_identifier(b_title.lower().replace(" ", "-")) book.set_title(b_title) book.set_language("en") book.add_author(conf["book"]["author"]) book.add_metadata("DC", "creator", "Created with wikipub") if "cover_image_url" in conf["book"]: url = conf["book"]["cover_image_url"] r = requests.get(url, stream=True) if r.status_code == 200: r.raw.decode_content = True img_path = url.split("/")[-1] book.set_cover(img_path, r.content) book.spine.append("nav") for idx, chapter in enumerate(conf["chapters"]): page = wiki.page(chapter["title"]) if page.exists(): c_title = chapter["title"] print(f"Processing: {c_title}") c_title_stub = c_title.lower().replace(" ", "-") f_name = f"{idx:03}_{c_title_stub}.xhtml" e_ch = epub.EpubHtml(title=c_title, file_name=f_name) e_ch.set_content(page.text) book.add_item(e_ch) book.spine.append(e_ch) book.toc.append(e_ch) # Finish off the book print("Finishing...") book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # Save the book print("Saving...") epub.write_epub(out, book) print(f"Saved as: {out}")
def txt2epub(data, base_store_path): base_name = list(data['index'].keys())[0] data = data['index'][base_name] for volume in data['index']: v_name = volume[0] b_name = base_name + v_name book = epub.EpubBook() chapter_list = [] toc_list = [] path = os.path.join(base_store_path, base_name, 'epub') if not os.path.isdir(path): os.makedirs(path) book.set_identifier('{}{}'.format(b_name, randint(0, 100000000))) book.set_title(b_name) book.add_author(data['author']) book.set_language('en') for c_name in volume[1:]: c_id = str(randint(0, 100000000)) chapter = epub.EpubHtml(title=c_name, file_name=c_id + '.xhtml') with open( os.path.join(base_store_path, base_name, 'txt', v_name, c_name + '.txt'), 'r') as fp: chapter.content = '<h1>{}</h1><br>{}'.format( c_name, fp.read().replace('\n', '<br>')) book.add_item(chapter) chapter_list.append(chapter) toc_list.append(epub.Link(c_id + '.xhtml', c_name, c_id)) book.toc = tuple(toc_list) book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) book.spine = ['nav'] + chapter_list epub.write_epub(os.path.join(path, b_name + '.epub'), book, {})