0

I want to show Table of contents of a PDF, as I am creating a PDFViewer using PySimpleGUI. I don't know if there is some other option that I can use for creating Table of contents other than TreeData().

My table of contents is a nested-list and it look something like this:

[1, 'Cover', 1]
[1, 'PART ONE OVERVIEW', 25]
[2, 'Chapter 1 Introduction', 27]
[3, '1.1 What Operating Systems Do', 28]
[3, '1.2 Computer-System Organization', 31]
[3, '1.3 Computer-System Architecture', 36]
[2, 'Chapter 2 Operating-System Structures', 79]
[3, '2.1 Operating-System Services', 79]
[3, '2.2 User and Operating-System Interface', 82]
[3, '2.3 System Calls', 86]
[1, 'PART TWO PROCESS MANAGEMENT', 127]
[2, 'Chapter 3 Processes', 129]
[3, '3.1 Process Concept', 129]

Now, I can't figure out how to loop through this list and put everything where it should be. For example, given list should look something like this:

Cover
PART ONE OVERVIEW
    Chapter 1 Introduction
        1.1 What Operating Systems Do
        1.2 Computer-System Organization
        1.3 Computer-System Architecture
    Chapter 2 Operating-System Structures
        2.1 Operating-System Services
        ....

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26

1 Answers1

0

With help of recursion, I was able to achieve my objective. I am sharing that function so that future visitors have the solution right away.

def create_toc(self, contents, parent, phead):
    cons = iter(contents)
    for content in cons:
        i = contents.index(content)
        head, text = content[0], content[1]

        if head == phead:
            i += 1
            key = ''.join(text.split())
            self.TOC_tree.insert(parent, key, text, content[2])
        else:
            j = i
            while True:
                j += 1
                if j < len(contents) and contents[j][0] != phead:
                    next(cons, None)
                else:
                    break
            self.create_toc(contents[i:j], key, head)

You first have to create a sg.TreeData() object and then insert Node to it. First call to this function would be like this:

create_toc(toc, "", toc[0][0])
Zain Arshad
  • 1,885
  • 1
  • 11
  • 26