The line item.content = item.content.replace(b"<body>", b'<body class="custom">') does…
- User
The line item.content = item.content.replace(b"", b'') does not do anything to apply Fast_Sans.ttf to the output.epub. Modify the code for generating CSS so the Fast_Sans.ttf font get applied to output.epub.
import os
from ebooklib import epub
proj_root = '/home/rayhanmuktader/Workspace/projects/personal/epub' existing_epub = f'{proj_root}/input/existing.epub'
Load the existing EPUB file
book = epub.read_epub(existing_epub)
Add the custom font file to the "fonts" folder
font_filename = 'Fast_Sans.ttf' font_path = f'{proj_root}/fonts/{font_filename}' epub_font_path = os.path.join('fonts', font_filename)
Create an EpubItem for the font file
font_item = epub.EpubItem(uid="font1", file_name=epub_font_path, media_type="application/x-font-ttf") with open(font_path, 'rb') as font_file: font_item.set_content(font_file.read())
Add the font file to the book
book.add_item(font_item)
Create a CSS file that uses the custom font
css_content = f'@font-face {{ font-family: "Fast_Sans"; src: url("{epub_font_path}"); }}' css_item = epub.EpubItem(uid="style1", file_name="styles/styles.css", media_type="text/css", content=css_content)
Add the CSS file to the book
book.add_item(css_item)
Apply the CSS file to all HTML items in the book
for item in book.get_items(): if isinstance(item, epub.EpubHtml): item.add_link(href='styles/styles.css', rel='stylesheet', type='text/css') item.content = item.content.replace(b"", b'')
Save the modified EPUB file
epub.write_epub(f'{proj_root}/output/output.epub', book)
- Assistant
To apply the Fast_Sans.ttf font to the output.epub file, you need to modify the CSS content and the line of code where the CSS file is added to the book.
First, create the CSS content with the font declaration:
python