Home > database >  How to choose where to save the PDF file generated (Python and FPDF)
How to choose where to save the PDF file generated (Python and FPDF)

Time:12-16

I am working on a project that requires this function to save a previous processed text as a PDF. And it has been successful. Though, i want to prompt a "save as..." for the user to pick where can he save the PDF generated, i have tried with I,D,F,S that is on the documentation of the library, but to no avail.

#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") 

CodePudding user response:

All you need to do is specify the directory in pdf.output function as well. Here's the modified function:

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)

Note that the directory that you are saving the file needs to exist, otherwise pdf.output will throw FileNotFoundError

Usage:

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"))
  • Related