User Tools

Site Tools


notes:use_page_ranges_in_pypdf2_pdffilemerger

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
notes:use_page_ranges_in_pypdf2_pdffilemerger [2017/11/02 21:22] – created adminnotes:use_page_ranges_in_pypdf2_pdffilemerger [2018/09/08 07:16] (current) admin
Line 4: Line 4:
 If you want to catenate multiple pages using expressions you can use a [[https://pythonhosted.org/PyPDF2/Easy%20Concatenation%20Script.html#page-range|Page Range expression]]. If you want to catenate multiple pages using expressions you can use a [[https://pythonhosted.org/PyPDF2/Easy%20Concatenation%20Script.html#page-range|Page Range expression]].
  
-Remember to import the PageRange class+To specify page ranges, you need to import the PageRange class
   from PyPDF2 import PdfFileMerger, PageRange   from PyPDF2 import PdfFileMerger, PageRange
  
-then you can specify the range as a PageRange() object. For example, the range from page 131 (**REMEMBER: page indices start with zero.!**) to the last one: +then you can specify the range as a PageRange() object. For example, the range from page 13 (**REMEMBER: page indices start with zero.!**) to the last one can be written
-  merger.append(pdf, pages=PageRange('130:-1'))+  merger.append(inpdf, pages=PageRange('13:-1'))
  
 More page range expression examples follows, if you want to play a bit with them: More page range expression examples follows, if you want to play a bit with them:
Line 21: Line 21:
     1:10:   1 3 5 7 9                2::-1     2 1 0.     1:10:   1 3 5 7 9                2::-1     2 1 0.
     ::-1      all pages in reverse order.     ::-1      all pages in reverse order.
 +
 +See below for a complete working python script with PyPDF2 and page ranges. Just set the in/out filenames, the starting/ending page numbers and run the script:
 +
 +  from PyPDF2 import PdfFileMerger, PdfFileReader, PageRange
 +  
 +  infn = "infilename.pdf"
 +  outfn = "outfilename.pdf"
 +  startpage = 5 #set starting page in the pdf -1 (i.e. here we want to start from page 6)
 +  endpage = -1  #last page
 +  
 +  srcfile = PdfFileReader(infn, 'rb')
 +  merger = PdfFileMerger()
 +  page_range = str(startpage) + ':' + str(endpage)
 +  merger.append(srcfile, pages=PageRange(page_range))
 +  merger.write(outfn)
 +
 +And if you are using Ubuntu, remember to install pypdf2 package first
 +  sudo apt install python3-pypdf2 
notes/use_page_ranges_in_pypdf2_pdffilemerger.1509657758.txt.gz · Last modified: 2017/11/02 21:22 by admin