0% found this document useful (0 votes)
14 views2 pages

PDF Stack with Merge Functionality

Uploaded by

13anmolbhullar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

PDF Stack with Merge Functionality

Uploaded by

13anmolbhullar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Code: PDF Stack with Merge Functionality

This Python script implements a PDF stack that allows you to: - Push PDF files onto a stack (stored
as raw bytes). - Pop PDFs from the stack (LIFO order). - Peek at the size of the top PDF. - Merge
all PDFs in the stack into one combined PDF file using PyPDF2.

# PDF Stack with Merge Functionality


# pip install PyPDF2

from PyPDF2 import PdfMerger

class PDFStack:
def __init__(self):
[Link] = []

def push(self, pdf_path: str):


"""Push a PDF file (as bytes) onto the stack."""
with open(pdf_path, "rb") as f:
data = [Link]()
[Link](data)
print(f"Pushed: {pdf_path}")

def pop(self, out_path: str):


"""Pop the last pushed PDF and save it to out_path."""
if not [Link]:
print("Stack is empty!")
return
data = [Link]()
with open(out_path, "wb") as f:
[Link](data)
print(f"Popped to: {out_path}")

def peek(self):
"""Preview size of the top PDF in bytes (without removing it)."""
if not [Link]:
print("Stack is empty!")
return None
return len([Link][-1])

def is_empty(self):
return len([Link]) == 0

def merge_stack(self, out_path: str):


"""Merge all PDFs currently in the stack into one PDF file."""
if not [Link]:
print("Stack is empty! Nothing to merge.")
return

merger = PdfMerger()
for idx, data in enumerate([Link]):
import io
[Link]([Link](data))
print(f"Added PDF {idx+1} to merge")

[Link](out_path)
[Link]()
print(f"Merged PDF saved as: {out_path}")

# Example usage
if __name__ == "__main__":
pdf_stack = PDFStack()

# Push multiple PDFs


pdf_stack.push("[Link]")
pdf_stack.push("[Link]")
pdf_stack.push("[Link]")

# Merge them into one file


pdf_stack.merge_stack("[Link]")

# Pop the last one (LIFO)


pdf_stack.pop("last_popped.pdf")

You might also like