سؤال

XPS Printer allows us to create xps file no matter if from an image or txt or doc file.

I would like to do the same just programmatically in c#.

How do I send a file to xps printer and let the printer convert it to .xps file?

Any ideas?

I Google this but haven't found much so far.

هل كانت مفيدة؟

المحلول

It is possible also to use print queue to print to the XPS document writer but it will always show the file dialog.

See below other alternatives to convert and print to XPS file.

Programmatically converting files to XPS

This is not as simple as you wish many users out there have tried and there is many different ways to accomplish it all which arent the best.

One way (easiest way) to convert documents to XPS would be to use WORD 2007+ API to do it. See below a snipped from this MSDN forum question

To programmatically convert docx to xps using Word 2007 see Document.ExportAsFixedFormat in the Word Object Model Reference (http://msdn2.microsoft.com/en-us/library/Bb256835.aspx). However, since this is a server-side scenario you should take note of KB 257757 Considerations for server-side Automation of Office (see http://support.microsoft.com/kb/257757).

Printing Images to XPS

You can easily print an Image to XPS file using the code below. The code below is WPF example the image you pass into the write method needs to be wrapped in a canvas see this post for an example: http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image-xps-document-or-raw-xaml/

XpsDocument xpsd = new XpsDocument("C:\\YourXPSFileName.xps", FileAccess.ReadWrite);
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(YourImageYouWishToWrite);

See an extended example below:

public void Export(Uri path, Canvas surface)
{
  if (path == null) return;

  // Save current canvas transorm
  Transform transform = surface.LayoutTransform;
  // Temporarily reset the layout transform before saving
  surface.LayoutTransform = null;

  // Get the size of the canvas
  Size size = new Size(surface.Width, surface.Height);
  // Measure and arrange elements
  surface.Measure(size);
  surface.Arrange(new Rect(size));

  // Open new package
  Package package = Package.Open(path.LocalPath, FileMode.Create);
  // Create new xps document based on the package opened
  XpsDocument doc = new XpsDocument(package);
  // Create an instance of XpsDocumentWriter for the document
  XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
  // Write the canvas (as Visual) to the document
  writer.Write(surface);
  // Close document
  doc.Close();
  // Close package
  package.Close();

  // Restore previously saved layout
  surface.LayoutTransform = transform;
}

There are third party tools that allow you to print PDFs and other file formats to XPS.

Printing XPS files

It is possible to print XPS Documents programmatically You will need .Net 4 at least for this solution.

The example below uses the Print dialog from WPF and some of the classes from System.Windows.Xps and System.Printing.

The code below will print the Xps file to the default printer on the system however if you want to print to a different printer or even print to a print server you need to change the PrintQueue object on the print dialog.

Which is quite simple using the System.Printing namespace.

See the example below.

Please bear in mind that because it is using the WPF dialog it needs to run on a STATThread model.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;

namespace ConsoleApplication
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            PrintDialog dlg = new PrintDialog();
            XpsDocument xpsDoc = new XpsDocument(@"C:\DATA\personal\go\test.xps", System.IO.FileAccess.Read);
            dlg.PrintDocument(xpsDoc.GetFixedDocumentSequence().DocumentPaginator, "Document title");

        }
    }
}

See below some Helpful links.

  1. Xps Document documentation
  2. Print Dialog from WPF documentation
  3. System.Printing namespace documentation

Hope this helps and fit your needs

نصائح أخرى

class Program
{
    [System.MTAThreadAttribute()] // Added for clarity, but this line is redundant because MTA     is the default. 
    static void Main(string[] args)
    {
        // Create the secondary thread and pass the printing method for  
        // the constructor's ThreadStart delegate parameter. The BatchXPSPrinter 
        // class is defined below.
        Thread printingThread = new Thread(BatchXPSPrinter.PrintXPS);

        // Set the thread that will use PrintQueue.AddJob to single threading.
        printingThread.SetApartmentState(ApartmentState.STA);

        // Start the printing thread. The method passed to the Thread  
        // constructor will execute.
        printingThread.Start();

    }//end Main

}//end Program class 

public class BatchXPSPrinter
{
    public static void PrintXPS()
    {
        // Create print server and print queue.
        LocalPrintServer localPrintServer = new LocalPrintServer();
        PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

        // Prompt user to identify the directory, and then create the directory object.
        Console.Write("Enter the directory containing the XPS files: ");
        String directoryPath = Console.ReadLine();
        DirectoryInfo dir = new DirectoryInfo(directoryPath);

        // If the user mistyped, end the thread and return to the Main thread. 
        if (!dir.Exists)
        {
            Console.WriteLine("There is no such directory.");
        }
        else
        {
            // If there are no XPS files in the directory, end the thread  
            // and return to the Main thread. 
            if (dir.GetFiles("*.xps").Length == 0)
            {
                Console.WriteLine("There are no XPS files in the directory.");
            }
            else
            {
                Console.WriteLine("\nJobs will now be added to the print queue.");
                Console.WriteLine("If the queue is not paused and the printer is working, jobs       will begin printing.");

                // Batch process all XPS files in the directory. 
                foreach (FileInfo f in dir.GetFiles("*.xps"))
                {
                    String nextFile = directoryPath + "\\" + f.Name;
                    Console.WriteLine("Adding {0} to queue.", nextFile);

                    try
                    {
                        // Print the Xps file while providing XPS validation and progress     notifications.
                        PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob(f.Name,     nextFile, false);
                    }
                    catch (PrintJobException e)
                    {
                        Console.WriteLine("\n\t{0} could not be added to the print queue.", f.Name);
                        if (e.InnerException.Message == "File contains corrupted data.")
                        {
                            Console.WriteLine("\tIt is not a valid XPS file. Use the isXPS Conformance Tool to debug it.");
                        }
                        Console.WriteLine("\tContinuing with next XPS file.\n");
                    }

                }// end for each XPS file

            }//end if there are no XPS files in the directory

        }//end if the directory does not exist

        Console.WriteLine("Press Enter to end program.");
        Console.ReadLine();

    }// end PrintXPS method

}// end BatchXPSPrinter class
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top