DEV Community

Gia
Gia

Posted on • Edited on

How can I Merge the Selected Page Ranges of PDFs via Python

Merging PDFs is a great way to avoid constantly opening files when you have multiple related files that need to be processed. You can easily merge them using a PDF editor. However, if you only want to merge specific pages from these PDFs in batches, maybe you can use an excellent PDF library to do that. In this passage, I will show you how to merge specific page ranges of PDFs via Python.

Library

Spire.PDF for Python

Installation

You can install Spire.PDF for Python in Visual Studio Code by performing the following steps:

  • Download and install Python.
  • Open Visual Studio Code, click “Extensions”, search for “Python” and then install it.
  • Click “Explorer” > “NO FOLRDER OPENED” > “Open Folder”.
  • Choose a folder.
  • Add a “.py” file to this folder and name it whatever you like.
  • Click “Terminal” > “New Terminal”.
  • Last, input the following commands
pip install Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Reference Code

1.Import required modules or libraries.

from spire.pdf import *
from spire.pdf.common import *
Enter fullscreen mode Exit fullscreen mode

2.Created a list containing paths to PDF files.

file1 = "C:/Users/Administrator/Desktop/PDF-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDF-2.pdf "
file3 = "C:/Users/Administrator/Desktop/PDF-3.pdf "
files = [file1, file2, file3]
Enter fullscreen mode Exit fullscreen mode

3.Then, use the PdfDocument class to load each PDF file as a PdfDocument object and add them to the list.

pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))
Enter fullscreen mode Exit fullscreen mode

4.Create an object of PdfDocument class and insert the selected pages from the loaded PDFs into the new document.

newPdf = PdfDocument()
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)
Enter fullscreen mode Exit fullscreen mode

5.Save the new PDF document

newPdf.SaveToFile("output/MergePages.pdf")
Enter fullscreen mode Exit fullscreen mode

Here I take three two-page PDF files as an example and merge their first page, second page and 1-2 pages respectively.

Image description

If you want to know more about merging PDFs programmatically, please refer to the following link.
Python: Merge PDF Documents

Top comments (0)