在Django中通过HTTP响应在浏览器新标签查看FPDF PDF报错求助
问题分析与修复方案
你的代码存在几个关键问题,导致无法在浏览器新标签页正常显示PDF:
- 多余的FPDF实例化:你先创建了
FPDF对象又立刻覆盖,这行代码完全没用,还可能干扰自定义类的初始化。 pdf.output()的使用错误:默认调用output()会直接输出内容到标准输出,而非返回二进制数据给HttpResponse。需要用output(dest='S')来获取PDF的字节内容。- 返回对象错误:HttpResponse需要接收二进制数据,而不是FPDF实例。
- 缺少Content-Disposition头部:要让浏览器在新标签页打开PDF,需指定
inline类型的响应头部。
修复后的代码如下:
class PDFWithHeaderFooter(FPDF): def header(self): # 添加页眉内容 self.set_font('Arial', 'B', 12) self.cell(0, 10, 'Your Header Text', 0, 1, 'C') def footer(self): # 添加页脚内容 self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, 'Page %s' % self.page_no(), 0, 0, 'C') @login_required(login_url='/') def Print_Quote(request, pk): id = Quote.objects.get(id = pk) term = id.terms.all() quote_item = Quote_item.objects.filter( quotes = id ) sub_total = quote_item.aggregate(Sum('sub_total')) gst_total = quote_item.aggregate(Sum('gst_total')) total = quote_item.aggregate(Sum('total')) # 直接实例化自定义PDF类并指定格式 pdf = PDFWithHeaderFooter(format='letter') pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.cell(40, 10, 'Hello, World!') # 获取PDF的二进制内容 pdf_content = pdf.output(dest='S') # 创建响应,设置正确的内容类型和头部 response = HttpResponse(pdf_content, content_type='application/pdf') # 指定inline让浏览器在新标签页打开 response['Content-Disposition'] = 'inline; filename="quote.pdf"' return response
内容的提问来源于stack exchange,提问作者shyam rathod
相关产品推荐
相关产品推荐

