Merge pull request #258 from dennwc/stable_creator

Make PDF output stable when using custom fonts
This commit is contained in:
Gunnsteinn Hall 2018-11-29 01:16:24 +00:00 committed by GitHub
commit dd145a2d15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -11,6 +11,8 @@ package creator
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
goimage "image"
"io/ioutil"
@ -2932,3 +2934,36 @@ func TestAllOptimizations(t *testing.T) {
t.Errorf("Optimization failed: size not changed %d vs %d", fileInfo.Size(), fileInfoOptimized.Size())
}
}
// Tests that creator's output is predictable and returns exactly the same file given the same input.
func TestCreatorStable(t *testing.T) {
writePDF := func() string {
creator := New()
font, err := model.NewCompositePdfFontFromTTFFile(testWts11TTFFile)
if err != nil {
t.Fatalf("Fail: %v\n", err)
}
p := creator.NewParagraph("你好")
p.SetFont(font)
err = creator.Draw(p)
if err != nil {
t.Fatalf("Fail: %v\n", err)
}
h := md5.New()
err = creator.Write(h)
if err != nil {
t.Fatalf("Fail: %v\n", err)
}
return hex.EncodeToString(h.Sum(nil))
}
h1 := writePDF()
h2 := writePDF()
if h1 != h2 {
t.Fatal("output is not stable")
}
}

View File

@ -8,6 +8,7 @@ package model
import (
"errors"
"io/ioutil"
"sort"
"github.com/unidoc/unidoc/common"
"github.com/unidoc/unidoc/pdf/core"
@ -412,6 +413,10 @@ func NewCompositePdfFontFromTTFFile(filePath string) (*PdfFont, error) {
for r := range ttf.Chars {
runes = append(runes, r)
}
// make sure runes are sorted so PDF output is stable
sort.Slice(runes, func(i, j int) bool {
return runes[i] < runes[j]
})
k := 1000.0 / float64(ttf.UnitsPerEm)