第 10 章 集成指南与代码样例
第 10 章 集成指南与代码样例
10.1 集成模式速查
| 需求 | 做法 |
|---|---|
| 网页打印按钮 | 引 /sdk/wxprint.js → wp.print({template, data, printer}) |
| 网页预览确认后打印 | wp.preview({...}) → 托盘弹原生预览窗口(或 /preview/{job_id}) |
| 后端出单 | POST /api/print(模板 id + 内联数据或数据 URL)+ 轮询 |
| 打印时才取数 | data: {url, headers} 服务端拉取 |
| 动态拼版 | POST /api/script 动词序列(或 SDK wp.document()) |
| 批量发货 | data 传数组 + copies_per_record 联数 |
| 局域网打印服务器 | bind: "0.0.0.0" + token;各机器提交时带 token |
| 存档 | POST /api/saveas(pdf/png/zip)或预览窗口导出 |
仓库 examples/ 提供全部样例的可运行版本(本章代码即取自那里):
examples/
├── websocket/ 浏览器演示(1 纯 HTML / 2 套打 / 3 Twig / 4 功能大全)
└── http/ 后端语言样例(python/php/nodejs/java/golang/
rust/c/cpp/csharp/ruby)+ mock_api.py(URL 数据源桩)
10.2 curl 快速验证
# 服务在跑?
curl -s http://127.0.0.1:8899/api/version
# 列打印机
curl -s http://127.0.0.1:8899/api/printers
# 提交打印(模板 id + 内联数据)
curl -s -X POST http://127.0.0.1:8899/api/print \
-H "Content-Type: application/json" \
-d '{"template": "invoice-a4", "data": {"no": "INV-001"},
"printer": "HP-LaserJet-M1005"}'
# 查状态
curl -s http://127.0.0.1:8899/api/jobs/<job_id>
10.3 Python(标准库 urllib)
import json, time, urllib.request
BASE, TOKEN = "http://127.0.0.1:8899", "" # 服务开 token 时填
def api(method, path, body=None, raw=False):
req = urllib.request.Request(BASE + path, method=method)
if TOKEN:
req.add_header("Authorization", f"Bearer {TOKEN}")
data = None
if body is not None:
data = json.dumps(body).encode()
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, data=data, timeout=30) as resp:
payload = resp.read()
return payload if raw else json.loads(payload)
# 1) 列打印机
printers = api("GET", "/api/printers")["printers"]
printer = next((p["name"] for p in printers if p["state"] == "ready"), "")
# 2) 提交打印:inline overlay 模板 + 内联数据
template = {
"id": "demo-waybill-py", "name": "Python 示例面单", "kind": "overlay",
"page": {"width_mm": 100, "height_mm": 180},
"elements": [
{"type": "text", "id": "title", "x": 5, "y": 6, "w": 90, "h": 8,
"text": "电子面单(Python 提交)",
"font": {"family": "", "size_pt": 12, "weight": 700}},
{"type": "barcode", "id": "bc", "x": 5, "y": 20, "w": 90, "h": 14,
"symbology": "code128", "content": "{{no}}", "show_text": True},
{"type": "text", "id": "addr", "x": 5, "y": 40, "w": 90, "h": 16,
"text": "收:{{name}}\n{{addr}}", "font": {"family": "", "size_pt": 8}},
],
}
job = api("POST", "/api/print", {
"template": template,
"data": {"no": "PY-2026-0001", "name": "赵六", "addr": "杭州市西湖区文三路 100 号"},
"printer": printer,
})
job_id = job["job_id"]
# 3) URL 数据形态(服务端拉取;headers 透传鉴权头)
job_url = api("POST", "/api/print", {
"template": {"url": "https://erp.example.com/tpl/order-label.json"},
"data": {"url": "https://erp.example.com/api/data/orders", # 数组=批量
"headers": {"Authorization": "Bearer erp-token"}, "timeout_s": 5},
})
# 4) 轮询状态
for _ in range(60):
st = api("GET", f"/api/jobs/{job_id}")
if st["status"] in ("done", "failed", "cancelled"):
break
time.sleep(0.5)
# 5) 注册模板(inline 提交不注册——按 id 复用先注册)
reg = api("POST", "/api/templates", template)
# 6) 预览 PDF(不出纸,按 id 引用)
pdf = api("POST", "/api/preview?format=pdf",
{"template": "demo-waybill-py", "data": {"no": "PY-2026-0002"}},
raw=True)
open("/tmp/wxprint-preview.pdf", "wb").write(pdf)
10.4 Node.js(内置 fetch,18+)
const BASE = "http://127.0.0.1:8899";
const TOKEN = "";
async function api(method, path, body) {
const headers = { "Content-Type": "application/json" };
if (TOKEN) headers.Authorization = `Bearer ${TOKEN}`;
const resp = await fetch(BASE + path, {
method, headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
return resp.json();
}
// 批量打印:数组数据 = 3 张标签连打
const job = await api("POST", "/api/print", {
template: {
id: "demo-label-node", kind: "overlay",
page: { width_mm: 60, height_mm: 40 },
elements: [
{ type: "text", id: "sku", x: 3, y: 3, w: 54, h: 6,
text: "{{sku}}", font: { family: "", size_pt: 9, weight: 700 } },
{ type: "barcode", id: "bc", x: 3, y: 11, w: 54, h: 12,
symbology: "code128", content: "{{code}}", show_text: false },
],
},
data: [
{ sku: "无线鼠标-黑", code: "SKU-10001", qty: 24, bin: "A-01-03" },
{ sku: "无线鼠标-白", code: "SKU-10002", qty: 18, bin: "A-01-04" },
{ sku: "有线键盘-87", code: "SKU-10003", qty: 12, bin: "B-02-01" },
],
printer: "",
});
for (let i = 0; i < 60; i++) {
const st = await api("GET", `/api/jobs/${job.job_id}`);
if (["done", "failed", "cancelled"].includes(st.status)) break;
await new Promise(r => setTimeout(r, 500));
}
10.5 Java(java.net.http.HttpClient,JDK 11+)
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
public class PrintWaybill {
static final String BASE = "http://127.0.0.1:8899";
static final String TOKEN = "";
static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5)).build();
static String api(String method, String path, String json) throws Exception {
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(BASE + path))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json");
if (!TOKEN.isEmpty()) req.header("Authorization", "Bearer " + TOKEN);
req.method(json == null ? "GET" : method,
json == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json));
HttpResponse<String> resp = HTTP.send(req.build(),
HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400)
throw new RuntimeException("HTTP " + resp.statusCode() + ": " + resp.body());
return resp.body();
}
public static void main(String[] args) throws Exception {
// 提交打印:inline overlay 模板(工程里建议 Jackson/Gson 序列化 POJO)
String body = """
{ "template": {
"id": "demo-waybill-java", "kind": "overlay",
"page": { "width_mm": 100, "height_mm": 100 },
"elements": [
{ "type": "text", "id": "title", "x": 5, "y": 5, "w": 90, "h": 8,
"text": "快递面单(Java 提交)",
"font": { "family": "", "size_pt": 12, "weight": 700 } },
{ "type": "barcode", "id": "bc", "x": 5, "y": 18, "w": 90, "h": 14,
"symbology": "code128", "content": "{{no}}", "show_text": true },
{ "type": "qrcode", "id": "qr", "x": 62, "y": 38, "w": 32, "h": 32,
"content": "{{url}}" } ] },
"data": { "no": "JAVA-2026-0001", "url": "https://example.com/t/1" },
"printer": "" }
""";
System.out.println(api("POST", "/api/print", body));
}
}
10.6 Go(标准库 net/http)
func api(method, path string, body any) (string, error) {
var rd io.Reader
if body != nil {
b, _ := json.Marshal(body)
rd = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, "http://127.0.0.1:8899"+path, rd)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil { return "", err }
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, b)
}
return string(b), nil
}
// inline html+twig 模板(entry = Twig 字符串,服务端渲染)
job, err := api("POST", "/api/print", map[string]any{
"template": map[string]any{
"id": "demo-report-go", "kind": "html",
"entry": `<h2>库存日报({{date}})</h2>
<table border="1" cellpadding="4" style="border-collapse:collapse;width:100%">
<tr style="background:#eee"><th>仓库</th><th>SKU 数</th></tr>
{% for w in warehouses %}<tr><td>{{w.name}}</td><td>{{w.sku_count}}</td></tr>{% endfor %}
</table>`,
"page": map[string]any{"width_mm": 210, "height_mm": 297,
"margin_mm": map[string]float64{"top": 15, "bottom": 15, "left": 14, "right": 14}},
},
"data": map[string]any{"date": "2026-10-24",
"warehouses": []map[string]any{{"name": "杭州一号仓", "sku_count": 1024}}},
})
10.7 PHP(cURL 扩展)
function api(string $method, string $path, ?array $body = null) {
$ch = curl_init("http://127.0.0.1:8899" . $path);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_TIMEOUT => 30]);
$headers = ['Content-Type: application/json'];
if (TOKEN !== '') { $headers[] = 'Authorization: Bearer ' . TOKEN; }
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode($body, JSON_UNESCAPED_UNICODE));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code >= 400) { fwrite(STDERR, "HTTP $code: $resp\n"); exit(1); }
return json_decode($resp, true);
}
$job = api('POST', '/api/print', [
'template' => 'invoice-a4',
'data' => ['no' => 'INV-2026-1042', 'amount' => 1280.50],
'printer' => 'HP-LaserJet-M1005',
]);
10.8 C#(.NET 8,零 NuGet 依赖)
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using var http = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:8899") };
var body = new {
template = new {
id = "demo-label-csharp", kind = "overlay",
page = new { width_mm = 60, height_mm = 40 },
elements = new object[] {
new { type = "text", id = "title", x = 3, y = 3, w = 54, h = 6,
text = "{{title}}", font = new { family = "", size_pt = 8, weight = 700 } },
new { type = "barcode", id = "bc", x = 3, y = 11, w = 54, h = 12,
symbology = "code128", content = "{{isbn}}", show_text = false },
},
},
data = new { title = "Rust 程序设计(第 2 版)", isbn = "978-7-111-00000-0" },
};
var resp = await http.PostAsJsonAsync("/api/print", body);
resp.EnsureSuccessStatusCode();
var job = await resp.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine($"job_id={job.GetProperty("job_id")}");
10.9 Ruby(标准库 net/http)
require 'net/http'
require 'json'
def api(method, path, body = nil)
uri = URI("http://127.0.0.1:8899#{path}")
req = Net::HTTP.const_get(method.capitalize).new(uri)
req['Content-Type'] = 'application/json'
req.body = JSON.generate(body) if body
Net::HTTP.start(uri.host, uri.port) { |http| http.request(req).body }
end
# 58mm 小票:inline html 模板(entry = Twig 字符串)
job = JSON.parse(api('post', '/api/print', {
'template' => {
'id' => 'demo-receipt-ruby', 'kind' => 'html',
'entry' => <<~HTML,
<div style="font-family:monospace">
<h3 style="margin:0">{{shop}}</h3>
{% for r in rows %}<div>{{r.name|escape}} × {{r.qty}} …… {{r.price}}</div>{% endfor %}
<div style="text-align:right"><b>合计:{{total}} 元</b></div>
</div>
HTML
'page' => { 'width_mm' => 58, 'height_mm' => 120,
'margin_mm' => { 'top' => 4, 'bottom' => 4, 'left' => 4, 'right' => 4 } }
},
'data' => { 'shop' => "示例便利店",
'rows' => [{ 'name' => '咖啡', 'qty' => 2, 'price' => 12 }],
'total' => 24 },
}))
10.10 C / C++ / Rust
三者样例在 examples/http/{c,cpp,rust}/(libcurl / 纯 std),核心
都是同一件事:POST JSON 到 /api/print、解析 job_id、轮询
/api/jobs/{id}。以 Rust 为例(仅 std):
// 提交 → 解析 job_id(serde_json 手拼/解析略,见 examples/http/rust)
let resp = http_post("http://127.0.0.1:8899/api/print", &body_json)?;
// 轮询
loop {
let st = http_get(&format!("http://127.0.0.1:8899/api/jobs/{job_id}"))?;
if st.contains("\"done\"") || st.contains("\"failed\"") { break; }
std::thread::sleep(std::time::Duration::from_millis(500));
}
10.11 网页集成
方式一:JS SDK(推荐)
<script src="http://127.0.0.1:8899/sdk/wxprint.js"></script>
<script>
const wp = new wxprint.WxPrint({ token: "T" });
wp.onJob(ev => updateProgress(ev.page_done, ev.total_pages));
document.getElementById("print-btn").onclick = async () => {
// 预览形态:done 后托盘弹原生预览窗口,用户确认后出纸
await wp.preview({ template: "invoice-a4",
data: { url: "/api/invoice/2026-1042" } });
// 直出形态:提交即出纸(电子面单/小票高频场景)
// await wp.print({ template: "sf-waybill-100x93", data: {...},
// printer: "HP-LaserJet-M1005" });
};
</script>
方式二:裸 WebSocket(见 5.4 节示例;断线重连需自行实现, SDK 已内置)。
弹窗防拦截:预览确认页若用 window.open,必须在用户手势
(click)内同步调用——异步回调里 open 会被浏览器拦截。先同步开
about:blank 写等待页,done 后 win.location.href 跳转
/preview/{job_id}。
10.12 连接目标自适应约定
示例与演示页遵守同一约定,业务集成建议沿用:
- 环境变量
WXPRINT_BASE/WXPRINT_TOKEN(显式指定); ~/.wxprint/config.json(托盘设置过的 bind/token 自动适配;0.0.0.0折算127.0.0.1);- 默认
http://127.0.0.1:8899匿名。
浏览器演示页另支持 URL 参数 ?host=&token= 显式覆盖。
10.13 从 Lodop 迁移
不做自动迁移工具,提供完整动词对照矩阵(docs/lodop-parity.md):
| Lodop | wxprint |
|---|---|
PRINT_INIT / PRINT_INITA |
init + pagesize |
ADD_PRINT_TEXT/HTM/TABLE/BARCODE/QRCODE/IMAGE/RECT/LINE |
add_text / add_html / add_table / add_barcode / add_qrcode / add_image / add_rect / add_line |
SET_PRINT_PAGESIZE(单位 0.1mm) |
pagesize(单位 mm,坐标直换) |
SET_PRINT_STYLE(A) |
set_style / set_stylea |
NEWPAGE |
newpage |
| ItemType 1/2/3/4(页眉页脚/首末页) | 元素 scope |
| PageNumber | {{page}} / {{pages}} |
PRINT / PRINTA / PRINT_PREVIEW / SAVEAS |
print / 预览组件选打印机 / 预览 / saveas(PRINT_SETUP 的元素级微调为规划项) |
ADD_PRINT_SETUP_BKIMG + SET_SHOW_MODE "BKIMG_PRINT" |
模板 background.image + background.print |
坐标 0.1mm→mm 直换;PRINT_SETUP 的现场微调数据格式私有,需在
新系统重新维护(常见场景可用模板级 calibration_offset 覆盖)。