I'm trying to develop a simple app for displaying each page of a Pdf file. I start by adding a container and a button. The Pdf file's full path(absolute path + file name) is given to the variable fullname
. The file is converted into a list of PIL images using the pdf2image library.
I'm trying to set the first image(first element of the list) as the content of the container after a button is clicked.
Here is the code:
import flet as ft
import pdf2image
def main(page: ft.Page):
fullname = r'Your Full Path To the Doc.pdf'
viewer = pdf2image.convert_from_path(fullname)
def btn_Click(e):
cont.content = ft.Image(src = viewer[0],
fit=ft.ImageFit.FILL,
)
page.update()
cont = ft.Container(height = 0.4*page.height,
width = 0.4 * page.width,
border=ft.border.all(3, ft.colors.RED),)
btn = ft.IconButton(
icon=ft.icons.UPLOAD_FILE,
on_click=btn_Click,
icon_size=35,)
page.add(ft.Column([cont, btn],
horizontal_alignment="center"))
page.window_maximized = True
page.horizontal_alignment = "center"
page.scroll = ft.ScrollMode.AUTO
page.update()
ft.app(target=main, assets_dir="assets")
Why is nothing is displayed in the container and no error shown?
I moddify code to use base64 image src with flet
i don't not why, but flet
working bad with normal image src and use src_base64 is better choise.
import flet as ft
import pdf2image
from io import BytesIO
from PIL import Image as image
import numpy as np
import base64
import pypdf
i = 0
def main(page: ft.Page):
fullname = r'D:\BDOT_2015.pdf'
src_pdf = pypdf.PdfReader(fullname)
def btn_Click(e):
global i
if i >= len(src_pdf.pages):
i = 0
out = pypdf.PdfWriter()
out.add_page(src_pdf.pages[i])
out.write('t.pdf')
viewer = pdf2image.convert_from_path('t.pdf',
poppler_path=r'D:\Python\PDF-ORGANIZER\PDF2TIFF\poppler-24.02.0\Library\bin')
viewer64 = []
for view in viewer:
arr = np.asarray(view)
pil_img = image.fromarray(arr)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
pic = base64.b64encode(buff.getvalue()).decode("utf-8")
viewer64.append(pic)
cont.content = ft.Image(src_base64=viewer64[0],
fit=ft.ImageFit.FILL,
)
page.update()
cont = ft.Container(expand=1,
border=ft.border.all(3, ft.colors.RED),)
btn = ft.IconButton(
icon=ft.icons.UPLOAD_FILE,
on_click=lambda e: btn_Click(e),
icon_size=35,)
def btn_Next(e):
global i
i += 1
btn_Click(e)
btn_n = ft.IconButton(
icon=ft.icons.NAVIGATE_NEXT,
on_click=lambda e: btn_Next(e),
icon_size=35,)
page.add(ft.Column([cont, btn, btn_n],
horizontal_alignment=ft.MainAxisAlignment.CENTER))
page.window_maximized = True
page.horizontal_alignment = ft.MainAxisAlignment.CENTER
page.scroll = ft.ScrollMode.AUTO
page.update()
ft.app(target=main, assets_dir="assets")
Now your code working as i think you expect.