1

我有一个 Javascript 应用程序。当我单击一个按钮时,使用 POST 请求将一个 JSON 对象发送到 Django-Pisa 远程服务器,以从 JSON 对象创建一个 PDF 文件。我必须使用 POST,因为 JSON 长度超过了 GET 允许的长度。

这是我的 Django 渲染函数

@csrf_exempt
def render_to_pdf(request):
  request_data = ast.literal_eval(request.POST.keys()[0])
  template_src = templates_map.TEMPLATES_MAP[request_data['intervention']]
  context_json = request_data['data']
  template = get_template(template_src)
  context = Context(context_json)
  html  = template.render(context)
  result = StringIO.StringIO()

  pdf = pisa.pisaDocument(StringIO.StringIO(html), result,link_callback=fetch_resources)

  if not pdf.err:
    return HttpResponse(result.getvalue(), content_type='application/pdf')
  return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

在 javascript 方面,这是点击事件

try {
  jQuery.post('http://pdfgen-server/pdfgen', JSON.stringify(requestData), 
    function(data) {
      var w = window.open();
      w.document.write(data);
    });
}
catch (err) {
  ; //error handling
}

当我单击时,我得到的是一个新窗口,内容,而不是呈现的 PDF 文件,实际上是 PDF 内容(就像我打开记事本查看 PDF 文件一样)。新浏览器窗口中的前几行:

%PDF-1.4 % ReportLab 生成的 PDF 文档http://www.reportlab.com % 'BasicFonts': class PDFDictionary 1 0 obj % 标准字体字典 << /F1 2 0 R /F2 3 0 R /F3 4 0 R /F4 5 0 R >> endobj % 'F1': 类 PDFType1Font 2 0 obj % Font Helvetica << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj % 'F2' : class PDFType1Font 3 0 obj % Font Times-Roman << /BaseFont /Times-

请让我知道如何解决这个问题?

谢谢

4

1 回答 1

1

我实际上不确定这会起作用,但试试看 -

try {
  jQuery.post('http://pdfgen-server/pdfgen', JSON.stringify(requestData), 
    function(data) {
      window.open("data:application/pdf," + escape(data));
    });
}
catch (err) {
  ; //error handling
}

(如果它确实有效,那么归功于这个问题

于 2013-03-08T18:41:53.920 回答