from fastapi import APIRouter, UploadFile, File, HTTPException, Security from fastapi.responses import FileResponse from pypdf import PdfReader, PdfWriter import os import shutil import tempfile # Define the APIRouter object router = APIRouter( prefix="/pdf", tags=["PDF Manipulation"], ) @router.post("/merge") async def merge_pdfs(files: list[UploadFile] = File(description="List of PDFs to merge")): """ Merges multiple uploaded PDF files into a single PDF. """ if len(files) < 2: raise HTTPException(status_code=400, detail="Please upload at least two PDF files to merge.") pdf_writer = PdfWriter() # Create a temporary directory to store files with tempfile.TemporaryDirectory() as temp_dir: output_path = os.path.join(temp_dir, "merged_output.pdf") for file in files: # Save the uploaded file temporarily temp_file_path = os.path.join(temp_dir, file.filename) with open(temp_file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) # Read and append pages try: reader = PdfReader(temp_file_path) for page in reader.pages: pdf_writer.add_page(page) except Exception as e: raise HTTPException(status_code=500, detail=f"Error reading PDF file {file.filename}: {e}") # Write the merged PDF to the output path with open(output_path, "wb") as output_file: pdf_writer.write(output_file) # Return the merged file as a response return FileResponse(output_path, media_type="application/pdf", filename="merged_document.pdf") @router.post("/rotate") async def rotate_pdf( file: UploadFile = File(description="PDF file to rotate"), degrees: int = 90 # Default rotation is 90 degrees clockwise ): """ Rotates all pages of a single PDF by a specified degree (90, 180, or 270). """ if degrees not in [90, 180, 270]: raise HTTPException(status_code=400, detail="Rotation must be 90, 180, or 270 degrees.") pdf_writer = PdfWriter() with tempfile.TemporaryDirectory() as temp_dir: input_path = os.path.join(temp_dir, file.filename) output_path = os.path.join(temp_dir, "rotated_output.pdf") # Save the uploaded file temporarily with open(input_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) # Read, rotate, and write try: reader = PdfReader(input_path) for page in reader.pages: page.rotate(degrees) pdf_writer.add_page(page) except Exception as e: raise HTTPException(status_code=500, detail=f"Error processing PDF: {e}") # Write the rotated PDF with open(output_path, "wb") as output_file: pdf_writer.write(output_file) return FileResponse(output_path, media_type="application/pdf", filename=f"rotated_{degrees}.pdf")