"Win 10 App development" Print UI elements

Source: Internet
Author: User

Original: "Win 10 App development" Print UI Element

The Windows app supports the ability to print the UI interface, which is similar to the purpose of a printed Web page in a browser, with the benefit of "WYSIWYG", which directly prints the content rendered on the interface, much more conveniently than recreating the printed image.

To print in a generic app, you rely on the following types:

PrintManager: located in the Windows.Graphics.Printing namespace, the main responsibility is to display the Print dialog box, set the print source and other operations. When used, the Getforcurrentview static method is called first to get a PrintManager instance, and then its printtaskrequested is processed, and the event occurs when it is to be printed.

Printtask: represents a print task. Creates a print task in the Printtaskrequested event handling of the PrintManager object.

PrintDocument: This class is more critical (in the Windows.UI.Xaml.Printing namespace). It enables you to convert UI elements into document logic to be printed. A. Handle the Paginate event to calculate the printed page break, and after calculation you can call the Printdocument.setpreviewpagecount method to set the total number of preview pages. B. Handle the Getpreviewpage event, which occurs when a request is previewed on a single page, and during processing, you can call the Printdocument.setpreviewpage method to set the specific page to preview. C, when you start printing, the Addpages event occurs when the Printdocument.addpage method is called to add pages to the print document logic, and when all the pages to be printed are added, call the Addpagescomplete method to notify the system that it can submit the print.

When you just touch the print, you think it's complicated, but when you do the experiment, you'll find that it's nothing. We, as developers of the new era, should have a hard-on spirit.

Let's take an example and print out the contents of a Richtextblock control on the page.

The XAML on the page is roughly the following, the old week directly posted out, do not explain, I believe you can read the XAML, if you do not understand, then even.

    <BorderPadding= "+"Background="{ThemeResource Applicationpagebackgroundthemebrush}">        <Grid>            <grid.rowdefinitions>                <RowDefinitionHeight= "Auto"/>                <RowDefinition/>                <RowDefinitionHeight= "Auto"/>            </grid.rowdefinitions>            <StackPanelMargin= "0,15"Orientation= "Horizontal">                <ButtonContent= "Start printing"Click= "OnClick"/>            </StackPanel>            <RichtextblockName= "TB"Grid.Row= "1"Width= "+" >                <ParagraphFontSize= "The "TextAlignment= "Center"FontFamily= "Italic">before the bed was bright moonlight,<LineBreak/>suspicion is ground frost. <LineBreak/>and looking at the moon,<LineBreak/>low head think so hometown. </Paragraph>                <ParagraphTextAlignment= "Center">                    <InlineUIContainer>                        <ImageHeight= "$"Source= "Http://img155.poco.cn/mypoco/myphoto/20110305/15/20110305154657_366496406.gif"/>                    </InlineUIContainer>                </Paragraph>            </Richtextblock>...</Grid>    </Border>

What we're going to print out of this example is the guy named TB.

Enter the code file for the page and declare the following fields in the page class:

        PrintManager printmgr = printmanager.getforcurrentview ();         NULL ;         =null;         null;

The function of the RotateTransform variable is to rotate the TB in order to handle the direction of the printed page, and if the page is horizontal, I turn the TB 90 degrees.

Handles the PrintManager printtaskrequested event, creates a print task, and sets the print source.

 Printmgr.       printtaskrequested += printmgr_printtaskrequested; ...  private  void               printmgr_printtaskrequested (printmanager sender, Printtaskrequestedeventargs args) {  var  def = args.            Request.getdeferral ();  //  Create a print task  task = args. Request.createprinttask (  print test   "  += task_completed;        Def.complete (); }

When you call the Createprinttask method to create a print task, there is a parameter that requires a delegate to set the print source. The so-called print source, is the document we want to print .

        Private Async void onprinttasksourcerequrested (Printtasksourcerequestedargs args)        {            var def = args. Getdeferral ();             await Dispatcher.runasync (Windows.UI.Core.CoreDispatcherPriority.Normal,                = =                {                     //  set the print source                    args. SetSource (printdic?). DocumentSource);                });            Def.complete ();        }

What we want to print here is actually PrintDocument object, our variable name seems wrong, call Printdoc reasonable, I played printdic. All right, everyone knows it's OK.

The following code handles the button's Click event:

        Private Async voidOnClick (Objectsender, RoutedEventArgs e) {            if(Printdic! =NULL) {Printdic.getpreviewpage-=Ongetpreviewpage; Printdic.paginate-=printdic_paginate; Printdic.addpages-=printdic_addpages; }             This. Printdic =NewPrintDocument (); Printdic.getpreviewpage+=Ongetpreviewpage; Printdic.paginate+=printdic_paginate; Printdic.addpages+=printdic_addpages; //Show Print dialog box            BOOLb=awaitPrintmanager.showprintuiasync (); }

After instantiating the PrintDocument, you want to handle several of its events.

The Addpages event is processed first, which occurs when you start printing, when you add pages to the printed document in event handling, and the content of each page is the UI element that we want to print, and for the sake of simplicity, only one page is printed for the old week.

        Private void Printdic_addpages (object  sender, Addpageseventargs e)        {            //  add page to print            printdic.addpage (TB);             // Report Add complete             printdic.addpagescomplete ();        }


Handles the Paginate event, which occurs when the Print dialog box is opened, and occurs when the user adjusts the parameters in the Print dialog box (such as modifying the page orientation) to recalculate the preview of the page.

        Private voidPrintdic_paginate (Objectsender, Paginateeventargs e) {printtaskoptions opt=task.            Options; //adjusts the direction of rotation of the printed content according to the orientation of the page            Switch(opt.) Orientation) { CasePRINTORIENTATION.DEFAULT:ROTTRF. Angle=0d;  Break;  CasePRINTORIENTATION.PORTRAIT:ROTTRF. Angle=0d;  Break;  CasePRINTORIENTATION.LANDSCAPE:ROTTRF. Angle=90d;  Break; }            //set the total number of pages in the preview pagePrintdic.setpreviewpagecount (1, previewpagecounttype.final); }

The following code adds a preview of a specific page.

        Private void Ongetpreviewpage (object  sender, Getpreviewpageeventargs e)        {            //  set page to preview this            . TB);        }


It's important to note that page previews and actual printing are two different things, so setpreviewpage just sets the UI element to preview, and the actual print is to add the page through the AddPage method in the Addpages event .

When the example is complete, you may have another problem, I do not have a printer, how to do? OK, the old week is very poor, there is no printer, but do not forget, the system has these features:

Yes, they do. Search for "devices and printers" to find them, so after running the sample, print the content directly as a. pdf document, and after printing, the. pdf file is stored in the documents directory.

Now run the application and click on the "Start printing" button.

The Print dialog box will then pop up.

Confirm to start printing, click "Print" button. The system will alert you with a toast notification when the print is complete. Shown is the printed. pdf file.

Well, isn't it a little tall on the feeling?

Sample code Download: Http://files.cnblogs.com/files/tcjiaan/printSample.zip

"Win 10 App development" Print UI elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.