FastAPI + PyPDF2 搭建 PDF 合并/拆分 Web 服务(含完整源码) 日常工作经常遇到需要合并多个 PDF 或从大 PDF 中提取某些页面的需求。虽然有很多在线工具但上传文件到第三方服务器总有隐私顾虑。今天我们就用 Python 的 FastAPI 和 PyPDF 库自己搭建一个本地运行的 PDF 工具服务。功能合并 PDF上传多个 PDF 文件自动合并为一个拆分 PDF上传一个 PDF按页拆分为独立文件打包为 ZIP 下载内存处理所有操作在内存中完成不写临时文件轻量部署单文件pip install 即可运行完整代码fromfastapiimportFastAPI,UploadFile,File,HTTPExceptionfromfastapi.responsesimportFileResponsefrompypdfimportPdfReader,PdfWriterimportioimportzipfile appFastAPI()app.get(/health)asyncdefhealth():return{status:ok}app.post(/merge)asyncdefmerge_pdfs(files:list[UploadFile]File(...)):ifnotfiles:raiseHTTPException(status_code400,detailNo files uploaded)writerPdfWriter()forfinfiles:ifnotf.filename.lower().endswith(.pdf):raiseHTTPException(status_code400,detailfFile {f.filename} is not a PDF)contentawaitf.read()readerPdfReader(io.BytesIO(content))forpageinreader.pages:writer.add_page(page)outputio.BytesIO()writer.write(output)output.seek(0)returnFileResponse(output,media_typeapplication/pdf,filenamemerged.pdf)app.post(/split)asyncdefsplit_pdf(file:UploadFileFile(...)):ifnotfile.filename.lower().endswith(.pdf):raiseHTTPException(status_code400,detailUploaded file is not a PDF)contentawaitfile.read()readerPdfReader(io.BytesIO(content))iflen(reader.pages)0:raiseHTTPException(status_code400,detailPDF has no pages)zip_bufferio.BytesIO()withzipfile.ZipFile(zip_buffer,w,zipfile.ZIP_DEFLATED)aszf:fori,pageinenumerate(reader.pages):writerPdfWriter()writer.add_page(page)page_bytesio.BytesIO()writer.write(page_bytes)page_bytes.seek(0)zf.writestr(fpage_{i1:04d}.pdf,page_bytes.getvalue())zip_buffer.seek(0)returnFileResponse(zip_buffer,media_typeapplication/zip,filenamesplit_pages.zip)if__name____main__:importuvicorn uvicorn.run(app,host0.0.0.0,port8765)运行方式 pip install fastapi uvicorn pypdf python-multipart python main.py 启动后访问 即可测试。## 代码要点1.内存处理使用 io.BytesIO 代替临时文件速度快且无磁盘残留2.错误处理校验文件类型、检查空 PDF3.pypdf 库PyPDF2 的继承者更现代、维护更活跃---需要类似的自定义工具我在爱发电提供编程服务赞助后帮你写代码 https://afdian.com/a/my-worker发完后把文章链接给我我帮你记下来后续可以继续发更多引流文章。_