gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
How can I make a slice of PDF-file (from startpage to endpage) using python?
- User
How can I make a slice of PDF-file (from start_page to end_page) using python?
- Assistant
How can I make a slice of PDF-file (from start_page to end_page) using python?
To create a slice of a PDF file (i.e., extract certain pages from one PDF and save them as a new PDF) using Python, you can use the PyPDF2 library. This library allows you to easily manipulate PDF files. If you don't have it installed yet, you can install it via pip:
pip install PyPDF2
Here's a sample script to extract pages from a PDF file and create a new PDF file with just those pages:
import PyPDF2
def slice_pdf(input_pdf_path, output_pdf_path, start_page, end_page):
# Open the input PDF file in read-binary mode
with open(input_pdf_path, 'rb') as input_file:
# Create a PDF reader object
pdf_reader = PyPDF2.PdfReader(input_file)
# Create a PDF writer object
pdf_writer = PyPDF2.PdfWriter()
# Adjusting page numbers to 0-based index for slicing
for page in range(start_page-1, end_page):
if page < len(pdf_reader.pages): # Check if the page exists
pdf_writer.add_page(pdf_reader.pages[page])
else:
print(f"Page {page+1} does not exist in the input PDF.")
# Write the sliced pages to a new PDF file
with open(output_pdf_path, 'wb') as output_file:
pdf_writer.write(output_file)
print(f"Sliced PDF created: {output_pdf_path}")
# Example usage
input_pdf = 'input.pdf' # Path to your input PDF
output_pdf = 'output.pdf' # Path where you want to save the sliced PDF
start_page = 1 # Starting page (1-based index)
end_page = 5 # Ending page (1-based index)
slice_pdf(input_pdf, output_pdf, start_page, end_page)
PyPDF2 library.slice_pdf function takes four arguments: the path to the input PDF, the path for the output PDF, the starting page, and the ending page.PdfReader object for reading the input PDF and a PdfWriter object for writing the output PDF.Make sure to replace 'input.pdf' and 'output.pdf' with your actual file paths!
Not yet included in a published release.