Created
June 16, 2021 07:05
-
-
Save capjamesg/48d6c723ac82cf3d2796085511534122 to your computer and use it in GitHub Desktop.
Print a hcard with a thermal printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mf2py | |
import main | |
import requests | |
import os | |
from Adafruit_Thermal import * | |
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5) | |
printer.setLineHeight(28) | |
hcard = mf2py.parse(url="https://jamesg.blog/") | |
def property_to_print(hcard_item, property): | |
# Special handling for org properties so I can create a list of properties | |
if property == "org" and hcard_item["properties"].get("org"): | |
org_list = [] | |
for item in hcard_item["properties"][property]: | |
if item["properties"].get("name"): | |
org_list.append(item["properties"]["name"][0]) | |
elif item[0]: | |
org_list.append(item[0]) | |
org_list = ", ".join(org_list) | |
printer.println(main.textWrapped(org_list)) | |
elif hcard_item["properties"].get(property): | |
printer.println(main.textWrapped(hcard_item["properties"][property][0])) | |
else: | |
print("No {} available.".format(property)) | |
def get_hcard(hcard_item, printer): | |
# Print image at start of hcard | |
if hcard_item["properties"].get("photo"): | |
image = requests.get(hcard_item["properties"]["photo"][0]) | |
with open("header.jpeg", "wb") as file: | |
file.write(image.content) | |
printer.printImage("header.jpeg") | |
os.remove("header.jpeg") | |
else: | |
print("No photo available.") | |
# Print name w/ gap between photo and following properties | |
# Name is in large text | |
printer.feed(2) | |
printer.setSize("L") | |
property_to_print(hcard_item, "name") | |
printer.setSize("S") | |
# Print other properties | |
properties_to_print = ["nickname", "job-title", "org", "email", "url", "locality", "region", "country-name", "tel", "note"] | |
for p in properties_to_print: | |
property_to_print(hcard_item, p) | |
hcard_item = [] | |
for item in hcard["items"]: | |
if item["type"][0] == "h-card": | |
hcard_item = item | |
break | |
if hcard_item == []: | |
print("H-card cannot be found.") | |
else: | |
get_hcard(hcard_item, printer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment