2

This Python code works in Windows but does not work in Raspbian. How do I print PDF files using the Raspberry Pi?

    import os
    fd = os.startfile("/home/pi/Desktop/a.pdf", "print")
0

3 Answers 3

3

You could use CUPS

import cups
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
conn.printFile(printer_name,'/home/pi/Desktop/a.pdf',"",{}) 
1

os.startfile()'s "print" option is not available in Raspbian (the OS of the Raspberry Pi). Make sure that your printer is connected to the Pi, and use Popen and lpr to communicate with the printer daemon.

1
  • That assumes that the printer understands PDF. Commented Jul 18, 2023 at 19:23
0

You could use the below code(NOTE: code starts from import cups)

import cups

def print_file(file_path, printer_name):

    conn = cups. Connection()

    printers = conn.getPrinters()
    
    if printer_name in printers:
        try:
            conn.printFile(printer_name, file_path, "Print Job", {})
            print("File sent to printer successfully.")
        except cups.IPPError as e:
            print(f"Error printing file: {e}")
    else:
        print(f"Printer '{printer_name}' not found.")

Example usage

file_to_print = "/path/to/your/file.pdf"
printer_name = "Your_Printer_Name"
print_file(file_to_print, printer_name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.