Showing posts with label .NET General. Show all posts
Showing posts with label .NET General. Show all posts

Friday, 21 January 2011

Print Xaml in background - Part2 - the PrintTicket

Following my previous post on Printing Xaml code to XPS, here's the second part.
In this part, I explain how to attach "Page Settings" to the XpsDocument. This can be done by using the System.Printing.PrintTicket in your code.

In my example, I print to A3, landscape.

Define the printticket


1:private  static  PrintTicket  pt = new  PrintTicket ();

Fill it with the necessary data:


1:PrintQueue  pq = LocalPrintServer .GetDefaultPrintQueue();
2: 
3:pt = new  System.Printing.PrintTicket 
4:             {   OutputColor  = OutputColor .Color,
5:                 PageMediaType  = PageMediaType .Plain,
6:                 PageOrientation  = PageOrientation .Landscape,
7:                 PageMediaSize  = 
new PageMediaSize(PageMediaSizeName .ISOA3),
8:                 PageBorderless  = PageBorderless .Borderless
9:             };
10:System.Printing.ValidationResult result = 
pq.MergeAndValidatePrintTicket(pq.UserPrintTicket, pt);

Code the printing itself:

1: XpsDocument  document =
2:         new  XpsDocument (path + @"\\sample.xps" , System.IO.FileAccess .Write);
3: XpsDocumentWriter  writer =
4:     XpsDocument .CreateXpsDocumentWriter(document);
5: writer.WritingPrintTicketRequired +=
6:         new  WritingPrintTicketRequiredEventHandler (writer_WritingPrintTicketRequired);
7: writer.Write(myfixedDocumentToPrint, pt);

And finally the writer_WritingPrintTicketRequired function

1: static  void  writer_WritingPrintTicketRequired(object  sender, 
2:                         WritingPrintTicketRequiredEventArgs  e)
3: {
4:     e.CurrentPrintTicket = pt;
5: }


Have fun...

Friday, 14 January 2011

Print Xaml in background

Printing Xaml (WPF) files in background?  Is it possible? Yes, and it's easy!
The following code example will show you how.
Step 1: Create a console application
Step 2: Add references to ReachFramework.dll and WindowsBase.dll
Step 3: Create a xaml usercontrol
Step 4 Create your code in you main function

Xaml user Control example:

1: <Border BorderThickness="1" Height="57" Margin="12,37,267,0" Name="border1" VerticalAlignment="Top"> 
2:     <Border.BorderBrush> 
3:         <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"> 
4:             <GradientStop Color="#FFF10202" Offset="0" /> 
5:             <GradientStop Color="#FF0CDEED" Offset="1" /> 
6:         LinearGradientBrush> 
7:     Border.BorderBrush> 
8:     <StackPanel Orientation="Vertical" HorizontalAlignment="Stretch" VerticalAlignment="Center"> 
9:         <CheckBox Content="Test checkbox 1" Height="16" Name="checkBox1" Margin="5,0" BorderThickness="0" BorderBrush="{x:Null}" /> 
10:         <CheckBox Content="Test checkbox 2" Height="16" Name="checkBox2" Margin="5,0" IsChecked="True" BorderThickness="0" BorderBrush="{x:Null}" /> 
11:     StackPanel> 
12: Border> 
13: <Label Content="This is a test of printing to an XPS Document" Height="28" HorizontalAlignment="Left" Margin="12,1,0,0" Name="label1" VerticalAlignment="Top" Width="479" FontWeight="Black" Foreground="#FF0000E1" /> 
14: <Image Height="200" HorizontalAlignment="Left" Margin="244,76,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="247" Source="/WpfApplication;component/Images/Penguins.jpg" /> 
15: <TextBox Height="200" HorizontalAlignment="Left" Margin="12,99,0,0" Name="textBox1" VerticalAlignment="Top" Width="224" Text="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." TextWrapping="Wrap" BorderBrush="{x:Null}" /> 
16: <Rectangle Height="1" HorizontalAlignment="Left" Margin="5,30,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="485" />
17: 

Main fucnction code:


1: FixedDocument  myfixedDocumentToPrint = new  FixedDocument ();
2: FixedPage  myPageToPrint = new  FixedPage ();
3: PageContent  pc = new  PageContent ();
4: PrintPage  printpageXaml = new  PrintPage ();
5: 
6: myPageToPrint.SnapsToDevicePixels = true ;
7: myPageToPrint.VerticalAlignment = 
8:     System.Windows.VerticalAlignment .Stretch;
9: myPageToPrint.HorizontalAlignment = 
10:     System.Windows.HorizontalAlignment .Stretch;
11: myPageToPrint.Height = 11.69 * 96;
12: myPageToPrint.Width = 8.27 * 96;
13: 
14: myPageToPrint.Children.Add(printpageXaml);
15: ((IAddChild )pc).AddChild(myPageToPrint);
16: myfixedDocumentToPrint.Pages.Add(pc);
17: 
18: var  assembly = System.Reflection.Assembly .GetExecutingAssembly();
19: var  path = assembly.Location.Replace(assembly.ManifestModule.Name, "" );
20: 
21: XpsDocument  document = 
22:     new  XpsDocument ( path + @"\\sample.xps" , System.IO.FileAccess .Write);
23: XpsDocumentWriter  writer = 
24:     XpsDocument .CreateXpsDocumentWriter(document);
25: writer.Write(myfixedDocumentToPrint);
26: writer = null ;
27: document.Close();
28: 


Important remark: you function has to be STAThread.

You see, nothing difficult about this one ... have fun.
J.

Thursday, 4 February 2010

Export Excel sheet to PDF document using Aspose

Last month I stumbled upon a business issue, which would allow an application to extract a single worksheet out of an excel document and save it as a PDF document.

Using Aspose, this can be done easily!

public class XlsToPdf
    {
        public void ExportSheet()
        {

            ///lets say we have an xls document containing 6 sheets
            ///each strongly named like sheet1 => sheet6
            ///suppose that you need to save sheet5 as a pdf document.

            string sourceWorkBook = "source.xls";
            string destinationDocument = "Destination.pdf";

            Aspose.Cells.Workbook sourceWb = new Aspose.Cells.Workbook();
            sourceWb.Open(sourceWorkBook);

            foreach (Aspose.Cells.Worksheet workSheet in sourceWb.Worksheets)
            {
                if (!workSheet.Name.ToUpper().Contains("sheet5"))
                    workSheet.IsVisible = false;
            }


            ///First thing to do is to save the xls in xml format, 
            ///but the formattype used already refers to PDF
            string destinationDocumentXml = "destination.xml";
            sourceWb.Save(destinationDocumentXml, 
                Aspose.Cells.FileFormatType.AsposePdf);


            Aspose.Pdf.Pdf pdfDocument = new Aspose.Pdf.Pdf();
            //bind the created xml to the PDFDoc you intialized.
            pdfDocument.BindXML(destinationDocumentXml, null);
            //Save...
            pdfDocument.Save(destinationDocument);

            ///If necessary, you can cleanup and remove 
            ///the intermediate files created
            ///using DirectoryInfo and files delet techniques from the System.IO
            ///...code goes here
        }
    }
You can find the Aspose help here: Cells and PDF

Have fun

Friday, 29 May 2009

Parser error : “The async attribute on the page directive is not allowed in this page”

Last week I bumped upon this error while I was trying to do an asynchrounous WCF service call from my "MS Project 2007 Web Access"-custom user control.

Turns out that you cannot set the Async="true" atttibute in the page directive af an aspx page in the Project Web Access.

The reason for this? Very simple ... the that SharePoint’s SPPageParserFilter class blocks some page directive attributes. When you use other attrubutes than the following list, you will get the error "The 'xxx' attribute on the page directive is not allowed in this page."

The list:

  • autoeventwireup
  • buffer
  • classname
  • codebehind
  • codepage
  • compileroptions
  • contenttype
  • culture
  • debug
  • description
  • enabletheming
  • enableviewstate
  • enableviewstatemac
  • errorpage
  • explicit
  • inherits
  • language
  • lcid
  • lineparagmas
  • maintainscrollpositiononpostback
  • masterpagefile
  • responsencoding
  • smartnavigation
  • strict
  • stylesheettheme
  • targetschema
  • theme
  • title

To take care of this issue we chose to have a webservice call which will handle the Ascynhrounous WCF call, and from our web user control we called this webservice method sycnhrounous.... Maybe this is not the best solution, but we really had an issue, so a quick fix was necessary here...

Tuesday, 12 May 2009

Community Day 2009

Third Edition of Microsoft Community Day, a networking and knowledge sharing event.
Register yourself and be there!


Monday, 23 February 2009

Adding toolbox items crashes VS2008

Problem:

When right-clicking the toolbox in an open Visual Studio 2008 environment, I had some strange behavior when selecting "Choose Items ... ".
In fact there was no behavior at all ... my development environment just crashed!!!

Rather annoying if you try to add some new items don't you think?

Cause:

The problem is caused by the Power Commands 2008 Addons for Visual Studio.

Resolution:

Uninstall the Power Commands 2008 Addons...