FB2 (Python package)
| Language | Python 3.10+ |
|---|---|
| License | MIT |
| Repository | github.com/Ae-Mc/FB2 |
| Documentation | README |
| Depends on | pydantic, iso639-lang |
| Read / write | no / yes |
The FB2 package (pip install fb2, imported as FB2) builds FictionBook 2 files from Python objects. You fill a FictionBook2 object with title info (title, authors, annotation, genres, keywords, language, series, cover), document info and chapters, and write() produces a valid FB2 file with images embedded as Base64 binary elements.
It’s a small, focused library for generating books, for example from web novels, scraped articles or Markdown. It doesn’t read FB2 files; for that use PyMuPDF or parse the XML with xml.etree.ElementTree.
Installation#
Shell
pip install fb2
Basic usage: create an FB2 book#
Python
from FB2 import Author, FictionBook2, SimpleChapter
book = FictionBook2()
book.titleInfo.title = "My Book"
book.titleInfo.authors = [Author(firstName="Jane", lastName="Doe")]
book.titleInfo.annotation = "A short example book."
book.titleInfo.genres = ["prose_contemporary"]
book.titleInfo.lang = "en"
book.documentInfo.authors = ["Jane Doe"]
book.documentInfo.version = "1.0"
book.chapters = [
SimpleChapter(title="Chapter 1", content=["First paragraph.", "Second paragraph."]),
SimpleChapter(title="Chapter 2", content=["Another chapter."]),
]
book.write("book.fb2")
Each string in content becomes a <p> paragraph.
How to add a cover image#
Python
from FB2 import Image
with open("cover.jpg", "rb") as f:
book.titleInfo.coverPageImages = [Image(media_type="image/jpeg", content=f.read())]
How to add images inside a chapter#
Put Image objects between paragraphs:
Python
with open("map.png", "rb") as f:
map_image = Image(media_type="image/png", content=f.read())
book.chapters.append(
SimpleChapter(title="Chapter 3", content=["Text before the map.", map_image, "Text after the map."])
)
How to create chapters with subchapters#
Python
from FB2 import ChapterWithSubchapters, SimpleChapter
book.chapters.append(
ChapterWithSubchapters(
title="Part 2",
epigraph=["An epigraph line."],
subchapters=[
SimpleChapter(title="Chapter 4", content=["Text of chapter 4."]),
SimpleChapter(title="Chapter 5", content=["Text of chapter 5."]),
],
)
)
Subchapters become nested <section> elements and appear nested in readers’ tables of contents.
How to set the series#
Python
book.titleInfo.sequences = [("My Series", 2)] # name and number in the series
Tips#
book.write("book.fb2", prettify=True)writes indented XML;str(book)returns the prettified XML as a string.- Use FB2 genre codes from the official list (
sf,detective,prose_classic,nonf_biography, …) so readers can sort the book. - Zip the result into
.fb2.zipwithzipfileto save space; most readers open it directly.