手始めに、ePubからメタデータや目次データ、画像データのパスなどを表示するプログラムをサンプルコードなどを参考に書いてみました。
EbookLibというPythonのライブラリを使っています。https://github.com/aerkalov/ebooklib
EbookLibの使い方の参考になれば幸いです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ebooklib | |
from ebooklib import epub, utils | |
book = epub.read_epub('.<.epubファイルのパス>') | |
# メタデータの読み込み | |
# タイトル | |
title = book.get_metadata('DC', 'title') | |
print('タイトル:', title) | |
# 執筆者 | |
creator = book.get_metadata('DC', 'creator') | |
print('執筆者:', creator) | |
# 発行者 | |
publisher = book.get_metadata('DC', 'publisher') | |
print('発行者:', publisher) | |
# 言語 | |
language = book.get_metadata('DC', 'language') | |
print('言語:', language) | |
# 発行日 | |
date = book.get_metadata('DC', 'date') | |
print('発行日:', date) | |
print('==================================') | |
# 目次(Table of contents) | |
for item in book.toc: | |
print(item.title, item.href) | |
print('==================================') | |
# カバー画像 | |
cover_image = list(book.get_items_of_type(ebooklib.ITEM_COVER))[0] | |
print('カバー画像 : ', cover_image.get_name()) | |
print('==================================') | |
# ページ画像 | |
for item in book.get_items_of_type(ebooklib.ITEM_DOCUMENT): | |
body = utils.parse_html_string(item.get_body_content()) | |
for elem in body.iter(): | |
if 'xlink:href' in elem.attrib: | |
print(item.get_name(), ':', elem.attrib.get('xlink:href')) |
出力例:
他にもEpubのメタデータを扱う便利なパッケージがありました。
epub-metaです。https://github.com/paulocheque/epub-meta
これなら数行で著者情報と目次データを抽出できます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import epub_meta | |
from pprint import pprint | |
import xml.etree.ElementTree as ET | |
# 作者情報や目次などのメタデータ | |
book = epub_meta.get_epub_metadata('.<.epubファイルのパス>', read_cover_image=False, read_toc=True) | |
pprint(book) | |
# 画像データのパス | |
opf_xml = epub_meta.get_epub_opf_xml(epub_path) | |
image_paths = [[],[]] | |
manifest = ET.fromstring(opf_xml.decode()).find('.//{{{0}}}manifest'.format('http://www.idpf.org/2007/opf')) | |
for item in manifest.findall('.//{{{0}}}item'.format('http://www.idpf.org/2007/opf')): | |
if item.attrib['media-type'] == 'application/xhtml+xml': | |
image_paths[0].append(item.attrib['href']) | |
if item.attrib['media-type'] == 'image/jpeg': | |
image_paths[1].append(item.attrib['href']) | |
for path in list(map(list, zip(*image_paths))): | |
if path[0].startswith(('Text/part', 'text/p-')): | |
print(path[0], ':', path[1]) |
出力例:
続き
【Python】img2pdfを使って複数画像をPDFに変換する
前回 からだいぶ時間が経ちましたが、目標である「漫画などの固定レイアウトEpubを目次付きPDFに変換するプログラムを作る」を達成するため、今回は前段階として、Pythonで連番を付けた複数画像ファイルをPDFに変換する方法を検討しました。 PythonのPDF関連のライブラ...
0 件のコメント:
コメントを投稿