Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.

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?

like image 657
everybodyHEALS Avatar asked Mar 14 '23 20:03

everybodyHEALS


1 Answers

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.

First, I give my pdf file a name:

pdf_name = number + ".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)

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)
....

And that's it.

like image 171
everybodyHEALS Avatar answered Mar 17 '23 09:03

everybodyHEALS