我正在使用 Django 制作一个与吉他和弦表相关的 Web 应用程序。其中一项功能是能够从和弦表生成 PDF 并下载。我正在使用 Weasyprint 生成 PDF,但遇到一个问题,该 View 没有下载文件,而是显示了非常长的数字序列。这是我的 View 函数:
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")
当我运行代码时,我得到的只是一个显示 53,635 位数字的空网页。
就其值(value)而言,我有一个类似的 View 函数,除了没有 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")
关于python - 使用 Weasyprint 创建文件响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68385270/