[1117] Remove some pages from a PDF while preserving the bookmarks
To remove the last page from a PDF while preserving the bookmarks, you can use the PyMuPDF library (fitz package) instead of PyPDF2, as PyMuPDF provides better support for handling bookmarks. Here’s how you can do it:
-
Install PyMuPDF:
pip install PyMuPDF -
Import the necessary library:
import fitz # PyMuPDF -
Remove the last page while keeping the bookmarks:
def remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path): # Open the original PDF pdf_document = fitz.open(input_pdf_path) # Remove the last page pdf_document.delete_page(pdf_document.page_count - 1) # Save the modified PDF to a new file pdf_document.save(output_pdf_path) # Example usage input_pdf_path = 'path/to/your/input.pdf' output_pdf_path = 'path/to/your/output.pdf' remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path)
Explanation:
-
Install PyMuPDF:
pip install PyMuPDFThis command installs the
PyMuPDFlibrary. -
Import the necessary library:
import fitz # PyMuPDFThis import brings in the
fitzmodule from thePyMuPDFlibrary. -
Remove the last page while keeping the bookmarks:
def remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path): pdf_document = fitz.open(input_pdf_path) pdf_document.delete_page(pdf_document.page_count - 1) pdf_document.save(output_pdf_path)- fitz.open(): Opens the original PDF file.
- delete_page(): Deletes the last page from the PDF (the index is
page_count - 1because the pages are 0-indexed). - save(): Saves the modified PDF to a new file, preserving the existing bookmarks.
Example: Remove the last page
import fitz # PyMuPDF
def remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path):
# Open the original PDF
pdf_document = fitz.open(input_pdf_path)
# Remove the last page
pdf_document.delete_page(pdf_document.page_count - 1)
# Save the modified PDF to a new file
pdf_document.save(output_pdf_path)
# Example usage
input_pdf_path = 'path/to/your/input.pdf'
output_pdf_path = 'path/to/your/output.pdf'
remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path)
Example: Rmove the last four pages
import fitz # PyMuPDF
def remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path):
# Open the original PDF
pdf_document = fitz.open(input_pdf_path)
# Remove the last four pages
for _ in range(4):
pdf_document.delete_page(pdf_document.page_count - 1)
# Save the modified PDF to a new file
pdf_document.save(output_pdf_path)
# Example usage
input_pdf_path = 'path/to/your/input.pdf'
output_pdf_path = 'path/to/your/output.pdf'
remove_last_page_keep_bookmarks(input_pdf_path, output_pdf_path)
This code will remove the last page from the specified PDF file while preserving the existing bookmarks.
If you have any further questions or need additional assistance, feel free to ask! 😊
浙公网安备 33010602011771号