我正在研究一个项目,该项目需要此函数将以前处理过的文本保存为PDF。它已经取得了成功。不过,我想提示"另存为…"为了让用户选择在哪里可以保存生成的PDF,我已经尝试了i,D,F,S,这是在库的文档中,但无济于事。
#Text to PDF function
def textPDF(text):
a4=210
chW=2.45
wTex=a4/chW
pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.set_auto_page_break(True, 10)
pdf.add_page()
pdf.set_font(family="Arial", size=15)
splitted = text.split('.')
for line in splitted:
lines = textwrap.wrap(line, wTex)
if len(lines) == 0:
pdf.ln()
for dot in lines:
pdf.cell(0, 5.5, dot, ln=1)
pdf.output("Summary.pdf")
您所需要做的就是在pdf.output
函数中指定目录。下面是修改后的函数:
from fpdf import FPDF
import textwrap
def textPDF(text, dest):
a4=210
chW=2.45
wTex=a4/chW
pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.set_auto_page_break(True, 10)
pdf.add_page()
pdf.set_font(family="Arial", size=15)
splitted = text.split('.')
for line in splitted:
lines = textwrap.wrap(line, wTex)
if len(lines) == 0:
pdf.ln()
for dot in lines:
pdf.cell(0, 5.5, dot, ln=1)
pdf.output(dest)
注意保存文件的目录必须存在,否则pdf.output
会抛出FileNotFoundError
用法:
textPDF("hi", "Summary.pdf")
textPDF("hi", "hello/Summary.pdf")
textPDF("hi", "hello\Summary.pdf")
# use os.path.join to ensure the same function works on multiple OSs
import os # Alternatively you can use pathlib as well
textPDF("hi", os.path.join("hello", "Summary.pdf"))