aerkalov/ebooklib

Images not shown between pages

ianustec opened this issue · 5 comments

Hi,

I'm trying to add an image for each chapters, but I'm not able to do this.

This is my draft code.

Thank in advance.

book = epub.EpubBook()

# add metadata
book.set_identifier(data['BookTitle'].lower().replace(' ', ''))
book.set_title(data['BookTitle'])
book.set_language(data['BookLanguage'])

book.add_author(data['BookAuthor'])

# add cover image
book.set_cover("cover.jpg", open(f'{IMAGES_FOLDER}/cover.png', 'rb').read())


# preface chapter
preface_content = open(f"{OUTPUT_FOLDER}/preface.xhtml", "rb").read()
p1 = epub.EpubHtml(title='Prefazione', file_name='preface.xhtml', lang=data['BookLanguage'], content=preface_content)

# defube style
style = '''BODY { text-align: justify;}'''

default_css = epub.EpubItem(uid="style_default", file_name="style/default.css", media_type="text/css", content=style)
book.add_item(default_css)


image_content0 = open(f'{IMAGES_FOLDER}/section_0.png', 'rb').read()
img0 = epub.EpubImage(uid='image_0', file_name='static/section_0.jpg', media_type='image/jpg', content=image_content0)

# chapter
c0_content = open(f"{OUTPUT_FOLDER}/section_0.xhtml", "rb").read()
c0 = epub.EpubHtml(title=data['Chapters'][0]['BookChapter'], file_name='section_0.xhtml', content=c0_content)
# c2.content='<h1>About this book</h1><p>Helou, this is my book! There are many books, but this one is mine.</p>'
c0.set_language(data['BookLanguage'])
c0.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none')
c0.add_item(default_css)


image_content1 = open(f'{IMAGES_FOLDER}/section_0.png', 'rb').read()
img1 = epub.EpubImage(uid='image_1', file_name='static/section_1.jpg', media_type='image/jpg', content=image_content1)

c1_content = open(f"{OUTPUT_FOLDER}/section_1.xhtml", "rb").read()
c1 = epub.EpubHtml(title=data['Chapters'][1]['BookChapter'], file_name='section_0.xhtml', content=c1_content)
# c2.content='<h1>About this book</h1><p>Helou, this is my book! There are many books, but this one is mine.</p>'
c1.set_language(data['BookLanguage'])
c1.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none')
c1.add_item(default_css)


image_content2 = open(f'{IMAGES_FOLDER}/section_0.png', 'rb').read()
img2 = epub.EpubImage(uid='image_2', file_name='static/section_2.jpg', media_type='image/jpg', content=image_content2)

c2_content = open(f"{OUTPUT_FOLDER}/section_2.xhtml", "rb").read()
c2 = epub.EpubHtml(title=data['Chapters'][2]['BookChapter'], file_name='section_0.xhtml', content=c2_content)
# c2.content='<h1>About this book</h1><p>Helou, this is my book! There are many books, but this one is mine.</p>'
c2.set_language(data['BookLanguage'])
c2.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none')
c2.add_item(default_css)

# add chapters to the book
book.add_item(p1)
book.add_item(img0)
book.add_item(c0)
book.add_item(img1)
book.add_item(c1)
book.add_item(img2)
book.add_item(c2)

# create table of contents
# - add manual link
# - add section
# - add auto created links to chapters

book.toc = (
              epub.Link("preface.xhtml", "Prefazione", "prefazione"),
              epub.Link("section_0.xhtml", data['Chapters'][0]['BookChapter'], data['Chapters'][0]['BookChapter'].lower().replace(' ', '').replace(':', '_')),
              epub.Link("section_1.xhtml", data['Chapters'][1]['BookChapter'], data['Chapters'][1]['BookChapter'].lower().replace(' ', '').replace(':', '_')),
              epub.Link("section_2.xhtml", data['Chapters'][2]['BookChapter'], data['Chapters'][2]['BookChapter'].lower().replace(' ', '').replace(':', '_')),
          )

# add navigation files
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())

# define css style
style = '''
      @namespace epub "http://www.idpf.org/2007/ops";

      body {
          font-family: Cambria, Liberation Serif, Bitstream Vera Serif, Georgia, Times, Times New Roman, serif;
      }

      h2 {
          text-align: left;
          text-transform: uppercase;
          font-weight: 200;     
      }

      ol {
              list-style-type: none;
      }

      ol > li:first-child {
              margin-top: 0.3em;
      }


      nav[epub|type~='toc'] > ol > li > ol  {
          list-style-type:square;
      }


      nav[epub|type~='toc'] > ol > li > ol > li {
              margin-top: 0.3em;
      }
      '''

# add css file
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
book.add_item(nav_css)

# create spine
book.spine = ['nav', p1, c0, c1, c2]

# create epub file
epub.write_epub(f'{OUTPUT_FOLDER}/test.epub', book, {})

In your files like f"{OUTPUT_FOLDER}/section_0.xhtml" do you reference your images with something like ? You create image object and you add it to the book, which is all ok, but then that image has to be references in CSS or HTML files somehow.

Thanks! I'm going to try. 🙏

Hi, I'm here again.

I tried to put img tag in .xhtml file that contains text too.

Checking the .xhtml on browser the image is visible file but not in epub.

c_content = open(f"{OUTPUT_FOLDER}/section_{chapter['BookSectionId']}_{str(i)}.xhtml", "rb").read()
c = epub.EpubHtml(title=f"{chapter['BookChapter']}:{paragraph['BookParagraph']}", file_name=f"section_{chapter['BookSectionId']}_{str(i)}.xhtml", content=c_content)
c.set_language(data['BookLanguage'])
c.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none')
c.add_item(default_css)

I've just tried as example (I suppose), but images are not shown.

In both, the the size of epub is the same 46Mb but images are not shown. They are in PNG format

    els = []
    book_toc = [epub.Link("preface.xhtml", "Prefazione", "prefazione")]

    for chapter in data['Chapters']:

        for i, paragraph in enumerate(chapter['BookParagraphs']):
        
            print(chapter['BookSectionId'])

            # image_content0 = open(f'{IMAGES_FOLDER}/section_0.png', 'rb').read()
            # img0 = epub.EpubImage(uid='image_0', file_name='static/section_0.jpg', media_type='image/jpg', content=image_content0)

            # chapter with image
            c1 = epub.EpubHtml(title=f"{chapter['BookChapter']}:{paragraph['BookParagraph']}", file_name=f"section_{chapter['BookSectionId']}_{str(i)}_img.xhtml")
            c1.set_language(data['BookLanguage'])
            c1.content = u'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
                    <html xmlns="http://www.w3.org/1999/xhtml">
                    <head>
                    <title>''' + chapter['BookChapter'] + '''</title>
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                    <link rel="stylesheet" href="style.css" type="text/css" />
                    <style>
                        h1 {
                            text-align: center;
                            font-variant: small-caps;
                            margin-top: 1em;
                            margin-bottom: 1em;
                        }
                        h2, h3, h4 {
                            text-align: left;
                            font-variant: small-caps;
                            margin-top: 1em;
                            margin-bottom: 1em;
                        }

                        a.noteref {
                            vertical-align: super;
                            position: relative;
                            bottom: 0.5em;
                            font-size: small;
                        }

                        p.note {
                            text-indent: 0px;
                            margin-top: 0.4em;
                            margin-left: 0.2em;
                            font-size: 0.9em;
                        }

                        p.center {
                            text-align: center;
                        }
                        p.right {
                            text-align: right;
                        }

                        p.comment {
                            margin-top: 1em;
                            margin-bottom: 1em;
                            margin-left: 4em;
                            margin-right: 8em;
                            font-size: 0.9em;
                            font-style: italic;
                        }

                        p.noindent {
                            text-indent: 0px;
                        }
                    </style>
                    </head>
                    <body>
                        <img src = "''' + f"{OUTPUT_FOLDER}/images/c{str(chapter['BookSectionId'])}_p{str(i)}.png" + '''" alt = "" srcset = "" / >
                    </body>
                </html>
            '''

            # chapter with image
            image_content = open(f"{OUTPUT_FOLDER}/images/c{str(chapter['BookSectionId'])}_p{str(i)}.png", 'rb').read()
            img = epub.EpubImage(uid=f"image_c{str(chapter['BookSectionId'])}_p{str(i)}", file_name=f"images/c{str(chapter['BookSectionId'])}_p{str(i)}.png", media_type='image/png', content=image_content)

            els.append(c1)
            els.append(img)

            # chapter
            c_content = open(f"{OUTPUT_FOLDER}/section_{chapter['BookSectionId']}_{str(i)}.xhtml", "rb").read()
            c = epub.EpubHtml(title=f"{chapter['BookChapter']}:{paragraph['BookParagraph']}", file_name=f"section_{chapter['BookSectionId']}_{str(i)}.xhtml", content=c_content)
            c.set_language(data['BookLanguage'])
            c.properties.append('rendition:layout-pre-paginated rendition:orientation-landscape rendition:spread-none')
            c.add_item(default_css)

            els.append(c)
            
            book_toc.append(epub.Link(f"section_{chapter['BookSectionId']}_{str(i)}.xhtml", chapter['BookChapter'],
                                 f"{chapter['BookChapter']}_{paragraph['BookParagraph']}".lower().replace(' ', '').replace(':', '_')))
        

    book.add_item(p1)
    for el in els:
        book.add_item(el)

    # create table of contents
    # - add manual link
    # - add section
    # - add auto created links to chapters

    
    book.toc = tuple(book_toc)

Hi.

Ok it works, but how can I center image horizontally?

https://ibb.co/zNwLBCH

I've tried this

img {
    max-width: 100% !important; 
    max-height: 100% !important;
    display: block !important;
    text-align: center !important;
    margin: auto !important;
}