2021-07-02 17:03:20 +10:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import tempfile
|
|
|
|
import subprocess
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
|
|
|
|
def convert_pdf(pdfname, args=[]):
|
|
|
|
pbmfile = tempfile.NamedTemporaryFile(suffix='.pbm')
|
|
|
|
subprocess.check_call(["pdftoppm", "-mono", "-singlefile"] + args + [pdfname, pbmfile.name.removesuffix('.pbm')])
|
|
|
|
|
|
|
|
return Image.open(pbmfile)
|
|
|
|
|
|
|
|
def convert_pdf_scaled(pdfname, max_width, max_height):
|
|
|
|
im = convert_pdf(pdfname)
|
|
|
|
aspect = im.size[0] / im.size[1]
|
|
|
|
max_aspect = max_width / max_height
|
|
|
|
|
|
|
|
if aspect < max_aspect:
|
|
|
|
max_width = int(max_height * aspect) - 1
|
|
|
|
else:
|
|
|
|
# pdftoppm tends to make it 1px too wide
|
|
|
|
max_width -= 1
|
|
|
|
max_height = int(max_width / aspect)
|
|
|
|
|
|
|
|
args = ['-scale-to-x', str(max_width), '-scale-to-y', str(max_height)]
|
|
|
|
im = convert_pdf(pdfname, args)
|
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
assert im.size[0] <= max_width + 1
|
2021-07-02 17:03:20 +10:00
|
|
|
assert im.size[1] <= max_height
|
|
|
|
|
|
|
|
return im
|
|
|
|
|
2021-07-02 20:04:26 +10:00
|
|
|
def label_to_command(image, labelwidth_mm=100, labelheight_mm=150, dpi=203):
|
2021-07-02 17:03:20 +10:00
|
|
|
"Centre the image on the label and generate a print command"
|
2021-07-02 20:04:26 +10:00
|
|
|
labelwidth = labelwidth_mm / 25.4 * dpi
|
|
|
|
labelheight = labelheight_mm / 25.4 * dpi
|
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
assert image.size[0] <= labelwidth + 5
|
|
|
|
assert image.size[1] <= labelheight + 5
|
2021-07-02 17:03:20 +10:00
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
paste_x = (labelwidth - image.size[0]) // 2
|
|
|
|
paste_y = (labelheight - image.size[1]) // 2
|
|
|
|
row_bytes = (image.size[0] + 7) // 8
|
2021-07-02 17:03:20 +10:00
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
command = b"SIZE %d mm\r\nCLS\r\nBITMAP %d,%d,%d,%d,0," % (labelwidth_mm, paste_x, paste_y, row_bytes, image.size[1])
|
2021-07-02 17:03:20 +10:00
|
|
|
command += image.tobytes()
|
2021-07-02 17:20:17 +10:00
|
|
|
command += b"\r\nPRINT 1,1\r\n"
|
2021-07-02 17:03:20 +10:00
|
|
|
return command
|
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
def print_pdf(filename):
|
|
|
|
im = convert_pdf_scaled(filename, 800, 1200)
|
|
|
|
cmd = label_to_command(im)
|
|
|
|
with open("/dev/usb/lp0", "r+b") as prn:
|
|
|
|
prn.write(cmd)
|
2021-07-02 17:03:20 +10:00
|
|
|
|
2021-07-02 20:40:12 +10:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import sys
|
|
|
|
print_pdf(sys.argv[1])
|