用Python(Django)将PDF转换为二进制文件

2024-04-29 07:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要提供一个PDF到浏览器,它是从API返回的二进制文件。在

我使用的是python2.7、django1.5和requests

我按照Django docs中的建议安装了ReportLab。我还得到了以下示例:

response = HttpResponse(content_type="application/pdf")
response["Content-Disposition"] = "inline; filename=a_test_document.pdf"

p = canvas.Canvas(response)

p.drawString(100, 500, "Hello world")

p.showPage()
p.save()

return response

不过,这只允许我在自己的PDF上绘图。有没有办法把二进制文件转换成PDF格式?我查看了reportlab文档以及其他一些解决方案,但没有看到任何明确的东西。在


Tags: 文件djangoapi示例docspdfresponse二进制
2条回答

为了生成PDF,您可以使用xhtml2pdf库。

函数返回response object,只需传递模板名称、上下文数据和pdfname。在

def fetch_resources(uri, rel):
    """
    Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
    `uri` is the href attribute from the html link element.
    `rel` gives a relative path, but it's not used here.

    """
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
                            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))
    else:
        path = os.path.join(settings.STATIC_ROOT,
                            uri.replace(settings.STATIC_URL, ""))

        if not os.path.isfile(path):
            path = os.path.join(settings.MEDIA_ROOT,
                                uri.replace(settings.MEDIA_URL, ""))

            if not os.path.isfile(path):
                raise UnsupportedMediaPathException(
                                    'media urls must start with %s or %s' % (
                                    settings.MEDIA_ROOT, settings.STATIC_ROOT))

    return path

def render_to_pdf_response(template_name, context=None, pdfname='test.pdf'):
  file_object = HttpResponse(mimetype='application/pdf')
  file_object['Content-Disposition'] = 'attachment; filename=%s' % pdfname
  template = get_template(template_name)
  html = template.render(Context(context))
  pisa.CreatePDF(html.encode("UTF-8"), file_object , encoding='UTF-8',
                 link_callback=fetch_resources)
  return file_object

以下是安装说明:https://pypi.python.org/pypi/xhtml2pdf/

看起来你正在尝试更新现有的PDF,而不是简单地创建一个新的。在这种情况下,this answer可能就是您要找的。总结一下他的解决方案:

  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(text.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

另一方面,如果您不确定接收到的二进制文件的文件类型(在您的示例中不太可能,但值得一提),可以使用名为^{}的东西。这是一个未经测试的潜在示例:

In [2]: import magic
In [3]: m = magic.Magic(mime=True)
In [4]: m.from_file('/home/culebron/Documents/chapter2.pdf')
Out[4]: 'pdf'

根据最终输出,您可以确定:

  1. 是否为PDF格式
  2. 如果是这样,如何应用您所需的更改或与当前PDF文档合并。在
  3. 如果没有,如何将内容写入画布。在

相关问题 更多 >