0

How do I add continuous line numbers to the left margin using pyfpdf or any other pdf creation library? What I want is something similar to a MS Word document with line numbers in the left margin, where every line is numbered.

max_max_mir
  • 1,494
  • 3
  • 20
  • 36
  • Please do search online docs before asking a question here. And post the code that you have tried even if it is not complete. Refer to this [pyfpdf doc](https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html) for the line numbers code. – Lakshmi Swetha G Jun 14 '19 at 06:38

1 Answers1

0

I have tried adding line numbers to left margin using PyPDF2.

# Importing module
import PyPDF2

# Creating object for pdf
pdfFileObj = open('/home/proton/Desktop/py.pdf','rb')

# Opening pdf
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

# Reading and printing total number of pages in the pdf
print("Number of pages:-"+str(pdfReader.numPages))
num = pdfReader.numPages

# Now I will read every page and all the lines of that page in pdf
i =0
while(i<num):
    line_number = 1
    pageObj = pdfReader.getPage(i)
    page_text=pageObj.extractText().strip().split('\n')
    for page_line in page_text:
        print(line_number,page_line)
        line_number+=1
    i= i+1

The above code prints all the line in the pdf along with the line number at left side. If you are looking for any inbuilt function which can add line number in a pdf then answer is "No" . You have to manually add it.

In case, you want to write a new pdf with line numbers you can use PyPDF2.PdfFilewriter() for this, Using this function of PyPDF2 you can write the new pdf file with line numbers Hope this helps :)

In this, i have printed only lines in one page with line numbers enter image description here

0xPrateek
  • 1,158
  • 10
  • 28