zzZ5 / Html2Epub

将 html链接, html文件 或 html文本 转换成 epub文件.
MIT License
23 stars 6 forks source link

Function create_epub to receive complete path #6

Open sjehuda opened 8 months ago

sjehuda commented 8 months ago

Related to https://github.com/wcember/pypub/issues/30

Greetings

I'm attempting to utilize Html2Epub with my Slixfeed XMPP news bot.

def generate_epub(text, pathname):
    pathname = pathname.split("/")
    filename = pathname.pop()
    directory = "/".join(pathname)
    book = xml2epub.Epub(filename)
    chapter0 = xml2epub.create_chapter_from_string(text, strict=False)
    book.add_chapter(chapter0)
    book.create_epub(directory, epub_name=filename)

The result would yield a filename that was not originally intended.

If my intention is to have filename_001.epub, it would turn into filename001.

This results in my program failing to locate the generated file.

To solve this, I import module os and rename the file.

def generate_epub(text, pathname):
    pathname_list = pathname.split("/")
    filename = pathname_list.pop()
    directory = "/".join(pathname_list)
    book = xml2epub.Epub(filename)
    chapter0 = xml2epub.create_chapter_from_string(text, strict=False)
    book.add_chapter(chapter0)
    filename_tmp = "slixfeedepub"
    book.create_epub(directory, epub_name=filename_tmp)
    pathname_tmp = os.path.join(directory, filename_tmp) + ".epub"
    os.rename(pathname_tmp, pathname)

Please allow passing a complete path, as it would make workflow more consistent.


Here are other functions I use for other filetypes.

def generate_html(text, filename):
    with open(filename, 'w') as file:
        file.write(text)

def generate_pdf(text, filename):
    pdfkit.from_string(text, filename)

def generate_markdown(text, filename):
    h2m = html2text.HTML2Text()
    markdown = h2m.handle(text)
    with open(filename, 'w') as file:
        file.write(markdown)

Notice that all filenames passed are utilized with no change.