Getting in python in advance the number of pages after printing a document

642 views Asked by At

My printer does not support two-sides printing, therefore I make a simple script in Python based on lpr utility. It prints documents page by page with delays, during which I'm turning papers manually:

from sys import argv
from subprocess import run

assert(len(argv) == 2)

i = 1
try:
  while True:
    opt = 'page-ranges={}'.format(i)
    i += 1
    print(run(['lpr', '-o', opt, argv[1]]))
    f = input('> Ready to print next page?\n'
              '(Press ENTER or CTRL+C to exit) ')
except KeyboardInterrupt:
  print()

The problem is I don't know in advance the number of pages of the final printed document, so I don't know when I should interrupt while loop.

Maybe is there solution that helps me get number of resulting pages?

P.S. I'm using macOS Sierra 10.12.2 and A4 papers.

1

There are 1 answers

1
Shijo On

Counting pdf

from pyPdf import PdfFileReader
pdf = PdfFileReader(open('path/to/file.pdf','rb'))
pdf.getNumPages()

Counting docs

from win32com.client import Dispatch
#open Word
word = Dispatch('Word.Application')
word.Visible = False
word = word.Documents.Open(doc_path)

#get number of sheets
word.Repaginate()
num_of_sheets = word.ComputeStatistics(2)

refer the below pages for more details thanks to @Josh & @a_guest

pyPDF - Retrieve page numbers from document

Number of pages of a word document with Python