File size: 2,496 Bytes
62e45ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4da081b
 
62e45ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os
from ebooklib import epub
from fpdf import FPDF

class BookBuilder:
    def __init__(self, title, author, description=""):
        self.title = title
        self.author = author
        self.description = description
        self.chapters = []

    def add_chapter(self, title, content):
        self.chapters.append({"title": title, "content": content})

    def generate_epub(self, output_path):
        book = epub.EpubBook()
        book.set_identifier("id123456")
        book.set_title(self.title)
        book.set_language("en")
        book.add_author(self.author)
        book.add_metadata("DC", "description", self.description)

        spine = ["nav"]
        for i, ch in enumerate(self.chapters):
            chapter = epub.EpubHtml(title=ch["title"], file_name=f"chap_{i+1}.xhtml", lang="en")
            content_html = ch["content"].replace("\n", "</p><p>")
            chapter.content = f"<h1>{ch['title']}</h1><p>{content_html}</p>"
            book.add_item(chapter)
            spine.append(chapter)

        book.add_item(epub.EpubNav())
        book.add_item(epub.EpubNcx())
        book.spine = spine
        epub.write_epub(output_path, book, {})
        return output_path

    def generate_pdf(self, output_path):
        pdf = FPDF()
        pdf.set_auto_page_break(auto=True, margin=15)
        pdf.add_page()
        
        # Title Page
        pdf.set_font("Arial", "B", 24)
        pdf.cell(200, 40, self.title, ln=True, align="C")
        pdf.set_font("Arial", "I", 16)
        pdf.cell(200, 10, f"By {self.author}", ln=True, align="C")
        pdf.ln(20)
        
        # Chapters
        for ch in self.chapters:
            pdf.add_page()
            pdf.set_font("Arial", "B", 18)
            pdf.cell(0, 10, ch["title"], ln=True)
            pdf.ln(10)
            pdf.set_font("Arial", "", 12)
            pdf.multi_cell(0, 10, ch["content"])
            
        pdf.output(output_path)
        return output_path

def create_ebook_files(title, author, content_list, base_name="ebook"):
    """
    Helper to create both formats.
    content_list: List of dicts with 'title' and 'content'.
    """
    builder = BookBuilder(title, author)
    for item in content_list:
        builder.add_chapter(item["title"], item["content"])
    
    os.makedirs("exports", exist_ok=True)
    epub_file = builder.generate_epub(f"exports/{base_name}.epub")
    pdf_file = builder.generate_pdf(f"exports/{base_name}.pdf")
    
    return epub_file, pdf_file