Home > Back-end >  tkPDFViewer - Open several .pdf in grid not working (display same pdf with a mix of all of them)
tkPDFViewer - Open several .pdf in grid not working (display same pdf with a mix of all of them)

Time:12-11

My goal is to display several PDFs at the same time in tkinter.

My issue is that it seems not possible to open different .pdf at the same time using : tkPDFViewer

The reproducible example is below :

    from tkPDFViewer import tkPDFViewer as pdf

    FramePdfMacro = tk.Frame(self,bg='white')
    FramePdfMacro.pack(expand=True, fill=BOTH,pady=2,padx=2)
    
    FramePdfMacro.grid_rowconfigure(0, weight=1)
    Grid.rowconfigure(FramePdfMacro, 0, weight=1)
    Grid.columnconfigure(FramePdfMacro, 0, weight=1)
    Grid.columnconfigure(FramePdfMacro, 1, weight=1)
    
    PDF1 = pdf.ShowPdf()
    PDFv1 = PDF1.pdf_view(FramePdfMacro, pdf_location = "PDF1.pdf",width = 100, height = 150)
    PDFv1.grid(row=0,column=0,sticky="nsew")    
    
    PDF2 = pdf.ShowPdf()
    PDFv2 = PDF2.pdf_view(FramePdfMacro, pdf_location = "PDF2.pdf",width = 100,height = 150)
    PDFv2.grid(row=0,column=1,sticky="nsew")

Once you run this code you will get twice a mix of those 2 .pdf

Does anyone knows how to display 2 differents .pdf in a same time ?

CodePudding user response:

For current design of tkPDFViewer, you cannot show two PDF files at the same time.

Since tkPDFViewer use pyMuPDF module, you can create your PDF viewer using same module as below:

import tkinter as tk
from tkinter.scrolledtext import ScrolledText
import fitz

class PDFViewer(ScrolledText):
    def show(self, pdf_file):
        self.delete('1.0', 'end') # clear current content
        pdf = fitz.open(pdf_file) # open the PDF file
        self.images = []   # for storing the page images
        for page in pdf:
            pix = page.get_pixmap()
            pix1 = fitz.Pixmap(pix, 0) if pix.alpha else pix
            photo = tk.PhotoImage(data=pix1.tobytes('ppm'))
            # insert into the text box
            self.image_create('end', image=photo)
            self.insert('end', '\n')
            # save the image to avoid garbage collected
            self.images.append(photo)

root = tk.Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure((0,1), weight=1)

pdf1 = PDFViewer(root, width=80, height=30, spacing3=5, bg='blue')
pdf1.grid(row=0, column=0, sticky='nsew')
pdf1.show('test.pdf')

pdf2 = PDFViewer(root, width=80, height=30, spacing3=5, bg='blue')
pdf2.grid(row=0, column=1, sticky='nsew')
pdf2.show('temp.pdf')

root.mainloop()
  • Related