Python reportlab 用画布保存到指定位置 [英] Python reportlab save with canvas to specified location
问题描述
我想知道如何将我的脚本保存到桌面.这是我的代码:
I am wondering how I can make my script save to the Desktop. Here's my code:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Image
import csv
import os
data_file = "hata.csv"
def import_data(data_file):
inv_data = csv.reader(open(data_file, "r"))
for row in inv_data:
var1 = row[0]
# do more stuff
pdf_file = os.path.abspath("~/Desktop/%s.pdf" % var1)
generate_pdf(variable, pdf_file)
def generate_pdf(variable, file_name):
c = canvas.Canvas(file_name, pagesize=letter)
# do some stuff with my variables
c.setFont("Helvetica", 40, leading=None)
c.drawString(150, 2300, var1)
c.showPage()
c.save()
import_data(data_file)
所以这很完美,它保存/创建了我想要的 PDF - 但在脚本的目录中.相反,我想将其保存到桌面.
So this works perfectly, and it saves/creates the PDF I want -- but in the directory of the script. I would instead like to save it to, say, the Desktop.
当我研究发现os.path.abspath
时,我以为我解决了;但我收到以下错误
When I researched and found os.path.abspath
, I thought I solved it; but I receive the following error
File "/usr/local/lib/python3.4/site-packages/reportlab/pdfbase/pdfdoc.py", line 218, in SaveToFile
f = open(filename, "wb")
FileNotFoundError: [Errno 2] No such file or directory: '/Users/TARDIS/Desktop/tests/~/Desktop/00001.pdf'
它告诉我它正在尝试从我脚本的主文件夹开始保存.我如何让它看到外面的东西?
which tells me that it's trying to save starting from my script's home folder. How do I get it to see outside of that?
推荐答案
在使用不同方法进行多次尝试和错误后,所有方法都有缺点,我想出了一个解决方案,并想把它张贴在这里以供后人使用.我对编程很陌生,所以如果这对更有经验的人来说很明显,我深表歉意.
After much trial and error using different methods that all had drawbacks, I came up with a solution and figured I'd post it here for posterity. I'm rather new to programming so apologies if this is obvious to the more experienced.
首先,我为我的 pdf 文件命名:
First, I give my pdf file a name:
pdf_name = number + ".pdf"
然后,我找到当前用户的桌面路径(假设我不知道用户名是什么,这是问题的原始根源)并创建一个路径,以便pdf可以将被保存在那里.
Then, I find the path to the Desktop for current user (given that I don't know what the user name will be, which was the original root of the problem) and create a path to it so that the pdf can be to be saved there.
save_name = os.path.join(os.path.expanduser("~"), "Desktop/", pdf_name)
最后,它传递给了我的 pdf 生成函数:
Finally, that's passed in to my pdf generation function:
...
save_name = ....
generate_pdf(variable, save_name)
def generate_pdf(variable, save_name):
c = canvas.Canvas(save_name, pagesize=letter)
....
就是这样.
这篇关于Python reportlab 用画布保存到指定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!