后台代码:
# coding="utf-8"
from flask import Flask,render_template,request
from werkzeug.utils import secure_filename
import os
import win32api
import win32gui
import win32print
import win32con
import time
from docx import Document
# create a MyFlask app
app = Flask(__name__)
child_handles = []
def all_ok(hwnd, param):
child_handles.append(hwnd)
@app.route("/")
def index():
return render_template("index.html")
@app.route('/Print',methods = ['POST'])
def Print():
if request.method == 'POST':
f = request.files['file']
t = request.form.get("text")
fname = f.filename
if(fname != ""):
f.save(os.path.join("./", fname))
win32api.ShellExecute(
0,
"print",
fname,
'/d:"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
time.sleep(3)
if os.path.splitext(fname)[-1] == ".jpg" or os.path.splitext(fname)[-1] == ".png":
# 父窗口句柄, 参数1是类名,参数2是标题
fileDialog = win32gui.FindWindow("NativeHWNDHost",'打印图片')
win32gui.EnumChildWindows(fileDialog, all_ok, None)
for a in child_handles:
clsname = win32gui.GetClassName(a)
text = win32gui.GetWindowText(a)
if text == "打印(&P)":
win32gui.PostMessage(a,win32con.BM_CLICK)
break
return "正在打印...."
if len(t) != 0:
txt_list = t.replace("\r","").split("\n")
document = Document()
for a in txt_list:
document.add_paragraph(a)
document.save("1.docx")
win32api.ShellExecute(
0,
"print",
"1.docx",
'/d:"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
time.sleep(3)
win32api.keybd_event(13,0,0,0)
win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0)
return "正在打印...."
else:
return "没有需要打印的东西"
else:
return render_template("index.html")
if __name__ == '__main__':
# 默认访问:http://127.0.0.1:8888/
app.run(debug=True,use_reloader=False,host='0.0.0.0', port=8888)
前端代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>免费无线打印机</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
html {
font-size: 62.5%;
}
body {
font: normal 100% Arial, sans-serif;
font-size: 14px;
font-size: 1.4rem;
}
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body style="background-image: linear-gradient(to right,lightblue,lightgreen);">
<h3 style="text-align: center;">欢迎来到周泓恺无线打印网站!</h3>
<br><br>
<form action="/Print" method="POST" enctype="multipart/form-data">
<label style="color:red">请打开文件:</label>
<input style="margin-top: -2rem;margin-left: 10rem;" type="file" name="file" />
<br>
<br>
<p style="color:red">请输入文字:</p>
<div style="position:absolute;" id="DisText"></div>
<textarea name="text" id="text" style="width:100%;height:50%;font-size: 1rem;"></textarea>
<div style="text-align: center;">
<input style="margin-top:10rem;background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);width:12rem;height:5rem;border-radius: 5rem;" type="submit" value="提交" />
</div>
</form>
</body>
</html>