You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TEdgeBrowser组件打印时控制页眉页脚的方法

在Delphi中用TEdgeBrowser自定义打印页眉页脚

针对你遇到的问题,目前有两种靠谱的方案实现TEdgeBrowser打印时自定义页眉页脚内容:

方案1:通过Edge DevTools Protocol(EDP)控制打印参数

TEdgeBrowser支持与Edge的开发者工具协议交互,你可以直接调用Page.print命令,通过配置headerTemplate和footerTemplate参数自定义页眉页脚的HTML内容。

实现步骤:

  1. 获取TEdgeBrowser的ICoreWebView2接口,建立与EDP的通信
  2. 构造包含headerTemplate和footerTemplate的JSON参数,这两个参数支持HTML字符串,可插入变量(比如{{title}}、{{pageNumber}}、{{totalPages}}等)
  3. 调用ICoreWebView2CallDevToolsProtocolMethodAsync执行打印命令

Delphi代码示例:

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, EdgeBrowser;

type
  TForm1 = class(TForm)
    EdgeBrowser1: TEdgeBrowser;
    btnPrint: TButton;
    procedure btnPrintClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnPrintClick(Sender: TObject);
var
  LWebView: ICoreWebView2;
  LJsonParams: string;
begin
  if EdgeBrowser1.CoreWebView2Interface.QueryInterface(ICoreWebView2, LWebView) = S_OK then
  begin
    // 构造打印参数,自定义页眉页脚
    LJsonParams := '{'+
      '"headerTemplate": "<div style=\"font-size:10px; text-align:center;\">自定义页眉 - {{title}}</div>",'+
      '"footerTemplate": "<div style=\"font-size:10px; text-align:right;\">第 {{pageNumber}} 页,共 {{totalPages}} 页</div>",'+
      '"printBackground": true,'+
      '"landscape": false'+
    '}';

    // 调用EDP的Page.print命令
    LWebView.CallDevToolsProtocolMethodAsync('Page.print', LJsonParams, nil);
  end;
end;

方案2:通过CSS媒体查询直接修改页面打印样式

这种方法不需要依赖浏览器接口,直接在要打印的HTML页面中添加打印专用的CSS,通过@media print和@page规则自定义页眉页脚。

示例CSS代码:

@media print {
  /* 设置页面边距,给页眉页脚留出空间 */
  @page {
    margin-top: 2cm;
    margin-bottom: 2cm;
  }

  /* 自定义页眉 */
  body::before {
    content: "自定义页眉 - " document.title;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;
    font-size: 10px;
    color: #666;
  }

  /* 自定义页脚 */
  body::after {
    content: "第 " counter(page) " 页,共 " counter(pages) " 页";
    position: fixed;
    bottom: 0;
    right: 20px;
    font-size: 10px;
    color: #666;
  }
}

你可以通过TEdgeBrowser的ExecuteScriptAsync方法动态注入这段CSS到当前页面,或者直接在HTML源码中包含该样式。


内容的提问来源于stack exchange,提问作者Kyle Williamson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:34:56