c# - Print page that contain ListBox or GridView -


printing page contain richtextblock. richtextblock used contain text , can use following code print. if page contains listbox or gridview, need on how print this. possible use richtextblock contain listbox , detect overflow continuation printing? appreciate if can provide sample , reference or tutorial on this. thanks

--- update
listbox contain data :

itemname itemcode price qty ..

------
------

---- update (2)

how add header , footer ?

header

customer
addr
date :
order no

brand    code     price     qty

   printdocument document = null; iprintdocumentsource source = null; list pages = null; frameworkelement page1; protected event eventhandler pagescreated; protected const double left = 0.075; protected const double top = 0.03;    protected override void onnavigatedto(navigationeventargs e)  {      //--- register print       document = new printdocument();     source = document.documentsource;      //--- handle document's events      document.paginate += printdocument_paginate;     document.getpreviewpage += printdocument_getpreviewpage;     document.addpages += printdocument_addpages;       printmanager manager = printmanager.getforcurrentview();     manager.printtaskrequested += manager_printtaskrequested;       pages = new list();      preparecontent();    }  

my answer based on helper class of printing textbox text. have tweaked sample supporting listbox. check out below code.

xaml

<grid background="{staticresource applicationpagebackgroundthemebrush}">     <canvas x:name="printcanvas" opacity="0" />     <stackpanel margin="100">         <listbox height="500" width="400" x:name="mylbx">         <listbox.itemtemplate>             <datatemplate>                 <stackpanel>                     <textblock fontsize="20">                         <run text="item name : "/> <run text="{binding itemname}" />                     </textblock>                     <textblock fontsize="20">                         <run text="item code : "/> <run text="{binding itemcode}" />                     </textblock>                     <textblock fontsize="20">                         <run text="price : "/> <run text="{binding price}" />                     </textblock>                     <textblock fontsize="20">                         <run text="quantity : "/> <run text="{binding quantity}" />                     </textblock>                 </stackpanel>             </datatemplate>         </listbox.itemtemplate>     </listbox>         <button content="print listbox" click="btnprint_click" horizontalalignment="center" margin="0,20,0,0"/>     </stackpanel> </grid> 

c#

protected override void onnavigatedto(navigationeventargs e) {     mylbx.itemssource = new list<itemmodel>      {         new itemmodel("item name 8", "item code 10", 180.76, 13),         new itemmodel("item name 19", "item code 16", 153.68, 14),         new itemmodel("item name 8", "item code 18", 195.71, 10),         new itemmodel("item name 11", "item code 16", 112.71, 14),         new itemmodel("item name 5", "item code 11", 156.09, 18),         new itemmodel("item name 7", "item code 8", 124.38, 18),         new itemmodel("item name 16", "item code 16", 129.31, 15),         new itemmodel("item name 13", "item code 5", 187.55, 19),         new itemmodel("item name 6", "item code 6", 146.10, 14),         new itemmodel("item name 19", "item code 5", 154.84, 18),         new itemmodel("item name 15", "item code 5", 149.69, 18),         new itemmodel("item name 17", "item code 5", 155.39, 6),         new itemmodel("item name 6", "item code 14", 119.19, 12),         new itemmodel("item name 14", "item code 19", 186.40, 19),         new itemmodel("item name 7", "item code 18", 178.30, 8),         new itemmodel("item name 12", "item code 17", 105.60, 8),         new itemmodel("item name 5", "item code 19", 120.94, 9),         new itemmodel("item name 9", "item code 12", 164.13, 19),         new itemmodel("item name 18", "item code 15", 119.24, 7),         new itemmodel("item name 16", "item code 10", 106.30, 16)     }; }  private async void btnprint_click(object sender, routedeventargs e) {     string printtext = "";     foreach (itemmodel item in mylbx.items)     {         printtext += "item name : " + item.itemname + "\n";         printtext += "item code : " + item.itemcode + "\n";         printtext += "price : " + item.price + "\n";         printtext += "quantity : " + item.quantity + "\n\n";     }      await printhelper.showprintuiasync(printcanvas, printtext, "printedlistbox.pdf"); } 

printhelper.cs

public class printhelper {     private static canvas printingroot { get; set; }      private static string texttobeprint { get; set; }      private static string printingfilename { get; set; }      internal static int currentpreviewpage;      private static printdocument printdocument = null;      private static iprintdocumentsource printdocumentsource = null;      internal static list<pageloadstate> printpreviewpages = new list<pageloadstate>();      private const double applicationcontentmarginleft = 0.075;      private const double applicationcontentmargintop = 0.03;      private static bool showtext     {         { return ((int)imagetext & (int)displaycontent.text) == (int)displaycontent.text; }     }      internal static displaycontent imagetext = displaycontent.textandimages;      private static void printtaskrequested(printmanager sender, printtaskrequestedeventargs e)     {         printtask printtask = e.request.createprinttask(printingfilename, sourcerequested => sourcerequested.setsource(printdocumentsource));     }      private static void registerforprinting()     {         // create printdocument.         printdocument = new printdocument();          // save documentsource.         printdocumentsource = printdocument.documentsource;          // add event handler creates preview pages.         printdocument.paginate += createprintpreviewpages;          // add event handler provides specified preview page.         printdocument.getpreviewpage += getprintpreviewpage;          // add event handler provides final print pages.         printdocument.addpages += addprintpages;           // create printmanager , add handler printing initialization.         printmanager printman = printmanager.getforcurrentview();         printman.printtaskrequested += printtaskrequested;     }      private static void unregisterforprinting()     {         // set instance of printdocument null.         printdocument = null;          // remove handler printing initialization.         printmanager printman = printmanager.getforcurrentview();         printman.printtaskrequested -= printtaskrequested;     }      private static event eventhandler pagescreated;      private static void createprintpreviewpages(object sender, paginateeventargs e)     {         // clear cache of preview pages          printpreviewpages.clear();          // clear printing root of preview pages         printingroot.children.clear();          // variable keeps track of last richtextblockoverflow element added page printed         richtextblockoverflow lastrtboonpage;          // printtaskoptions         printtaskoptions printingoptions = ((printtaskoptions)e.printtaskoptions);          // page description deterimine how big page         printpagedescription pagedescription = printingoptions.getpagedescription(0);          // know there @ least 1 page printed. passing null first parameter         // addoneprintpreviewpage tells function add first page.         lastrtboonpage = addoneprintpreviewpage(null, pagedescription);          // know there more pages added long last richtextboxoverflow added print preview         // page has content         while (lastrtboonpage.hasoverflowcontent)         {             lastrtboonpage = addoneprintpreviewpage(lastrtboonpage, pagedescription);         }          if (pagescreated != null)             pagescreated.invoke(printpreviewpages, null);          // report number of preview pages created         printdocument.setpreviewpagecount(printpreviewpages.count, previewpagecounttype.intermediate);     }      private static void getprintpreviewpage(object sender, getpreviewpageeventargs e)     {         interlocked.exchange(ref currentpreviewpage, e.pagenumber - 1);          pageloadstate pageloadstate = printpreviewpages[e.pagenumber - 1];          if (!pageloadstate.ready)         {             // notify user content not available yet             // apps may opt don't show preview untill complete , use await isreadyasync             //rootpage.notifyuser("image loading not complete, previewing text", notifytype.errormessage);         }          // set preview if images failed load         printdocument.setpreviewpage(e.pagenumber, pageloadstate.page);     }      private static void addprintpages(object sender, addpageseventargs e)     {         // loop on of preview pages , add each 1  add each page printied         (int = 0; < printpreviewpages.count; i++)         {             // should have pages ready @ point...             printdocument.addpage(printpreviewpages[i].page);         }          // indicate of print pages have been provided         printdocument.addpagescomplete();     }      private static richtextblockoverflow addoneprintpreviewpage(richtextblockoverflow lastrtboadded, printpagedescription printpagedescription)     {         // create cavase represents page          canvas page = new canvas();         page.width = printpagedescription.pagesize.width;         page.height = printpagedescription.pagesize.height;          pageloadstate pagestate = new pageloadstate(page, printpreviewpages.count);         pagestate.readyaction = async (pagenumber, currentpage) =>         {             // ignore if not current page             if (interlocked.compareexchange(ref currentpreviewpage, currentpreviewpage, pagenumber) == pagenumber)             {                 await window.current.dispatcher.runasync(windows.ui.core.coredispatcherpriority.normal, () =>                 {                     //await new windows.ui.popups.messagedialog("content loaded").showasync();                     printdocument.setpreviewpage(pagenumber + 1, currentpage);                 });             }         };          // create grid contains actual content printed         grid content = new grid();          // margins size         // if imageablerect smaller app provided margins use imageablerect         double marginwidth = math.max(printpagedescription.pagesize.width - printpagedescription.imageablerect.width,                                     printpagedescription.pagesize.width * applicationcontentmarginleft * 2);          double marginheight = math.max(printpagedescription.pagesize.height - printpagedescription.imageablerect.height,                                         printpagedescription.pagesize.height * applicationcontentmargintop * 2);          // set content size based on given margins         content.width = printpagedescription.pagesize.width - marginwidth;         content.height = printpagedescription.pagesize.height - marginheight;          // set content margins         content.setvalue(canvas.leftproperty, marginwidth / 2);         content.setvalue(canvas.topproperty, marginheight / 2);          // add rowdefinitions grid content printed         rowdefinition rowdef = new rowdefinition();          rowdef.height = new gridlength(2.5, gridunittype.star);         content.rowdefinitions.add(rowdef);         rowdef = new rowdefinition();         rowdef.height = new gridlength(3.5, gridunittype.star);         content.rowdefinitions.add(rowdef);         rowdef = new rowdefinition();         rowdef.height = new gridlength(1.5, gridunittype.star);         content.rowdefinitions.add(rowdef);          // if lastrtboadded null know creating first page.          bool isfirstpage = lastrtboadded == null;          frameworkelement previousltconpage = null;         richtextblockoverflow rtbo = new richtextblockoverflow();         // create linked containers , and add them content grid         if (isfirstpage)         {             // first linked container in chain of linked containers is richtextblock             richtextblock rtbl = new richtextblock();             rtbl.setvalue(grid.rowproperty, 0);             rtbl = addcontenttortbl(rtbl);             int = rtbl.blocks.count();             rtbl.foreground = new solidcolorbrush(windows.ui.colors.black);             content.children.add(rtbl);              // save richtextblock last linked container added page             previousltconpage = rtbl;         }         else         {             // not first page first element on page has             // richtextboxoverflow links last richtextblockoverflow added             // previous page.             rtbo = new richtextblockoverflow();             rtbo.setvalue(grid.rowproperty, 0);             content.children.add(rtbo);              // keep text flowing previous page page setting linked text container             // created (rtbo) overflowcontenttarget last linked text container previous page              lastrtboadded.overflowcontenttarget = rtbo;              // save richtextblockoverflow last linked container added page             previousltconpage = rtbo;         }          if (showtext)         {             // create next linked text container on page.             rtbo = new richtextblockoverflow();             rtbo.setvalue(grid.rowproperty, 1);              // add richtextblockoverflow content printed.             content.children.add(rtbo);              // add new richtextblockoverflow chain of linked text containers. check             // see if previous container richtextblock or richtextblockoverflow.             if (previousltconpage richtextblock)                 ((richtextblock)previousltconpage).overflowcontenttarget = rtbo;             else                 ((richtextblockoverflow)previousltconpage).overflowcontenttarget = rtbo;              // save last linked text container added chain             previousltconpage = rtbo;              // create next linked text container on page.             rtbo = new richtextblockoverflow();             rtbo.setvalue(grid.rowproperty, 2);             content.children.add(rtbo);              // add new richtextblockoverflow chain of linked text containers. don't have check             // type of previous linked container time because know it's richtextblockoverflow element             ((richtextblockoverflow)previousltconpage).overflowcontenttarget = rtbo;         }         // done creating content page. add canvas represents page         page.children.add(content);          // add newley created page printing root part of visual tree , force go         // through layout linked containers correctly distribute content inside them.         printingroot.children.add(page);         printingroot.invalidatemeasure();         printingroot.updatelayout();          // add newley created page list of pages         printpreviewpages.add(pagestate);          // return last linked container added page         return rtbo;     }      private static richtextblock addcontenttortbl(richtextblock rtbl)     {         // create run , give content         run run = new run();         run.text = texttobeprint;          // create paragraph, set it's property according text box.         paragraph para = new paragraph();         para.fontsize = 20;          para.inlines.add(run);         // add paragraph blocks collection of richtextblock         rtbl.blocks.add(para);         return rtbl;     }      public static async task showprintuiasync(canvas printingcanvas, string texttobeprint, string filename)     {         if (printingcanvas == null)             throw new nullreferenceexception("canvas must present in xaml. showing print preview.");          if (string.isnullorwhitespace(filename))             throw new argumentexception("the file name document going print must not empty or white space.");          printingroot = printingcanvas;         texttobeprint = texttobeprint;         printingfilename = filename;         unregisterforprinting();         registerforprinting();         await printmanager.showprintuiasync();     } }  public class pageloadstate {     private countdownevent loadingelements;      public action<int, uielement> readyaction { get; set; }      private int pagenumber;      private uielement page;      public uielement page     {         { return page; }     }      public pageloadstate(uielement page, int pagenumber)     {         this.page = page;         this.pagenumber = pagenumber;         loadingelements = new countdownevent(0);     }      private void setelementcomplete()     {         loadingelements.signal();     }      public void listenforcompletion(bitmapimage bitmap)     {         if (loadingelements.currentcount == 0)         {             // event signaled. manually set count 1 , "arm" event.             loadingelements.reset(1);         }         else         {             // addcount throw if event in signaled state.             loadingelements.addcount();         }         bitmap.imageopened += (s, e) => setelementcomplete();     }      public bool ready     {                 {             var ready = loadingelements.currentcount == 0;             if (!ready)             {                 // request made , content not ready, serve once it's complete                 task.run(async () =>                 {                     await isreadyasync();                     readyaction(pagenumber, page);                 });             }              return ready;         }     }      public async task isreadyasync()     {         await task.run(() => { loadingelements.wait(); });     } }  internal enum displaycontent : int {     text = 1,      images = 2,      textandimages = 3 } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -