PDFkit 直接写入 HTTP 响应
PDFkit write directly to the HTTP response
我有一台没有写入权限的服务器,我想用 pdfkit 生成一个 pdf 并将其内容写入 HTTP 响应,而不先将文件保存到下面 server.The 中的临时文件代码无效
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)
例如我的 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
我有一台没有写入权限的服务器,我想用 pdfkit 生成一个 pdf 并将其内容写入 HTTP 响应,而不先将文件保存到下面 server.The 中的临时文件代码无效
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)
例如我的 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