我正在使用WebBrowser
该类来打开文档、更改值、保存和打印。问题是,它打印的文档包括页眉(“第 1 页,共 1 页”)和页脚(文档的根 + 日期)
我查看了文档并没有找到删除它们的方法。甚至可以使用WebBrowser
还是我应该寻找替代品?
有一个解决方案,可能不如它本来的那么干净。由于 WebBrowser 继承了 Internet Explorer 的设置,因此可以更改注册表中的值。幸运的是,这些值在 HKCU 之下,因此不需要管理权限。
这样做的诀窍是将包含变量 ByRef SafeArray 的 Variant 传递给 WebBrowser 控件。我还没有弄清楚如何从 C# 中做到这一点。这是其他正在解决相同问题的人,他求助于使用托管 C++
http://www.limilabs.com/blog/printing-in-webbrowser-control-custom-header-and-footer
不是 C#,而是我基于现已失效的KB267240提出的 C++ 代码。它会在打印时删除页眉和页脚:
BOOL bRes = FALSE;
//Get IWebBrowser2 from your IE control
CComPtr<IWebBrowser2> pWebBrowser = this->GetIWebBrowser2();
if(pWebBrowser)
{
HRESULT hr;
COleVariant varNull;
SAFEARRAYBOUND psabBounds[1];
SAFEARRAY *psaHeadFoot;
hr = S_OK;
VARIANT vArg;
BOOL bGot_vArg = FALSE;
VARIANT vHeadStr, vFootStr;
long rgIndices;
VariantInit(&vHeadStr);
VariantInit(&vFootStr);
// Initialize header and footer parameters to send to ExecWB().
psabBounds[0].lLbound = 0;
psabBounds[0].cElements = 3;
psaHeadFoot = SafeArrayCreate(VT_VARIANT, 1, psabBounds);
if(psaHeadFoot)
{
// Argument 1: Header
vHeadStr.vt = VT_BSTR;
vHeadStr.bstrVal = SysAllocString(L" "); //Must be at least one space
if (vHeadStr.bstrVal)
{
// Argument 2: Footer
vFootStr.vt = VT_BSTR;
vFootStr.bstrVal = SysAllocString(L" "); //Must be at least one space
if(vFootStr.bstrVal)
{
rgIndices = 0;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&vHeadStr));
rgIndices = 1;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&vFootStr));
rgIndices = 2;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&varNull)); //Set stream to NULL as we don't need it
//NOTE: Currently, the SAFEARRAY variant must be passed by using
// the VT_BYREF vartype when you call the ExecWeb method.
VariantInit(&vArg);
vArg.vt = VT_ARRAY | VT_BYREF;
vArg.parray = psaHeadFoot;
//Got it
bGot_vArg = TRUE;
}
}
}
//Did we get all the vars?
if(bGot_vArg)
{
if(SUCCEEDED(hr = pWebBrowser->ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, &vArg, NULL)))
{
//All good
bRes = TRUE;
}
}
else
{
//Use fallback (that will keep the footer & header)
if(SUCCEEDED(hr = pWebBrowser->ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, varNull, varNull)))
{
//Printed via fallback
bRes = TRUE;
}
}
//Clean up
VariantClear(&vHeadStr);
VariantClear(&vFootStr);
if(psaHeadFoot)
{
SafeArrayDestroy(psaHeadFoot);
psaHeadFoot = NULL;
}
}