C# 如何打印文本框的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15563886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:10:49  来源:igfitidea点击:

How to print the contents of a TextBox

c#.netwindows-8microsoft-metrowindows-store-apps

提问by jay_t55

How do I print the contents of a TextBox in metro apps? I have read this quickstart guide on MSDNand many online tutorials, but they are very complicated and do not work with TextBox controls, only RichTextBoxcontrols.

如何在 Metro 应用程序中打印 TextBox 的内容?我已经阅读了 MSDN 上的这个快速入门指南和许多在线教程,但它们非常复杂,并且不适用于 TextBox 控件,只能使用 RichTextBox控件

How do we print from a TextBox control in a metro app? Is it even possible? How?

我们如何从 Metro 应用程序中的 TextBox 控件打印?甚至有可能吗?如何?

采纳答案by Xyroid

UPDATE 1

更新 1

I have created a helper class which simplifies printing text box content. You can add helper class via NuGet. If you want to enhance my existing helper class, fork on GitHub

我创建了一个帮助程序类,它简化了打印文本框内容。您可以通过NuGet添加辅助类。如果你想增强我现有的辅助类,请在GitHub 上fork



Here I am giving you the modified print samplefrom MSDN. I have put textbox you can write anything and that will be printed. Please note I have not done sample which prints textbox text exactly same as it is i.e formatting (bold, italic, underline, colors). I have set hard-coded print format. You can make your own format.

在这里,我为您提供来自 MSDN的修改后的打印示例。我已经把文本框你可以写任何东西,这将被打印出来。请注意,我还没有完成打印与格式完全相同的文本框文本的示例(粗体、斜体、下划线、颜色)。我已经设置了硬编码打印格式。您可以制作自己的格式。

Stack Overflow has character limit in answer and my code is too long so posting CodePaste.net links.

Stack Overflow 的回答有字符限制,我的代码太长,所以发布 CodePaste.net 链接。

XAML : http://codepaste.net/9nf261

XAML:http: //codepaste.net/9nf261

CS : http://codepaste.net/q3hsm3

CS:http: //codepaste.net/q3hsm3

Please note that I have used some images so put images in "Images" folder

请注意,我使用了一些图像,因此将图像放在“图像”文件夹中

回答by Tomtom

I just created a small winforms-application with a textbox (textBox1) and a button (button1). The code-behind looks like:

我刚刚创建了一个带有文本框 (textBox1) 和按钮 (button1) 的小型 winforms 应用程序。代码隐藏看起来像:

public partial class Form1 : Form
{
    public Form1()
    {
           InitializeComponent();
    }

    private void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
    {
        e.Graphics.DrawString(this.textBox1.Text, this.textBox1.Font, Brushes.Black, 10, 25);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        PrintDocument printDocument = new PrintDocument();
        printDocument.PrintPage += PrintDocumentOnPrintPage;
        printDocument.Print();
    }
}

On a click on the button the printing will be done.

单击按钮即可完成打印。

回答by Alexandru

I urge you to check my question herein which I illustrate one of the simplest cases in which you can print something off a page (and you can add that code onto any page you currently have - just replace the example text box's text I use to whatever your heart desires). The reason why they use the rich text boxes is because it can detect when text overflows off the page, thus they use that information to create a new page with another rich text box until no more overflowing occurs. No matter, you can use your own string parser to split your text up on different pages. Essentially, printing in Windows 8 apps will print any UIElement you want, so you can pretty much XAML align your page programmatically and style it just the way you'd style any other Windows app. Seriously, check the question, it'll be a huge help. I spent hours hacking the PrintSample down to the simplest case until I figured out how it all worked. No point in reinventing the wheel, use my struggles to your advantage, that's what Stack is all about. Cheers!

我敦促你在这里检查我的问题在其中我说明了一种最简单的情况,在这种情况下,您可以从页面上打印一些内容(并且您可以将该代码添加到您当前拥有的任何页面上 - 只需将我使用的示例文本框的文本替换为您想要的任何内容)。他们使用富文本框的原因是因为它可以检测文本何时溢出页面,因此他们使用该信息创建一个带有另一个富文本框的新页面,直到不再发生溢出。无论如何,您可以使用自己的字符串解析器将文本拆分到不同的页面上。本质上,在 Windows 8 应用程序中打印将打印您想要的任何 UIElement,因此您几乎可以通过 XAML 以编程方式对齐您的页面,并按照您为任何其他 Windows 应用程序设置样式的方式对其进行样式设置。说真的,检查这个问题,这将是一个巨大的帮助。我花了几个小时将 PrintSample 分解为最简单的情况,直到我弄清楚它是如何工作的。没有必要重新发明轮子,利用我的努力为您带来优势,这就是 Stack 的全部意义所在。干杯!

Edit: I'll pose the code here for your convenience, guys.

编辑:为了您的方便,我将在这里提供代码,伙计们。

Step 1: Add this code to the page with your text box.

第 1 步:将此代码添加到带有文本框的页面。

        protected PrintDocument printDocument = null;
        protected IPrintDocumentSource printDocumentSource = null;
        internal List<UIElement> printPreviewElements = new List<UIElement>();
        protected event EventHandler pagesCreated;

        protected void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
        {
            PrintTask printTask = null;
            printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested =>
            {
                printTask.Completed += async (s, args) =>
                {
                    if (args.Completion == PrintTaskCompletion.Failed)
                    {
                        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                        {
                            MessageDialog dialog = new MessageDialog("Something went wrong while trying to print. Please try again.");
                            await dialog.ShowAsync();
                        });
                    }
                };
                sourceRequested.SetSource(printDocumentSource);
            });
        }

        protected void RegisterForPrinting()
        {
            printDocument = new PrintDocument();
            printDocumentSource = printDocument.DocumentSource;
            printDocument.Paginate += CreatePrintPreviewPages;
            printDocument.GetPreviewPage += GetPrintPreviewPage;
            printDocument.AddPages += AddPrintPages;
            PrintManager printMan = PrintManager.GetForCurrentView();
            printMan.PrintTaskRequested += PrintTaskRequested;
        }

        protected void UnregisterForPrinting()
        {
            if (printDocument != null)
            {
                printDocument.Paginate -= CreatePrintPreviewPages;
                printDocument.GetPreviewPage -= GetPrintPreviewPage;
                printDocument.AddPages -= AddPrintPages;
                PrintManager printMan = PrintManager.GetForCurrentView();
                printMan.PrintTaskRequested -= PrintTaskRequested;
            }
        }

        protected void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
        {
            printPreviewElements.Clear();
            PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
            PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
            AddOnePrintPreviewPage(pageDescription);
            if (pagesCreated != null)
            {
                pagesCreated.Invoke(printPreviewElements, null);
            }
            ((PrintDocument)sender).SetPreviewPageCount(printPreviewElements.Count, PreviewPageCountType.Intermediate);
        }

        protected void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
        {
            ((PrintDocument)sender).SetPreviewPage(e.PageNumber, printPreviewElements[e.PageNumber - 1]);
        }

        protected void AddPrintPages(object sender, AddPagesEventArgs e)
        {
            foreach (UIElement element in printPreviewElements)
            {
                printDocument.AddPage(element);
            }
            ((PrintDocument)sender).AddPagesComplete();
        }

        protected void AddOnePrintPreviewPage(PrintPageDescription printPageDescription)
        {
            TextBlock block = new TextBlock();
            block.Text = "This is an example.";
            block.Width = printPageDescription.PageSize.Width;
            block.Height = printPageDescription.PageSize.Height;
            printPreviewElements.Add(block);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            RegisterForPrinting();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            UnregisterForPrinting();
        }

Step 2: Replace block.Text with your desired text.

第 2 步:将 block.Text 替换为您想要的文本。

Step 3: Use a print button to show the print UI:

第 3 步:使用打印按钮显示打印 UI:

        private async void PrintDocument(object sender, RoutedEventArgs e)
        {
            await Windows.Graphics.Printing.PrintManager.ShowPrintUIAsync();
        }

Step 4: Put RequestedTheme="Light" in your App.xaml and you're done. Note: Might be able to alternatively style the textbox the way you want in this XAML class and not have to set the theme of the entire app.

第 4 步:将 RequestedTheme="Light" 放入您的 App.xaml 中,您就完成了。注意:也许可以在此 XAML 类中按照您想要的方式设置文本框的样式,而不必设置整个应用程序的主题。

Step 5 (Later On): You might want to consider adding in your own new page detection logic that keeps calling that method up top to create a new page.

第 5 步(稍后):您可能需要考虑添加自己的新页面检测逻辑,该逻辑会不断调用该方法以创建新页面。

Step 6 (Right Now): Get into a fight with the guy at M$ who's responsible for making us struggle.

第 6 步(现在):与 M$ 的那个负责让我们挣扎的人打架。