如何从Web浏览器控件设置纸张尺寸和边距打印

say*_*man 7 .net c# printing webbrowser-control winforms

我正在尝试从winform应用程序中的Web浏览器控件进行打印.问题是它将字母设置为默认纸张大小但我需要A4.此外,它会自动设置一些边距错误,我可以设置它们手动更正设置,但我想以编程方式进行.

这怎么可能?

这是我打印的代码.

private void metroButton1_Click(object sender, EventArgs e)
    {
        loadprintData();
        // Create a WebBrowser instance. 
        WebBrowser webBrowserForPrinting = new WebBrowser();

        // Add an event handler that prints the document after it loads.
        wa.DocumentCompleted +=
            new WebBrowserDocumentCompletedEventHandler(ShowPrintDocument);
        wa.ShowPrintPreviewDialog();
        reloadpage();

    }
    private void ShowPrintDocument(object sender,WebBrowserDocumentCompletedEventArgs e)
    {
        // Print the document now that it is fully loaded.
        ((WebBrowser)sender).ShowPrintPreviewDialog();

        // Dispose the WebBrowser now that the task is complete. 
        // ((WebBrowser)sender).Dispose();
        reloadpage();
    }
    private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        // Print the document now that it is fully loaded.
        ((WebBrowser)sender).Print();

        // Dispose the WebBrowser now that the task is complete. 
       // ((WebBrowser)sender).Dispose();
    }
Run Code Online (Sandbox Code Playgroud)

Jer*_*son 9

要更改边距大小,您必须在打印前编辑(HKCU)注册表:

string pageSetupKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
bool isWritable = true;

RegistryKey rKey = Registry.CurrentUser.OpenSubKey(pageSetupKey, isWritable);

if (stringToPrint.Contains("something"))
{
    rKey.SetValue("margin_bottom", 0.10);
    rKey.SetValue("margin_top", 0.25);
}
else
{
    //Reset old value
    rKey.SetValue("margin_bottom", 0.75);
    rKey.SetValue("margin_top", 0.75);
}
Run Code Online (Sandbox Code Playgroud)

别忘了将其恢复为默认值.

参考Microsoft KB文章


要更改纸张尺寸,您必须在打印前在其他位置编辑(HKCU)注册表:

string pageSetupKey2 = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
isWritable = true;

rKey = Registry.CurrentUser.OpenSubKey(pageSetupKey2, isWritable);

// Use 1 for Portrait and 2 for Landccape 
rKey.SetValue("PageOrientation", 2, RegistryValueKind.DWord); 
// Specifies paper size. Valid settings are 1=letter, 5=Legal, 9=A4, 13=B5.Default setting is 1.
rKey.SetValue("PaperSize", 9, RegistryValueKind.DWord); 
// Specifies print quality
rKey.SetValue("PrintQuality ", 1, RegistryValueKind.DWord);
Run Code Online (Sandbox Code Playgroud)

参考MSDN


say*_*man 0

好吧,我尝试了很多事情,但最后我发现不可能轻松地从代码中对打印机设置进行编程。但我可以通过@jeremy 的回答做保证金。我发现,对于从 WebBrowser 控件进行打印,它使用我们所知道的 Internet Explorer,但一开始它使用的是 Explorer 7,我必须将其默认更改为 Explorer 11。然后我看到资源管理器没有自己的打印设置。它使用默认打印机设置。因此,您必须更改默认打印机预览。您将看到预览会以这种方式显示。