You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现从Bytes数据在内存生成PDF并在浏览器展示

内存中加载PDF字节数据并在浏览器打开的实现方案

要实现不写入磁盘,直接用数据库返回的bytes类型PDF数据在浏览器打开,核心思路是通过临时HTTP服务器将内存中的字节数据以PDF格式响应给浏览器,具体修改代码如下:

import http.server
import socketserver
import webbrowser
import threading
import time

# 数据库查询逻辑保留
l_statement = "select srno,attachment from dbo.attachments where srno = 1"
sqlcursor.execute(l_statement)

for row in sqlcursor.fetchall():
    pdf_bytes = row[1]
    print(type(pdf_bytes))
    print(pdf_bytes)

    # 自定义HTTP处理器,返回内存中的PDF数据
    class PDFHandler(http.server.SimpleHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-Type', 'application/pdf')
            self.send_header('Content-Length', str(len(pdf_bytes)))
            self.end_headers()
            self.wfile.write(pdf_bytes)

    # 启动临时服务器,自动分配空闲端口
    with socketserver.TCPServer(("", 0), PDFHandler) as httpd:
        port = httpd.server_address[1]
        # 用线程启动服务器,避免阻塞主线程
        server_thread = threading.Thread(target=httpd.serve_forever)
        server_thread.daemon = True
        server_thread.start()

        # 调用浏览器打开临时服务地址
        webbrowser.open_new(f"http://localhost:{port}")
        
        # 等待浏览器加载完成后关闭服务器,可根据实际情况调整等待时长
        time.sleep(2)
        httpd.shutdown()

关键细节说明:

  • 完全跳过磁盘写入步骤,直接复用数据库返回的pdf_bytes字节数据
  • 采用随机端口启动临时HTTP服务,避免固定端口冲突问题
  • 通过线程异步启动服务,防止主线程被阻塞无法执行后续操作
  • 设置Content-Type为application/pdf,确保浏览器正确识别并渲染PDF内容

内容的提问来源于stack exchange,提问作者Kamlesh Dhairyavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:41:04