【问题标题】:pdfkit django in digitaloceandigitalocean中的pdfkit django
【发布时间】:2020-02-04 18:00:26
【问题描述】:

pdfkit在本地机器上工作一切正常显示为pdf,但在digitalocean中向服务器发送错误500,为什么?

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.template.loader import get_template
import pdfkit
from .models import Buses

    def pdf(request, id):
        bus = Buses.objects.get(id=id)
        template = get_template('buses/pdf.html')
        html = template.render({'bus': bus})
        options = {
            'page-size': 'Letter',
            'encoding': "UTF-8",
        }

        pdf = pdfkit.from_string(html, False, options)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="{}_{}.pdf"'.format(bus.company, bus.name)

        return response

【问题讨论】:

  • 能否添加错误日志?
  • 对于 PDF 生成,通常需要在 VM 上安装一些二进制文件。您是否安装了所有必需的依赖项?
  • @narendra-choudhary 我只安装 pip pdfkit
  • pdfkit 依赖于 wkhtmltopdf。你安装了 wkhtmltopdf 吗?来源:github.com/JazzCore/python-pdfkit
  • @narendra-choudhary 是的,我安装了 wkhtmltopdf,但是 pdfkit 不起作用?它发送到服务器错误 500

标签: django python-3.x pdfkit


【解决方案1】:

如果您的模板引用了其他文件,您可能需要在选项中设置'enable-local-file-access': True

见:https://github.com/wkhtmltopdf/wkhtmltopdf/issues/4460

【讨论】:

    【解决方案2】:

    我不确定,但您的问题可能是 wkhtmltopdf 的位置 指定 wkhtmltopdf 位置始终是更好的选择。所以在你的数字海洋服务器上——首先安装 wkhtmltopdf——如果你还没有的话。

    这是适用于任何版本的 Ubuntu 的绝佳教程 - https://computingforgeeks.com/install-wkhtmltopdf-on-ubuntu-debian-linux/

    然后在你的命令行上:

    which wkhtmltopdf
    

    记下位置,您的代码将如下所示:

    from django.shortcuts import render, redirect, get_object_or_404
    from django.http import HttpResponse
    from django.template.loader import get_template
    import pdfkit
    from .models import Buses
    
        def pdf(request, id):
            bus = Buses.objects.get(id=id)
            template = get_template('buses/pdf.html')
            html = template.render({'bus': bus})
            options = {
                'page-size': 'Letter',
                'encoding': "UTF-8",
            }
            config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') #use your actual location here
    
    
            pdf = pdfkit.from_string(html, False, configuration=config, options=options)
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="{}_{}.pdf"'.format(bus.company, bus.name)
    
            return response
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多