[Python] How do I create and save a text into that PDF file and save it in desktop using...

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am making an mcq generator using AI (for questions based on given paragraph) and I want to save that AI returned text into a PDF file and save it in the user's desktop but I am getting no directory/no permission error.

    I use toga for cross platform. I used a library called reportlab to create the PDF.

    from reportlab.genpdf import canvas

    def pdf_file_question_write(self, widget):
    try:
    os_name = platform.system()
    if os_name == "Windows":
    desktop_path = os.path.join(os.environ['USERPROFILE'], 'Desktop')
    elif os_name in ["Linux", "Darwin"]: # macOS is "Darwin"
    desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
    elif "ANDROID_BOOTLOGO" in os.environ:
    # If running on Android, use the Downloads folder
    desktop_path = "/storage/emulated/0/Download"
    else:
    raise Exception("Unsupported operating system")

    output_path = os.path.join(desktop_path, "MCQ Generator.pdf")

    # Create a PDF and add text
    pdf = canvas.Canvas(output_path)
    pdf.setFont("Helvetica", 12)
    pdf.drawString(100, 800, "Generated Questions:") # Title
    text_lines = str(self.Generated_Question).split("\n") # Split text into lines
    y = 780 # Start position for text
    for line in text_lines:
    pdf.drawString(100, y, line)
    y -= 15 # Move down for the next line
    pdf.save() # Save the PDF
    print(f"PDF saved successfully at: {output_path}")

    except Exception as e:
    print(f"An error occurred: {str(e)}")

    Continue reading...

Compartilhe esta Página