/** * The class to handle the before-page event while converting an XPS document. */ public static class NavigationInjector extends BeforePageSavingEventHandler { private final XpsFont _font; private List _pageNumbers; public NavigationInjector(XpsFont font, int[] pageNumbers) { _font = font; if (pageNumbers == null || pageNumbers.length == 0) return; // Turn the page number array into a sorted collection of unique values. SortedMap map = new TreeMap(); for (int pn : pageNumbers) map.put(pn, 0); _pageNumbers = new ArrayList(map.keySet()); } /** * The action itself to be triggered on a before-page event. * @param args The even arguments. */ @Override public void handle(BeforeSavingEventArgs args) { PageAPI api = args.getElementAPI(); XpsGlyphs glyphs; // For all pages in the output PDF except the first one... if (args.getOutputPageNumber() > 1) { // ...insert a hyperlink to the first page... glyphs = api.createGlyphs(_font, 15f, 5f, api.getHeight() - 10f, "[First]"); glyphs.setFill(api.createSolidColorBrush(Color.BLUE)); glyphs.setHyperlinkTarget(new XpsPageLinkTarget(_pageNumbers == null ? 1 : _pageNumbers.get(0))); api.add(glyphs); // ...and to the previous page. glyphs = api.createGlyphs(_font, 15f, 60f, api.getHeight() - 10f, "[Prev]"); glyphs.setFill(api.createSolidColorBrush(Color.BLUE)); glyphs.setHyperlinkTarget(new XpsPageLinkTarget( _pageNumbers == null ? args.getAbsolutePageNumber() - 1 : _pageNumbers.get(args.getOutputPageNumber() - 2))); api.add(glyphs); } // For all pages in the output PDF except the last one... if ((_pageNumbers != null && args.getOutputPageNumber() < _pageNumbers.size()) || (_pageNumbers == null && args.getOutputPageNumber() < api.getTotalPageCount())) { // ...insert a hyperlink to the next page... glyphs = api.createGlyphs(_font, 15f, 110f, api.getHeight() - 10f, "[Next]"); glyphs.setFill(api.createSolidColorBrush(Color.BLUE)); glyphs.setHyperlinkTarget(new XpsPageLinkTarget( _pageNumbers == null ? args.getAbsolutePageNumber() + 1 : _pageNumbers.get(args.getOutputPageNumber()))); api.add(glyphs); // ...and to the last page. glyphs = api.createGlyphs(_font, 15f, 160f, api.getHeight() - 10f, "[Last]"); glyphs.setFill(api.createSolidColorBrush(Color.BLUE)); glyphs.setHyperlinkTarget(new XpsPageLinkTarget( _pageNumbers == null ? api.getTotalPageCount() : _pageNumbers.get(_pageNumbers.size() - 1))); api.add(glyphs); } // Insert a page number in the bottom-right corner. glyphs = api.createGlyphs(_font, 15f, api.getWidth() - 20f, api.getHeight() - 10f, Integer.toString(args.getOutputPageNumber())); glyphs.setFill(api.createSolidColorBrush(Color.BLACK)); api.add(glyphs); // Add an outline entry to display the links to the converted pages in the navigation pane of a PDF viewer. api.addOutlineEntry(MessageFormat.format("Page {0}", args.getOutputPageNumber()), 1, args.getAbsolutePageNumber()); } }