PDFkit直接写入HTTP响应

时间:2016-04-01 13:38:39

标签: python pdfkit

我有一个我没有写访问权限的服务器,我想用pdfkit生成一个pdf,只是将其内容写入HTTP响应,而不首先将文件保存到服务器中的临时文件。以下代码不会工作

import cgitb
cgitb.enable()
print "Content-Type: application/pdf;\n"

import base64
from io import BytesIO
import sys
import pdfkit

data=pdfkit.from_string("asfddsgsdfg", False, {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'orientation': 'Landscape'
})

sys.stdout.write(data)

1 个答案:

答案 0 :(得分:2)

我的Django项目中的一些代码作为示例:

import pdfkit

def program2pdf(filename):

    programconfig = ProgramConfig.get_solo()
    programconfig.downloaded += 1
    programconfig.save()

    config = pdfkit.configuration(wkhtmltopdf=settings.PDF_WKHTMLTOPDF)

    content = render_to_string(
        'program/item2pdf.html', {
            'events': Event.objects.all(), 
            'abs_path': settings.PDF_ADDRESS,
            'programconfig': programconfig
        }
    )

    pdf = pdfkit.PDFKit(content, "string", configuration=config).to_pdf()

    response = HttpResponse(pdf)
    response['Content-Type'] = 'application/pdf'
    response['Content-disposition'] = 'attachment;filename='
    response['Content-disposition'] += programconfig.get_filename

    return response