Saturday, August 11, 2012

Creating Your Own XPS Document

Well, I cobbled together enough sample code to create custom XPS documents, at least in terms of the process to go through.  I haven't explored content creation options, that is my next challenge.

The process to create an XPS document in very basic outline is:

1/            Create an XPSDocument Package
2/            Add a FixedDocumentSequence at the Package root
3/            Add a FixedDocument to the FixedDocumentSequence with an IXpsFixedDocumentWriter
4/            Add page to the FixedDocument using an IXpsFixedPageWriter
5/            Add resources to the page, put them in a Dictionary collection for ease of use
6/            Write the page content using XML to describe the elements
7/            Commit the page/s to the FixedDocument
8             Optionally attach a PrintTicket
9/            Commit the FixedDocument to the FixedDocumentSequence
10/          Close the Package

Resources are embedded fonts and images.
Page contents are text, graphics and brushes (ie text, drawing and pictures)

So, some lines of code to create the elements described above:
Firstly, Imports (really hard to find sample code with correct Imports!)
Imports System.Printing
Imports System.IO
Imports System.Windows.Xps.Packaging
Imports System.IO.Packaging
Imports System.Windows.Xps
Imports System.Xml

1/ Using XPSDocPackage as Package = XPSDocPackage.Open(strDocumentPath)

2/ Dim xpsDoc as XpsDocument = New XpsDcoument(XPSDocPackage)

3/ Dim documentSequenceWriter As IXpsFixedDocumentSequenceWriter =   xpsDoc  .AddFixedDocumentSequence()

4/ Dim fixedPageWriter As IXpsFixedPageWriter = fixedDocumentWriter.AddFixedPage()

5/ Dim resources As Dictionary(Of String, List(Of XpsResource))
        ' Collections of images and fonts used in the current page.
        Dim xpsImages As New List(Of XpsResource)
        Dim xpsFonts As New List(Of XpsResource)

        Dim p_xpsImage As XpsImage
        Dim p_xpsFont As XpsFont

        ' Add, Write, and Commit image1
        p_xpsImage = fixedPageWriter.AddImage(XpsImageType.JpegImageType)
        WriteToStream(p_xpsImage.GetStream(), image1)
        p_xpsImage.Commit()
        xpsImages.Add(p_xpsImage) ' Add image1 as a required resource.

        ' Add, Write, and Commit font 1
        p_xpsFont = fixedPageWriter.AddFont()
        WriteObfuscatedStream(p_xpsFont.Uri.ToString(), p_xpsFont.GetStream(), font1)
        p_xpsFont.Commit()
        xpsFonts.Add(p_xpsFont) ' Add font1 as a required resource.

        ' Return the image and font resources in a combined collection.
        resources.Add("XpsImage", xpsImages)
        resources.Add("XpsFont", xpsFonts)
6/ TO COME!! (I need to flesh out my knowledge here!)

7/  fixedPageWriter.Commit()

8/ TO COME!! (I need to flesh out my knowledge here!)

9/ fixedDocumentWriter.Commit()

10/  xpsDoc.Close()



No comments:

Post a Comment