使用Weasyprint创建文件响应



我正在用Django制作一个与吉他和弦表相关的web应用程序。其中一个功能是能够从和弦表生成PDF并下载。我正在使用Weasyprint生成PDF,但我遇到了一个问题,视图中没有下载文件,而是显示了一个很长的数字序列。这是我的视图功能:

def download_pdf(request, song_id):
song = get_object_or_404(Song, pk=song_id)
song.chordsheet.open("r")
chordsheet_html = HTML(string=chopro2html(song.chordsheet.read())) # Generates HTML from a text file, not relevant here
chordsheet_css = CSS(string="div.chords-lyrics-line {n"
"   display: flex;n"
"   font-family: Roboto Mono, monospace;n"
"}n")
song.chordsheet.close()
return FileResponse(chordsheet_html.write_pdf(stylesheets=[chordsheet_css]), as_attachment=True, filename=song.title + "_" + song.artist + ".pdf")

当我运行代码时,我得到的只是一个显示53635位数字的空网页。

值得一提的是,我有一个类似的视图功能,除了没有PDF生成(下载原始文件(之外,它也能做同样的事情,而且效果很好。我该怎么解决这个问题?

我找到了一个解决方案-我需要在响应之前将PDF写入缓冲区。

import io
def download_pdf(request, song_id):
buffer = io.BytesIO()

# ...
chordsheet_html.write_pdf(buffer, stylesheets=[chordsheet_css])
buffer.seek(0)
return FileResponse(buffer, as_attachment=True, filename=song.title + "_" + song.artist + ".pdf")

最新更新