XPS page event-based modifications | .NET

What is the event-based approach in programming?

The event-based approach in programming is a paradigm that revolves around the concept of events and event handling. In this model, the flow of the program is determined by events, which can be user actions (like mouse clicks or key presses), system-generated notifications, or messages from other applications. Here are some key aspects of the event-based approach:

Overall, the event-based approach is a powerful way to manage interactions and workflows within a program, making it particularly effective for applications that require responsiveness and user interaction.

Events that occur during the XPS document conversion

When you need to make changes to a specific page of an XPS document using the Aspose.Page API, you typically select the active document (if there are multiple documents in the XPS file), select the active page, and then make the changes themselves.

Now, suppose you need to make repeating changes to all pages in an XPS file and then convert the result to PDF or an image format. Some examples of such changes include placing a watermark over the pages or adding navigation hyperlinks. The direct way to make such changes involves traversing through the documents in the XPS package, traversing through the pages in the current active document, and then, finally, applying your changes. Therefore, the code to accomplish this task would look as follows:

 1for (int i = 1; i <= document.DocumentCount; i++)
 2{
 3    document.SelectActiveDocument(i);
 4    for (j = 1; j <= document.PageCount; j++)
 5    {
 6        document.SelectActivePage(j);
 7        // Your changes ...
 8    }
 9}
10document.SaveAsPdf("file-name.pdf", saveOptions);

If you also need to make some irregular changes before the repeating ones, this approach may lead to some confusion or excessive traversals through documents and pages, let alone these loops may seem a little cumbersome.

When you convert an XPS document to PDF or an image, the process occurs page by page. When the conversion job is ready to process the next page, it triggers a “before-page” event. The user can define the handling of such events by extending the BeforePageSavingEventHandler class, thereby taking advantage of some benefits outlined in the introductory section of this article.

Here, we will provide an example related to the case of navigation hyperlinks. And to make the task a little more complicated, we will convert only a subset of all pages to PDF, as specified by the PdfSaveOptions.PageNumbers property.

The event handler class

Below is the extension of the BeforePageSavingEventHandler class:

 1/// <summary>
 2/// The class to handle the before-page event while converting an XPS document.
 3/// </summary>
 4public class NavigationInjector : BeforePageSavingEventHandler
 5{
 6    // The font in which navigation hyperlinks and page numbers will be displayed.
 7    private readonly XpsFont _font;
 8    // The page numbers to convert.
 9    private readonly SortedList<int, int> _pageNumbers;
10
11    public NavigationInjector(XpsFont font, int[] pageNumbers)
12    {
13        _font = font;
14        if (pageNumbers == null)
15            return;
16
17        // Turn the page number array into a sorted collection of unique values.
18        _pageNumbers = new SortedList<int, int>();
19        foreach (int pn in pageNumbers)
20            _pageNumbers[pn] = 0;
21    }
22
23    public override void Handle(BeforeSavingEventArgs<PageAPI> args)
24    {
25        PageAPI api = args.ElementAPI;
26
27        XpsGlyphs glyphs;
28        // For all pages in the output PDF except the first one...
29        if (args.OutputPageNumber > 1)
30        {
31            // ...insert a hyperlink to the first page...
32            glyphs = api.CreateGlyphs(_font, 15f, 5f, api.Height - 10f, "[First]");
33            glyphs.Fill = api.CreateSolidColorBrush(Color.Blue);
34            glyphs.HyperlinkTarget = new XpsPageLinkTarget(_pageNumbers == null ? 1 : _pageNumbers.Keys[0]);
35            api.Add(glyphs);
36
37            // ...and to the previous page.
38            glyphs = api.CreateGlyphs(_font, 15f, 60f, api.Height - 10f, "[Prev]");
39            glyphs.Fill = api.CreateSolidColorBrush(Color.Blue);
40            glyphs.HyperlinkTarget = new XpsPageLinkTarget(
41                _pageNumbers == null ? args.AbsolutePageNumber - 1 : _pageNumbers.Keys[args.OutputPageNumber - 2]);
42            api.Add(glyphs);
43        }
44
45        // For all pages in the output PDF except the last one...
46        if ((_pageNumbers != null && args.OutputPageNumber < _pageNumbers.Count) ||
47            (_pageNumbers == null && args.OutputPageNumber < api.TotalPageCount))
48        {
49            // ...insert a hyperlink to the next page...
50            glyphs = api.CreateGlyphs(_font, 15f, 110f, api.Height - 10f, "[Next]");
51            glyphs.Fill = api.CreateSolidColorBrush(Color.Blue);
52            glyphs.HyperlinkTarget = new XpsPageLinkTarget(
53                _pageNumbers == null ? args.AbsolutePageNumber + 1 : _pageNumbers.Keys[args.OutputPageNumber]);
54            api.Add(glyphs);
55
56            // ...and to the last page.
57            glyphs = api.CreateGlyphs(_font, 15f, 160f, api.Height - 10f, "[Last]");
58            glyphs.Fill = api.CreateSolidColorBrush(Color.Blue);
59            glyphs.HyperlinkTarget = new XpsPageLinkTarget(
60                _pageNumbers == null ? api.TotalPageCount : _pageNumbers.Keys[_pageNumbers.Keys.Count - 1]);
61            api.Add(glyphs);
62        }
63
64        // Insert a page number in the bottom-right corner.
65        glyphs = api.CreateGlyphs(_font, 15f, api.Width - 20f, api.Height - 10f, args.OutputPageNumber.ToString());
66        glyphs.Fill = api.CreateSolidColorBrush(Color.Black);
67        api.Add(glyphs);
68
69        // Add an outline entry to display the links to the converted pages in the navigation pane of a PDF viewer.
70        api.AddOutlineEntry(string.Format("Page {0}", args.OutputPageNumber), 1, args.AbsolutePageNumber);
71    }
72}

The handler class should be aware of the pages we want to save as PDF in order to create the correct hyperlink targets. Therefore, the constructor should take the options’ array property as an argument. If the array of page numbers is specified, we create a sorted collection of them, avoiding duplicates at the same time. (By the way, this solution is not entirely accurate. Can you figure out what might cause inconsistency in the output?) We will also need an XpsFont object containing the font data for the hyperlink text.

The overridden Handle() method is where it all happens. The method’s argument is an object that contains the modification API for the current page, the document number within the XPS package, the absolute page number across all documents, the relative page number within the current document (which is equal to the previous number in case of only one document in the package), and the output page number (which is equal to the absolute page number when we convert the entire package).

The logic of the following two if blocks is quite straightforward. It is based on the analysis of the OutputPageNumber event argument to omit some of the links where appropriate: the [First] and [Prev] links will be added to all output pages except the first one, while the [Next] and [Last] links will appear on all pages except the last one. The logic is also tailored for both cases, whether page numbers are specified or not.

After the if blocks, there is code for adding a page number in the bottom-right corner of the page.

The last line adds the page’s outline entry, the item that will be displayed in the navigation pane of a PDF viewer (if supported).

The conversion code

Now that the “before-page” event handler is defined, we can write the code that converts the document:

 1// The path to the documents directory.
 2string dataDir = RunExamples.GetDataDir_WorkingWithPages();
 3// Open an XPS document
 4using (XpsDocument doc = new XpsDocument(dataDir + "Sample3.xps"))
 5// Create a font
 6using (Stream fontStream = File.OpenRead(dataDir + "arialbd.ttf"))
 7{
 8    // Create options for conversion to PDF
 9    PdfSaveOptions options = new PdfSaveOptions();
10    // Set the filter for the pages that need conversion
11    options.PageNumbers = new int[] { 2, 6, 7, 13 };
12    // Add the event handler that will execute right before the conversion of each page
13    options.BeforePageSavingEventHandlers.Add(new NavigationInjector(doc.CreateFont(fontStream), options.PageNumbers));
14    // Save resultant XPS document
15    doc.SaveAsPdf(dataDir + "ModifyPageOnConversion_out.pdf", options);
16}

We open an XPS file and then instantiate a stream object with the font data file. Next, we create an instance of the PdfSaveOptions class and specify the numbers of pages we need to convert. The next line is where the “before-page” event handler becomes “connected” to the conversion job via the BeforePageSavingEventHandlers collection option.

All that’s left to do is run the conversion to PDF using the document’s SaveAsPdf() method.

Conclusion

In this article, we explored the key points of the event-based approach in programming, examined the direct method for modifying pages of an XPS document, and learned a more advanced and sophisticated technique for making repeating changes to all output pages during the conversion process, using the insertion of navigation hyperlinks as an example.

For the complete examples, explore our Example project.

Have any questions about Aspose.Page?



Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.