From 13a5fda5f79f2c15eea512e6ec3de2ce60aa29ca Mon Sep 17 00:00:00 2001
From: Kurt Jung <kurt.w.jung@gmail.com>
Date: Sun, 11 Oct 2015 13:23:37 -0400
Subject: Conditionally sort two map iterations in template code; more to come.

---
 fpdf.go     | 27 +++++++++++++++++++++++----
 template.go | 21 +++++++++++++++++++--
 2 files changed, 42 insertions(+), 6 deletions(-)

diff --git a/fpdf.go b/fpdf.go
index b5ed8e6..08bcb2e 100644
--- a/fpdf.go
+++ b/fpdf.go
@@ -3366,10 +3366,29 @@ func (f *Fpdf) putxobjectdict() {
 			f.outf("/I%d %d 0 R", image.i, image.n)
 		}
 	}
-	for _, tpl := range f.templates {
-		id := tpl.ID()
-		if objID, ok := f.templateObjects[id]; ok {
-			f.outf("/TPL%d %d 0 R", id, objID)
+	{
+		var key int64
+		var keyList []int64
+		var tpl Template
+		for key = range f.templates {
+			keyList = append(keyList, key)
+		}
+		if f.catalogSort {
+			gensort(len(keyList),
+				func(a, b int) bool {
+					return keyList[a] < keyList[b]
+				},
+				func(a, b int) {
+					keyList[a], keyList[b] = keyList[b], keyList[a]
+				})
+		}
+		for _, key = range keyList {
+			tpl = f.templates[key]
+			// for _, tpl := range f.templates {
+			id := tpl.ID()
+			if objID, ok := f.templateObjects[id]; ok {
+				f.outf("/TPL%d %d 0 R", id, objID)
+			}
 		}
 	}
 }
diff --git a/template.go b/template.go
index 342032e..bf25c9f 100644
--- a/template.go
+++ b/template.go
@@ -17,6 +17,10 @@ package gofpdf
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+import (
+	"sort"
+)
+
 // CreateTemplate defines a new template using the current page size.
 func (f *Fpdf) CreateTemplate(fn func(*Tpl)) Template {
 	return newTpl(PointType{0, 0}, f.curPageSize, f.unitStr, f.fontDirStr, fn, f)
@@ -135,8 +139,21 @@ func (f *Fpdf) putTemplates() {
 		tTemplates := t.Templates()
 		if len(tImages) > 0 || len(tTemplates) > 0 {
 			f.out("/XObject <<")
-			for _, ti := range tImages {
-				f.outf("/I%d %d 0 R", ti.i, ti.n)
+			{
+				var key string
+				var keyList []string
+				var ti *ImageInfoType
+				for key = range tImages {
+					keyList = append(keyList, key)
+				}
+				if gl.catalogSort {
+					sort.Strings(keyList)
+				}
+				for _, key = range keyList {
+					// for _, ti := range tImages {
+					ti = tImages[key]
+					f.outf("/I%d %d 0 R", ti.i, ti.n)
+				}
 			}
 			for _, tt := range tTemplates {
 				id := tt.ID()
-- 
cgit v1.2.1-24-ge1ad