Showing posts with label C#. Show all posts
Showing posts with label C#. 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

Wednesday, 11 February 2009

Continue next step after exception

In some case it is handy to catch the exception and then continue with the next step right after the line that threw the exception.
There are several ways to do this, one is writing a try {} catch{} block around every line of code (which will of course pollute your code).

I found some code bits on the internet, which wrap this in a function.
I created a new Console application to demonstrate this.

First we create a class handling this functionality:

public static class Executer
{
public static void Execute(Action action, string errorMessageToLog)
{
try
{
action();
}
catch
{
Console.WriteLine(errorMessageToLog);
}
}
}


Then we create the code in the Main function of our console application:


static void Main(string[] args)
{
for (int counter = 10; counter > -10; counter--)
{
Executer.Execute(() =>
Console.WriteLine((10 / counter).ToString()), "Error Occured");
}
Console.Read();
}


When we run the code, you will notice that when counter = 0, a division by zero will occur, so this will throw an error. This error is displayed to the console and the next value of counter will be processed.