script - Randomly reorder pages in PDF document

06
2014-04
  • synaptik

    I'm looking for a series of commands to randomize the order of pages in an existing PDF document.

  • Answers
  • synaptik

    Turns out, there's a nice python library pyPDF which can be used in the following script to randomize the order of pages in a PDF document.

    The script below, call it mixpdf, creates a copy of an input PDF file with randomly reordered pages when called by the statement mixpdf myinputfile.pdf.

    #!/usr/bin/python
    
    import sys
    import random
    
    from pyPdf import PdfFileWriter, PdfFileReader
    
    # read input pdf and instantiate output pdf
    output = PdfFileWriter()
    input1 = PdfFileReader(file(sys.argv[1],"rb"))
    
    # construct and shuffle page number list
    pages = list(range(input1.getNumPages()))
    random.shuffle(pages)
    
    # display new sequence
    print 'Reordering pages according to sequence:'
    print pages
    
    # add the new sequence of pages to output pdf
    for page in pages:
        output.addPage(input1.getPage(page))
    
    # write the output pdf to file
    outputStream = file(sys.argv[1]+'-mixed.pdf','wb')
    output.write(outputStream)
    outputStream.close()
    

  • Related Question

    Convert office document to PDF with horizontal page in the middle
  • ianix

    I'm using CutePDF to convert a Word Document to PDF, but the document has one page in the middle with a horizontal page layout and the PDF doesn't get the horizontal page. Is there a way / tool I can use so I can get the PDF as I'd want?


  • Related Answers
  • R. Martinho Fernandes

    If you are using Office 2007, update to SP2. Under the "Save As" submenu you will find "PDF or XPS". It works really good.