zoukankan      html  css  js  c++  java
  • Django分析之导出为PDF文件

           最近在公司一直忙着做exe安装包,以及为程序添加新功能,好久没有继续来写关于Django的东西了….难得这个周末清闲,来了解了解Django的一些小功能也是极好的了~

           那今天就来看看在Django的视图中将页面导出为pdf格式的功能吧。那么动态生成pdf的好处是什么呢?你可以为不同目的的用户创建定制的pdf。那么是如何实现的呢?它使用的是Python开源的pdf库---ReportLab

           安装ReportLab

           你可以从http://www.reportlab.com/software/opensource/rl-toolkit/download/下载安装ReportLab库,有个用户指南来解释如何安装它,或者你也可以使用pip来安装。

    sudo pip install reportlab

            测试你是否成功安装好了ReportLab

    >>> import reportlab

            如果这个命令没有报任何错误的话就说明ReportLab已经成功安装好了。

            Django动态生成pdf的关键是ReportLab关于文件的API接口,APi接口是文件对象,而Django的HttpResponse对象也是文件对象,这就相通了。

            那我们就来一个“Hello World”的例子:

    from reportlab.pdfgen import canvas
    from django.http import HttpResponse
    
    def some_view(request):
        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    
        # Create the PDF object, using the response object as its "file."
        p = canvas.Canvas(response)
    
        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        p.drawString(100, 100, "Hello world.")
    
        # Close the PDF object cleanly, and we're done.
        p.showPage()
        p.save()
        return response

          这里response得到一个特殊的MIME类型  'application/pdf’这个标示告诉浏览器这是一个PDF文件,而非一个HTML文件,如果你不这样的话浏览器会解释输出为HTML的文件格式,这样会导致在窗口展示十分的丑陋。

          同时,response会得到一个额外的内容,这其中包括了PDF文件的名称,当然这个文件名是任意的,你可以使用浏览器的另存为来给它取任何的名字。这这个例子中紧接着会弹出对话框来确认如何处理文档。最后最重要的是使用showPage()方法和save()方法来保存导出的PDf文件了。

          注意:ReportLab是非线程安全的。

          那现在我们来看看复杂的PDF文件,如果你要用ReportLab创建一个复杂的PDF文档,那就要考虑使用IO类来辅助作为一个临时的中转了,这个库提供了一个十分有效的文件类的对象接口,下面我们就来重写上面那个“Hello World”:

    from io import BytesIO
    from reportlab.pdfgen import canvas
    from django.http import HttpResponse
    
    def some_view(request):
        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    
        buffer = BytesIO()
    
        # Create the PDF object, using the BytesIO object as its "file."
        p = canvas.Canvas(buffer)
    
        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        p.drawString(100, 100, "Hello world.")
    
        # Close the PDF object cleanly.
        p.showPage()
        p.save()
    
        # Get the value of the BytesIO buffer and write it to the response.
        pdf = buffer.getvalue()
        buffer.close()
        response.write(pdf)
        return response

         当然,除了ReportLab库之外还有很多优秀的Python第三方库,例如:

    PDFlib:是Django绑定了另外一个Python库,还有诸如“XHTML2PDF”库,还有就是使用“HTMLdoc”,它是一个将HTML转成PDF的命令行,但是它没有接口,只能使用Python的输入输出界面。

  • 相关阅读:
    pat乙级1034
    getline()读入一整行
    c++ 输入split
    13.缓存、三级缓存、内存溢出、AsyncTask
    12、json、GridView、缓存
    11.webview、shareSDK
    10.下拉刷新、加载更多、标记已读、轮播条、缓存
    9.indicate、xutils、json
    8.滑动事件处理
    7.ViewPagerIndicator
  • 原文地址:https://www.cnblogs.com/fuhuixiang/p/4131084.html
Copyright © 2011-2022 走看看