using python pycups cups how to set margin for custom page size

171 views Asked by At

Below is script using pycups I am able to print with custom page size but I need to set the margin also how do it do that.

import cups

def print_to_printer(printer_name, file_path, custom_width=720, custom_length=432):
    conn = cups.Connection()

    # Get the printer information
    printer_info = conn.getPrinterAttributes(printer_name)

    # Convert inches to points (1 inch = 72 points)
    custom_width_points = str(int(custom_width * 72))
    custom_length_points = str(int(custom_length * 72))

    # Create the page size string
    page_size_str = f"{custom_width_points}x{custom_length_points}"

    # Start the print job with custom page size
    print_options = {'PageSize': page_size_str}
    print_job_id = conn.printFile(printer_name, file_path, "Print Job", print_options)

    print(f"Print job {print_job_id} sent to {printer_name} with custom page size ({custom_width}x{custom_length} inches)")

# Example usage
printer_name = "TVS_MSP-250CH-TVS-original"  # Replace with your actual printer name
file_to_print = "/home/tk/Documents/bill.txt"  # Replace with the path to your file
custom_width = 10  # Replace with your desired width in inches
custom_length = 6  # Replace with your desired length in inches
print_to_printer(printer_name, file_to_print, custom_width, custom_length)
2

There are 2 answers

2
naved196 On

Try again with Pycups library

import pycups

printer = pycups.Connection("Your printer name")

printer.raw("PageSize A4: \"</PageSize[595 842]>>setpagedevice\"")

printer.printFile("document.pdf")

Doumentation link below:- https://www.cups.org/doc/spec-ppd.html#cupsPageSizeCategory

0
thetaco On

Pycups does not allow the ability to set margin on your documents. However, there may be a hard-coded value of your printers expected margin in your .ppd file. You can edit this file at /etc/cups/ppd/insertYourPrinterName.ppd . As stolen from this forum, you can edit

*ImageableArea Letter/US Letter:        "18 36 594 756"

The numbers correspond to [Left Top Right Bottom] margins (starting from the top and left of the page). Change these values to your desired margin.

You will often need to adjust the margin of the document that you're printing as well.