print pdf with chrome

This commit is contained in:
Simon Zeyer
2024-10-16 13:36:43 +00:00
parent b82d1bed1f
commit 47c1c5ceb8
5 changed files with 36 additions and 15 deletions
+2 -2
View File
@@ -132,5 +132,5 @@ def files():
html = html + '</ul><form method="post" enctype="multipart/form-data"><input type="file" name="file"><input type=submit value=Upload></form>'
return html
if __name__ == "__main__":
app.run(port=5000)
# if __name__ == "__main__":
# app.run(port=5000, host='0.0.0.0')
+13 -11
View File
@@ -2,10 +2,9 @@ import os
import logging
import requests
import cups
from weasyprint import HTML, CSS
from weasyprint.text.fonts import FontConfiguration
from requests.adapters import Retry
import uuid
import subprocess
retries = Retry(total=5,
backoff_factor=0.1,
@@ -122,23 +121,26 @@ def alarminator_api(parsed_body: dict):
except Exception as e:
logging.error("alarminator_api", e)
def generate_pdf(html_body, filename):
f = "/tmp/{}.html".format(uuid.uuid4())
with open(f,"w") as _f:
_f.write(html_body)
subprocess.run(["/usr/bin/google-chrome-stable", "--headless", "--no-sandbox", "--disable-gpu", "--print-to-pdf="+filename, "--no-pdf-header-footer", "--print-to-pdf-no-header", "--no-margins", f])
if os.path.exists(f):
os.remove(f)
def cups_print(parsed_body: dict, body: str):
html = HTML(string='<html><head></head><body>'+body+"</body></html>", base_url="")
font_config = FontConfiguration()
pdf = html.write_pdf(font_config=font_config,stylesheets=[CSS(string='body { font-family: serif !important }')])
fname = "/tmp/{}.pdf".format(uuid.uuid4())
if os.environ.get('IS_DEV') and os.environ.get('IS_DEV') == "True":
with open("{}.pdf".format(uuid.uuid4()),"wb") as f:
f.write(pdf)
generate_pdf(body, "{}.pdf".format(uuid.uuid4()))
fname = "/tmp/{}.pdf".format(uuid.uuid4())
try:
conn = cups.Connection ()
printer_arr = os.environ.get('printer',"DEFAULT").split(";")
print_num = int(os.environ.get('print_num',0))
if printer_arr.__len__() > 0:
generate_pdf(body, fname)
for printer in printer_arr:
if 'ALARMDEPESCHE' in parsed_body:
with open(fname,"wb") as f:
f.write(pdf)
for i in range(0, print_num):
conn.printFile (printer, fname, "Alarmfax", {})
os.remove(fname)