aardio 文档

aardio 范例: WebView2 打印网页,自动修改打印设置

查找打印机

import web.view;
import win.ui;
/*DSG{{*/
var winform = win.form(text="WebView2 打印网页,自动修改打印设置";right=966;bottom=622)
winform.add()
/*}}*/

/*
import com.wmi;
var printer = com.wmi.get("Select * From Win32_Printer WHERE Name=@name",{
    name = "EPSON L360 Series" //查找指定打印机
})
if(printer){
    printer.SetDefaultPrinter() //设为默认打印机
}
//查找打印机: https://www.aardio.com/zh-cn/docs/examples/System/Printer/Win32_Printer.html
*/

//WebView2 加载用户配置
var userDataDir = ..io.appData("aardio/std/examples/web-view-print-direct");
var preferences,path = web.view.loadPreferences(userDataDir);
var appState = table.get("printing.print_preview_sticky_settings.appState",preferences)

//获取与修改打印设置
var printAppState = JSON.tryParse(appState) //不存在会返回 NULL 值
printAppState = table.assignDeep(printAppState , {
    "version":2,
    "duplexType":"LONG_EDGE",
    "mediaSize":{"height_microns":297000,"width_microns":210000},
    "marginsType":0,
    "customMargins":{"marginTop":72,"marginRight":72,"marginBottom":72,"marginLeft":72},
    "isColorEnabled":true,
    "isHeaderFooterEnabled":false,
    "isLandscapeEnabled":false,
    "isCollateEnabled":true,
    "isCssBackgroundEnabled":false,
    "scaling":"100"
});

//保存打印机设置
printAppState = JSON.stringify(printAppState)
table.set("printing.print_preview_sticky_settings.appState",printAppState,preferences)
JSON.save(path,preferences,false);//保存,不需要格式化

//创建浏览器控件,参数 @1 指定窗口或 custom 控件对象。
var wb = web.view(winform,{
    //--kiosk-printing 允许直接打印,--use-system-default-printer 参数使用系统默认打印机
    startArguments =  ["--kiosk-printing","--use-system-default-printer"];
    userDataDir = userDataDir;
})

//演示网页,调用 Print.js 可以更方便的控制打印
wb.html = /********
<!doctype html>
<html><head>
    <meta charset="utf-8">
    <style type="text/css">html,body{ height:100%; margin:0; } </style>
    <link rel="stylesheet" type="text/css"  href="https://lib.baomitu.com/print-js/1.6.0/print.min.css">
    <script src="https://lib.baomitu.com/print-js/1.6.0/print.min.js"></script>
    <script> 

function printHtml() {
  printJS({
    printable: 'printableArea', // 传入要打印的元素的ID
    type: 'html',
    header: '我的报告标题', // 在打印页面的顶部添加页眉
    targetStyles: ['*'] // 继承页面中的所有样式
  });
}
    </script>
</head>
<body>
<div id="printableArea">
    <h1>用户报告</h1>
    <p>这是一份从页面特定区域打印的报告。</p>
    <table border="1" style="width:100%">
        <tr>
            <th>姓名</th>
            <th>邮箱</th>
        </tr>
        <tr>
            <td>张三</td>
            <td>zhangsan@example.com</td>
        </tr>
    </table>
</div>

<button onclick="printHtml()">直接打印报告(不需要确认)</button>
</body></html>
********/

winform.show();
win.loopMessage();

Markdown 格式