printers.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import os
  2. import json
  3. import textwrap
  4. from fpdf import FPDF
  5. from PIL import Image
  6. import cups
  7. def add_printers():
  8. with open('printers/printers.json', 'r', encoding='utf-8') as file:
  9. printers = json.load(file)
  10. for printer in printers.items():
  11. name = printer[0]
  12. location = printer[1]['Location']
  13. model = printer[1]['Model']
  14. domain = printer[1]['Domain']
  15. os.system(f'lpadmin -p "{name}" -L "{location}" -D "{model}" -E -v http://{domain}')
  16. def pdf_from_text(text, filename):
  17. a4_width_mm = 210
  18. pt_to_mm = 0.35
  19. fontsize_pt = 11
  20. fontsize_mm = fontsize_pt * pt_to_mm
  21. margin_bottom_mm = 10
  22. character_width_mm = 7 * pt_to_mm
  23. width_text = a4_width_mm / character_width_mm
  24. pdf = FPDF(orientation='P', unit='mm', format='A4')
  25. pdf.set_auto_page_break(True, margin=margin_bottom_mm)
  26. pdf.add_page()
  27. pdf.set_font(family='Helvetica', size=fontsize_pt)
  28. splitted = text.split('\n')
  29. for line in splitted:
  30. lines = textwrap.wrap(line, width_text)
  31. if len(lines) == 0:
  32. pdf.ln()
  33. for wrap in lines:
  34. pdf.cell(0, fontsize_mm, wrap, ln=1)
  35. pdf.output(filename+'.pdf', 'F')
  36. return filename + '.pdf'
  37. def pdf_from_images(images, filename):
  38. pdf = FPDF(orientation='P', unit='mm', format='A4')
  39. pdf.set_auto_page_break(True, margin=10)
  40. for image in images:
  41. pdf.add_page()
  42. img = Image.open(image)
  43. img = img.rotate(90, expand=True, resample=Image.Resampling.BICUBIC)
  44. pdf.image(img, x=0, y=0, h=297)
  45. pdf.output(filename+'.pdf', 'F')
  46. return filename + '.pdf'
  47. def print_file(path, printer):
  48. conn = cups.Connection()
  49. # printers = conn.getPrinters()
  50. title = path.split('/')[-1]
  51. # printer = printer if list(printer.keys()) else list(printers.keys())[0]
  52. if os.path.isfile(path):
  53. conn.printFile(printer, path, title, {})