From 99f3184879e62a3a58a3005df665f03aead17e57 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 19:28:50 +0200 Subject: [PATCH 1/7] define slices with a var instead of an empty literal --- pdf/contentstream/encoding.go | 2 +- pdf/contentstream/parser.go | 8 ++++---- pdf/contentstream/utils.go | 8 ++++---- pdf/core/encoding.go | 12 ++++++------ pdf/core/parser.go | 6 +++--- pdf/core/primitives.go | 8 ++++---- pdf/core/utils.go | 4 ++-- pdf/creator/block.go | 2 +- pdf/creator/creator.go | 2 +- pdf/creator/division.go | 2 +- pdf/creator/image.go | 2 +- pdf/creator/paragraph.go | 6 +++--- pdf/creator/styled_paragraph.go | 8 ++++---- pdf/creator/table.go | 2 +- pdf/creator/utils.go | 2 +- pdf/extractor/text.go | 2 +- pdf/fdf/fielddata.go | 2 +- pdf/internal/cmap/cmap.go | 10 +++++----- pdf/internal/cmap/cmap_test.go | 4 ++-- pdf/internal/cmap/parser.go | 2 +- pdf/internal/sampling/resample.go | 4 ++-- pdf/internal/strutils/encoding.go | 2 +- pdf/internal/textencoding/cmap.go | 2 +- pdf/internal/textencoding/utils.go | 2 +- pdf/model/colorspace.go | 26 +++++++++++++------------- pdf/model/flatten.go | 4 ++-- pdf/model/font.go | 4 ++-- pdf/model/font_test.go | 2 +- pdf/model/fontfile.go | 2 +- pdf/model/fonts/ttfparser.go | 2 +- pdf/model/form.go | 6 +++--- pdf/model/functions.go | 8 ++++---- pdf/model/image.go | 8 ++++---- pdf/model/optimize/optimize_test.go | 2 +- pdf/model/page.go | 6 +++--- pdf/model/reader.go | 4 ++-- pdf/model/writer.go | 4 ++-- pdf/ps/exec.go | 2 +- pdf/ps/parser.go | 2 +- 39 files changed, 93 insertions(+), 93 deletions(-) diff --git a/pdf/contentstream/encoding.go b/pdf/contentstream/encoding.go index 77435e1b..7de12745 100644 --- a/pdf/contentstream/encoding.go +++ b/pdf/contentstream/encoding.go @@ -301,7 +301,7 @@ func newMultiEncoderFromInlineImage(inlineImage *ContentStreamInlineImage) (*cor // Prepare the decode params array (one for each filter type) // Optional, not always present. var decodeParamsDict *core.PdfObjectDictionary - decodeParamsArray := []core.PdfObject{} + var decodeParamsArray []core.PdfObject if obj := inlineImage.DecodeParms; obj != nil { // If it is a dictionary, assume it applies to all dict, isDict := obj.(*core.PdfObjectDictionary) diff --git a/pdf/contentstream/parser.go b/pdf/contentstream/parser.go index f992c361..517be764 100644 --- a/pdf/contentstream/parser.go +++ b/pdf/contentstream/parser.go @@ -255,7 +255,7 @@ func (csp *ContentStreamParser) parseNumber() (core.PdfObject, error) { func (csp *ContentStreamParser) parseString() (*core.PdfObjectString, error) { csp.reader.ReadByte() - bytes := []byte{} + var bytes []byte count := 1 for { bb, err := csp.reader.Peek(1) @@ -277,7 +277,7 @@ func (csp *ContentStreamParser) parseString() (*core.PdfObjectString, error) { return core.MakeString(string(bytes)), err } - numeric := []byte{} + var numeric []byte numeric = append(numeric, b) for _, val := range bb { if core.IsOctalDigit(val) { @@ -340,7 +340,7 @@ func (csp *ContentStreamParser) parseHexString() (*core.PdfObjectString, error) hextable := []byte("0123456789abcdefABCDEF") - tmp := []byte{} + var tmp []byte for { csp.skipSpaces() @@ -495,7 +495,7 @@ func (csp *ContentStreamParser) parseDict() (*core.PdfObjectDictionary, error) { // An operand is a text command represented by a word. func (csp *ContentStreamParser) parseOperand() (*core.PdfObjectString, error) { - bytes := []byte{} + var bytes []byte for { bb, err := csp.reader.Peek(1) if err != nil { diff --git a/pdf/contentstream/utils.go b/pdf/contentstream/utils.go index 69e04d67..7ff98ebf 100644 --- a/pdf/contentstream/utils.go +++ b/pdf/contentstream/utils.go @@ -14,7 +14,7 @@ import ( ) func makeParamsFromFloats(vals []float64) []core.PdfObject { - params := []core.PdfObject{} + var params []core.PdfObject for _, val := range vals { params = append(params, core.MakeFloat(val)) } @@ -22,7 +22,7 @@ func makeParamsFromFloats(vals []float64) []core.PdfObject { } func makeParamsFromNames(vals []core.PdfObjectName) []core.PdfObject { - params := []core.PdfObject{} + var params []core.PdfObject for _, val := range vals { params = append(params, core.MakeName(string(val))) } @@ -30,7 +30,7 @@ func makeParamsFromNames(vals []core.PdfObjectName) []core.PdfObject { } func makeParamsFromStrings(vals []core.PdfObjectString) []core.PdfObject { - params := []core.PdfObject{} + var params []core.PdfObject for _, val := range vals { params = append(params, core.MakeString(val.Str())) } @@ -38,7 +38,7 @@ func makeParamsFromStrings(vals []core.PdfObjectString) []core.PdfObject { } func makeParamsFromInts(vals []int64) []core.PdfObject { - params := []core.PdfObject{} + var params []core.PdfObject for _, val := range vals { params = append(params, core.MakeInteger(val)) } diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index da98f620..d60fd0bb 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -1130,7 +1130,7 @@ func newRunLengthEncoderFromStream(streamObj *PdfObjectStream, decodeParams *Pdf */ func (this *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { bufReader := bytes.NewReader(encoded) - inb := []byte{} + var inb []byte for { b, err := bufReader.ReadByte() if err != nil { @@ -1168,8 +1168,8 @@ func (this *RunLengthEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, // Encode a bytes array and return the encoded value based on the encoder parameters. func (this *RunLengthEncoder) EncodeBytes(data []byte) ([]byte, error) { bufReader := bytes.NewReader(data) - inb := []byte{} - literal := []byte{} + var inb []byte + var literal []byte b0, err := bufReader.ReadByte() if err == io.EOF { @@ -1272,7 +1272,7 @@ func (this *ASCIIHexEncoder) MakeStreamDict() *PdfObjectDictionary { func (this *ASCIIHexEncoder) DecodeBytes(encoded []byte) ([]byte, error) { bufReader := bytes.NewReader(encoded) - inb := []byte{} + var inb []byte for { b, err := bufReader.ReadByte() if err != nil { @@ -1348,7 +1348,7 @@ func (this *ASCII85Encoder) MakeStreamDict() *PdfObjectDictionary { // 5 ASCII characters -> 4 raw binary bytes func (this *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { - decoded := []byte{} + var decoded []byte common.Log.Trace("ASCII85 Decode") @@ -1663,7 +1663,7 @@ func newMultiEncoderFromStream(streamObj *PdfObjectStream) (*MultiEncoder, error // Prepare the decode params array (one for each filter type) // Optional, not always present. var decodeParamsDict *PdfObjectDictionary - decodeParamsArray := []PdfObject{} + var decodeParamsArray []PdfObject obj := encDict.Get("DecodeParms") if obj != nil { // If it is a dictionary, assume it applies to all diff --git a/pdf/core/parser.go b/pdf/core/parser.go index e56ec1f2..f8418bba 100755 --- a/pdf/core/parser.go +++ b/pdf/core/parser.go @@ -338,7 +338,7 @@ func (parser *PdfParser) parseString() (*PdfObjectString, error) { return MakeString(r.String()), err } - numeric := []byte{} + var numeric []byte numeric = append(numeric, b) for _, val := range bb { if IsOctalDigit(val) { @@ -898,7 +898,7 @@ func (parser *PdfParser) parseXrefStream(xstm *PdfObjectInteger) (*PdfObjectDict // Subsections cannot overlap; an object number may have at most // one entry in a section. // Default value: [0 Size]. - indexList := []int{} + var indexList []int if indexObj != nil { common.Log.Trace("Index: %b", indexObj) indicesArray, ok := indexObj.(*PdfObjectArray) @@ -1235,7 +1235,7 @@ func (parser *PdfParser) loadXrefs() (*PdfObjectDictionary, error) { } // Load old objects also. Only if not already specified. - prevList := []int64{} + var prevList []int64 intInSlice := func(val int64, list []int64) bool { for _, b := range list { if b == val { diff --git a/pdf/core/primitives.go b/pdf/core/primitives.go index 71f8fc50..3daae1d2 100644 --- a/pdf/core/primitives.go +++ b/pdf/core/primitives.go @@ -422,7 +422,7 @@ func (array *PdfObjectArray) Clear() { // returned if the array contains non-numeric objects (each element can be either PdfObjectInteger // or PdfObjectFloat). func (array *PdfObjectArray) ToFloat64Array() ([]float64, error) { - vals := []float64{} + var vals []float64 for _, obj := range array.Elements() { switch t := obj.(type) { @@ -441,7 +441,7 @@ func (array *PdfObjectArray) ToFloat64Array() ([]float64, error) { // ToIntegerArray returns a slice of all array elements as an int slice. An error is returned if the // array non-integer objects. Each element can only be PdfObjectInteger. func (array *PdfObjectArray) ToIntegerArray() ([]int, error) { - vals := []int{} + var vals []int for _, obj := range array.Elements() { if number, is := obj.(*PdfObjectInteger); is { @@ -457,7 +457,7 @@ func (array *PdfObjectArray) ToIntegerArray() ([]int, error) { // ToInt64Slice returns a slice of all array elements as an int64 slice. An error is returned if the // array non-integer objects. Each element can only be PdfObjectInteger. func (array *PdfObjectArray) ToInt64Slice() ([]int64, error) { - vals := []int64{} + var vals []int64 for _, obj := range array.Elements() { if number, is := obj.(*PdfObjectInteger); is { @@ -560,7 +560,7 @@ func getNumberAsFloatOrNull(obj PdfObject) (*float64, error) { // GetAsFloat64Slice returns the array as []float64 slice. // Returns an error if not entirely numeric (only PdfObjectIntegers, PdfObjectFloats). func (array *PdfObjectArray) GetAsFloat64Slice() ([]float64, error) { - slice := []float64{} + var slice []float64 for _, obj := range array.Elements() { number, err := GetNumberAsFloat(TraceToDirectObject(obj)) diff --git a/pdf/core/utils.go b/pdf/core/utils.go index 32164a61..41e13129 100644 --- a/pdf/core/utils.go +++ b/pdf/core/utils.go @@ -38,7 +38,7 @@ func (parser *PdfParser) Inspect() (map[string]int, error) { // GetObjectNums returns a sorted list of object numbers of the PDF objects in the file. func (parser *PdfParser) GetObjectNums() []int { - objNums := []int{} + var objNums []int for _, x := range parser.xrefs { objNums = append(objNums, x.objectNumber) } @@ -67,7 +67,7 @@ func (parser *PdfParser) inspect() (map[string]int, error) { objCount := 0 failedCount := 0 - keys := []int{} + var keys []int for k := range parser.xrefs { keys = append(keys, k) } diff --git a/pdf/creator/block.go b/pdf/creator/block.go index c8f7df37..65b5d5d0 100644 --- a/pdf/creator/block.go +++ b/pdf/creator/block.go @@ -126,7 +126,7 @@ func (blk *Block) duplicate() *Block { // GeneratePageBlocks draws the block contents on a template Page block. // Implements the Drawable interface. func (blk *Block) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { - blocks := []*Block{} + var blocks []*Block if blk.positioning.isRelative() { // Draw at current ctx.X, ctx.Y position diff --git a/pdf/creator/creator.go b/pdf/creator/creator.go index 19762687..ec186545 100644 --- a/pdf/creator/creator.go +++ b/pdf/creator/creator.go @@ -399,7 +399,7 @@ func (c *Creator) finalize() error { } blocks, _, _ := c.toc.GeneratePageBlocks(c.context) - tocpages := []*model.PdfPage{} + var tocpages []*model.PdfPage for _, block := range blocks { block.SetPos(0, 0) totPages++ diff --git a/pdf/creator/division.go b/pdf/creator/division.go index 9398d85e..9cee852f 100644 --- a/pdf/creator/division.go +++ b/pdf/creator/division.go @@ -103,7 +103,7 @@ func (div *Division) Width() float64 { // GeneratePageBlocks generates the page blocks for the Division component. // Multiple blocks are generated if the contents wrap over multiple pages. func (div *Division) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { - pageblocks := []*Block{} + var pageblocks []*Block origCtx := ctx diff --git a/pdf/creator/image.go b/pdf/creator/image.go index 42031ec8..1ec898af 100644 --- a/pdf/creator/image.go +++ b/pdf/creator/image.go @@ -168,7 +168,7 @@ func (img *Image) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, er img.makeXObject() } - blocks := []*Block{} + var blocks []*Block origCtx := ctx blk := NewBlock(ctx.PageWidth, ctx.PageHeight) diff --git a/pdf/creator/paragraph.go b/pdf/creator/paragraph.go index 285dcefe..6327df89 100644 --- a/pdf/creator/paragraph.go +++ b/pdf/creator/paragraph.go @@ -378,7 +378,7 @@ func sum(widths []float64) float64 { // over multiple pages. Implements the Drawable interface. func (p *Paragraph) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { origContext := ctx - blocks := []*Block{} + var blocks []*Block blk := NewBlock(ctx.PageWidth, ctx.PageHeight) if p.positioning.isRelative() { @@ -507,7 +507,7 @@ func drawParagraphOnBlock(blk *Block, p *Paragraph, ctx DrawContext) (DrawContex w += p.fontSize * metrics.Wx } - objs := []core.PdfObject{} + var objs []core.PdfObject spaceMetrics, found := p.textFont.GetGlyphCharMetrics("space") if !found { @@ -530,7 +530,7 @@ func drawParagraphOnBlock(blk *Block, p *Paragraph, ctx DrawContext) (DrawContex objs = append(objs, core.MakeFloat(-shift)) } - encoded := []byte{} + var encoded []byte isCID := p.textFont.IsCID() for _, r := range runes { glyph, ok := p.textFont.Encoder().RuneToGlyph(r) diff --git a/pdf/creator/styled_paragraph.go b/pdf/creator/styled_paragraph.go index 592e30a0..da953da5 100644 --- a/pdf/creator/styled_paragraph.go +++ b/pdf/creator/styled_paragraph.go @@ -463,7 +463,7 @@ func (p *StyledParagraph) wrapText() error { // if the contents wrap over multiple pages. Implements the Drawable interface. func (p *StyledParagraph) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { origContext := ctx - blocks := []*Block{} + var blocks []*Block blk := NewBlock(ctx.PageWidth, ctx.PageHeight) if p.positioning.isRelative() { @@ -549,10 +549,10 @@ func drawStyledParagraphOnBlock(blk *Block, p *StyledParagraph, ctx DrawContext) p.wrapText() // Add the fonts of all chunks to the page resources. - fonts := [][]core.PdfObjectName{} + var fonts [][]core.PdfObjectName for _, line := range p.lines { - fontLine := []core.PdfObjectName{} + var fontLine []core.PdfObjectName for _, chunk := range line { fontName = core.PdfObjectName(fmt.Sprintf("Font%d", num)) @@ -647,7 +647,7 @@ func drawStyledParagraphOnBlock(blk *Block, p *StyledParagraph, ctx DrawContext) height *= p.lineHeight // Add line shifts. - objs := []core.PdfObject{} + var objs []core.PdfObject wrapWidth := p.wrapWidth * 1000.0 if p.alignment == TextAlignmentJustify { diff --git a/pdf/creator/table.go b/pdf/creator/table.go index bd1b1f95..cc32c8f0 100644 --- a/pdf/creator/table.go +++ b/pdf/creator/table.go @@ -152,7 +152,7 @@ func (table *Table) SetPos(x, y float64) { // over multiple pages. // Implements the Drawable interface. func (table *Table) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) { - blocks := []*Block{} + var blocks []*Block block := NewBlock(ctx.PageWidth, ctx.PageHeight) origCtx := ctx diff --git a/pdf/creator/utils.go b/pdf/creator/utils.go index 51c619e5..7847b065 100644 --- a/pdf/creator/utils.go +++ b/pdf/creator/utils.go @@ -31,7 +31,7 @@ func loadPagesFromFile(path string) ([]*model.PdfPage, error) { } // Load the pages. - pages := []*model.PdfPage{} + var pages []*model.PdfPage for i := 0; i < numPages; i++ { page, err := pdfReader.GetPage(i + 1) if err != nil { diff --git a/pdf/extractor/text.go b/pdf/extractor/text.go index 21acd6f1..28b18ca6 100644 --- a/pdf/extractor/text.go +++ b/pdf/extractor/text.go @@ -644,7 +644,7 @@ func (to *textObject) getFont(name string) (*model.PdfFont, error) { // Eject a victim if the cache is full. if len(to.e.fontCache) >= maxFontCache { - names := []string{} + var names []string for name := range to.e.fontCache { names = append(names, name) } diff --git a/pdf/fdf/fielddata.go b/pdf/fdf/fielddata.go index 80b92b3e..9d7e2c65 100644 --- a/pdf/fdf/fielddata.go +++ b/pdf/fdf/fielddata.go @@ -80,7 +80,7 @@ func (fdf *Data) FieldValues() (map[string]core.PdfObject, error) { return nil, err } - keys := []string{} + var keys []string for fieldName := range fieldDictMap { keys = append(keys, fieldName) } diff --git a/pdf/internal/cmap/cmap.go b/pdf/internal/cmap/cmap.go index fa62a338..ec813e15 100644 --- a/pdf/internal/cmap/cmap.go +++ b/pdf/internal/cmap/cmap.go @@ -318,14 +318,14 @@ func (cmap *CMap) toBfData() string { } // codes is a sorted list of the codeToUnicode keys. - codes := []CharCode{} + var codes []CharCode for code := range cmap.codeToUnicode { codes = append(codes, code) } sort.Slice(codes, func(i, j int) bool { return codes[i] < codes[j] }) // charRanges is a list of the contiguous character code ranges in `codes`. - charRanges := []charRange{} + var charRanges []charRange c0, c1 := codes[0], codes[0]+1 for _, c := range codes[1:] { if c != c1 { @@ -339,8 +339,8 @@ func (cmap *CMap) toBfData() string { } // fbChars is a list of single character ranges. fbRanges is a list of multiple character ranges. - fbChars := []CharCode{} - fbRanges := []fbRange{} + var fbChars []CharCode + var fbRanges []fbRange for _, cr := range charRanges { if cr.code0+1 == cr.code1 { fbChars = append(fbChars, cr.code0) @@ -355,7 +355,7 @@ func (cmap *CMap) toBfData() string { common.Log.Trace("charRanges=%d fbChars=%d fbRanges=%d", len(charRanges), len(fbChars), len(fbRanges)) - lines := []string{} + var lines []string if len(fbChars) > 0 { numRanges := (len(fbChars) + maxBfEntries - 1) / maxBfEntries for i := 0; i < numRanges; i++ { diff --git a/pdf/internal/cmap/cmap_test.go b/pdf/internal/cmap/cmap_test.go index dc10de20..6e402e20 100644 --- a/pdf/internal/cmap/cmap_test.go +++ b/pdf/internal/cmap/cmap_test.go @@ -672,12 +672,12 @@ func checkCmapWriteRead(t *testing.T, codeToUnicode map[CharCode]rune) { return } - codes0 := []CharCode{} + var codes0 []CharCode for code := range codeToUnicode { codes0 = append(codes0, code) } sort.Slice(codes0, func(i, j int) bool { return codes0[i] < codes0[j] }) - codes := []CharCode{} + var codes []CharCode for code := range cmap.codeToUnicode { codes = append(codes, code) } diff --git a/pdf/internal/cmap/parser.go b/pdf/internal/cmap/parser.go index f1dec8f0..cc734c74 100644 --- a/pdf/internal/cmap/parser.go +++ b/pdf/internal/cmap/parser.go @@ -203,7 +203,7 @@ func (p *cMapParser) parseString() (cmapString, error) { return cmapString{buf.String()}, err } - numeric := []byte{} + var numeric []byte numeric = append(numeric, b) for _, val := range bb { if core.IsOctalDigit(val) { diff --git a/pdf/internal/sampling/resample.go b/pdf/internal/sampling/resample.go index c32a530b..e9447f88 100644 --- a/pdf/internal/sampling/resample.go +++ b/pdf/internal/sampling/resample.go @@ -8,7 +8,7 @@ package sampling // Resample the raw data which is in 8-bit (byte) format as a different // bit count per sample, up to 32 bits (uint32). func ResampleBytes(data []byte, bitsPerSample int) []uint32 { - samples := []uint32{} + var samples []uint32 bitsLeftPerSample := bitsPerSample var sample uint32 @@ -102,7 +102,7 @@ func ResampleBytes(data []byte, bitsPerSample int) []uint32 { // bitsPerOutputSample is the number of bits for each output sample (up to 32) // bitsPerInputSample is the number of bits used in each input sample (up to 32) func ResampleUint32(data []uint32, bitsPerInputSample int, bitsPerOutputSample int) []uint32 { - samples := []uint32{} + var samples []uint32 bitsLeftPerSample := bitsPerOutputSample var sample uint32 diff --git a/pdf/internal/strutils/encoding.go b/pdf/internal/strutils/encoding.go index faf22e07..781a4f04 100644 --- a/pdf/internal/strutils/encoding.go +++ b/pdf/internal/strutils/encoding.go @@ -60,7 +60,7 @@ func StringToUTF16(s string) string { // PDFDocEncodingToRunes decodes PDFDocEncoded byte slice `b` to unicode runes. func PDFDocEncodingToRunes(b []byte) []rune { - runes := []rune{} + var runes []rune for _, bval := range b { rune, has := pdfDocEncoding[bval] if !has { diff --git a/pdf/internal/textencoding/cmap.go b/pdf/internal/textencoding/cmap.go index cdc03526..63423c07 100644 --- a/pdf/internal/textencoding/cmap.go +++ b/pdf/internal/textencoding/cmap.go @@ -26,7 +26,7 @@ func (cmap CMapIdentityH) CharacterCodesToCID(raw []byte) ([]CID, error) { return nil, core.ErrRangeError } - cids := []CID{} + var cids []CID for i := 0; i < len(raw); i += 2 { b1 := CID(raw[i]) b2 := CID(raw[i+1]) diff --git a/pdf/internal/textencoding/utils.go b/pdf/internal/textencoding/utils.go index 6beebb56..c5f4c2d9 100644 --- a/pdf/internal/textencoding/utils.go +++ b/pdf/internal/textencoding/utils.go @@ -34,7 +34,7 @@ func runeToGlyph(r rune, runeToGlyphMap map[rune]GlyphName) (GlyphName, bool) { func splitWords(raw string, encoder TextEncoder) []string { runes := []rune(raw) - words := []string{} + var words []string startsAt := 0 for idx, r := range runes { diff --git a/pdf/model/colorspace.go b/pdf/model/colorspace.go index 7c9ead58..9b908976 100644 --- a/pdf/model/colorspace.go +++ b/pdf/model/colorspace.go @@ -300,7 +300,7 @@ func (this *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { samples := img.GetSamples() common.Log.Trace("DeviceGray-ToRGB Samples: % d", samples) - rgbSamples := []uint32{} + var rgbSamples []uint32 for i := 0; i < len(samples); i++ { grayVal := samples[i] rgbSamples = append(rgbSamples, grayVal, grayVal, grayVal) @@ -445,7 +445,7 @@ func (this *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { samples := img.GetSamples() maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 - graySamples := []uint32{} + var graySamples []uint32 for i := 0; i < len(samples); i += 3 { // Normalized data, range 0-1. r := float64(samples[i]) / maxVal @@ -629,7 +629,7 @@ func (this *PdfColorspaceDeviceCMYK) ImageToRGB(img Image) (Image, error) { maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 common.Log.Trace("MaxVal: %f", maxVal) - rgbSamples := []uint32{} + var rgbSamples []uint32 for i := 0; i < len(samples); i += 4 { // Normalized c, m, y, k values. c := interpolate(float64(samples[i]), 0, maxVal, decode[0], decode[1]) @@ -893,7 +893,7 @@ func (this *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { samples := img.GetSamples() maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 - rgbSamples := []uint32{} + var rgbSamples []uint32 for i := 0; i < len(samples); i++ { // A represents the gray component of calibrated gray space. // It shall be in the range 0.0 - 1.0 @@ -1224,7 +1224,7 @@ func (this *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { samples := img.GetSamples() maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 - rgbSamples := []uint32{} + var rgbSamples []uint32 for i := 0; i < len(samples)-2; i++ { // A, B, C in range 0.0 to 1.0 aVal := float64(samples[i]) / maxVal @@ -1589,7 +1589,7 @@ func (this *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { samples := img.GetSamples() maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 - rgbSamples := []uint32{} + var rgbSamples []uint32 for i := 0; i < len(samples); i += 3 { // Get normalized L*, a*, b* values. [0-1] LNorm := float64(samples[i]) / maxVal @@ -1825,7 +1825,7 @@ func (this *PdfColorspaceICCBased) ToPdfObject() PdfObject { dict.Set("Metadata", this.Metadata) } if this.Range != nil { - ranges := []PdfObject{} + var ranges []PdfObject for _, r := range this.Range { ranges = append(ranges, MakeFloat(r)) } @@ -2251,7 +2251,7 @@ func (this *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfCol } cvals := this.colorLookup[index : index+N] - floats := []float64{} + var floats []float64 for _, val := range cvals { floats = append(floats, float64(val)/255.0) } @@ -2299,7 +2299,7 @@ func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { samples := img.GetSamples() N := this.Base.GetNumComponents() - baseSamples := []uint32{} + var baseSamples []uint32 // Convert the indexed data to base color map data. for i := 0; i < len(samples); i++ { // Each data point represents an index location. @@ -2514,7 +2514,7 @@ func (this *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) altDecode := this.AlternateSpace.DecodeArray() - altSamples := []uint32{} + var altSamples []uint32 // Convert tints to color data in the alternate colorspace. for i := 0; i < len(samples); i++ { // A single tint component is in the range 0.0 - 1.0 @@ -2583,7 +2583,7 @@ func (this *PdfColorspaceDeviceN) GetNumComponents() int { // DecodeArray returns the component range values for the DeviceN colorspace. // [0 1.0 0 1.0 ...] for each color component. func (this *PdfColorspaceDeviceN) DecodeArray() []float64 { - decode := []float64{} + var decode []float64 for i := 0; i < this.GetNumComponents(); i++ { decode = append(decode, 0.0, 1.0) } @@ -2726,13 +2726,13 @@ func (this *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { maxVal := math.Pow(2, float64(img.BitsPerComponent)) - 1 // Convert tints to color data in the alternate colorspace. - altSamples := []uint32{} + var altSamples []uint32 for i := 0; i < len(samples); i += this.GetNumComponents() { // The input to the tint transformation is the tint // for each color component. // // A single tint component is in the range 0.0 - 1.0 - inputs := []float64{} + var inputs []float64 for j := 0; j < this.GetNumComponents(); j++ { tint := float64(samples[i+j]) / maxVal inputs = append(inputs, tint) diff --git a/pdf/model/flatten.go b/pdf/model/flatten.go index d20aac42..3d0be700 100644 --- a/pdf/model/flatten.go +++ b/pdf/model/flatten.go @@ -77,7 +77,7 @@ func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenera // Go through all pages and flatten specified annotations. for _, page := range pdf.PageList { - annots := []*PdfAnnotation{} + var annots []*PdfAnnotation // Wrap the content streams. err := appgen.WrapContentStream(page) @@ -132,7 +132,7 @@ func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenera // Generate the content stream to display the XForm. // TODO(gunnsth): Creating the contentstream directly here as cannot import contentstream package into // model (as contentstream depends on model). Consider if we can change the dependency pattern. - ops := []string{} + var ops []string ops = append(ops, "q") ops = append(ops, fmt.Sprintf("%.6f %.6f %.6f %.6f %.6f %.6f cm", 1.0, 0.0, 0.0, 1.0, xRect, yRect)) ops = append(ops, fmt.Sprintf("/%s Do", name.String())) diff --git a/pdf/model/font.go b/pdf/model/font.go index d7ffdbfc..94bcc938 100644 --- a/pdf/model/font.go +++ b/pdf/model/font.go @@ -190,7 +190,7 @@ func GetAlphabet(text string) map[rune]int { // sortedAlphabet the runes in `alphabet` sorted by frequency. func sortedAlphabet(alphabet map[rune]int) []rune { - runes := []rune{} + var runes []rune for r := range alphabet { runes = append(runes, r) } @@ -682,7 +682,7 @@ func (descriptor *PdfFontDescriptor) GetCapHeight() (float64, error) { // String returns a string describing the font descriptor. func (descriptor *PdfFontDescriptor) String() string { - parts := []string{} + var parts []string if descriptor.FontName != nil { parts = append(parts, descriptor.FontName.String()) } diff --git a/pdf/model/font_test.go b/pdf/model/font_test.go index c008d1e2..e3d75b37 100644 --- a/pdf/model/font_test.go +++ b/pdf/model/font_test.go @@ -528,7 +528,7 @@ func parsePdfObjects(text string) (map[int]core.PdfObject, error) { common.Log.Debug("parsePdfObjects") // Build the numObj {object number: object} map - nums := []int{} + var nums []int for { obj, err := parser.ParseIndirectObject() common.Log.Debug("parsePdfObjects: %T %v", obj, err) diff --git a/pdf/model/fontfile.go b/pdf/model/fontfile.go index 8c2648c1..8dcdc0df 100644 --- a/pdf/model/fontfile.go +++ b/pdf/model/fontfile.go @@ -85,7 +85,7 @@ func newFontFileFromPdfObject(obj core.PdfObject) (*fontFile, error) { } segment1 := data[:length1] - segment2 := []byte{} + var segment2 []byte if length2 > 0 { segment2 = data[length1 : length1+length2] } diff --git a/pdf/model/fonts/ttfparser.go b/pdf/model/fonts/ttfparser.go index f05ec1d9..0c86cf5d 100644 --- a/pdf/model/fonts/ttfparser.go +++ b/pdf/model/fonts/ttfparser.go @@ -208,7 +208,7 @@ func (t *ttfParser) Parse() (TtfType, error) { // describeTables returns a string describing `tables`, the tables in a TrueType font file. func describeTables(tables map[string]uint32) string { - tags := []string{} + var tags []string for tag := range tables { tags = append(tags, tag) } diff --git a/pdf/model/form.go b/pdf/model/form.go index d8f0d70a..c36f8657 100644 --- a/pdf/model/form.go +++ b/pdf/model/form.go @@ -53,7 +53,7 @@ func flattenFields(field *PdfField) []*PdfField { // AllFields returns a flattened list of all fields in the form. func (form *PdfAcroForm) AllFields() []*PdfField { - fields := []*PdfField{} + var fields []*PdfField if form.Fields != nil { for _, field := range *form.Fields { fields = append(fields, flattenFields(field)...) @@ -64,7 +64,7 @@ func (form *PdfAcroForm) AllFields() []*PdfField { // signatureFields returns a slice of all signature fields in the form. func (form *PdfAcroForm) signatureFields() []*PdfFieldSignature { - sigfields := []*PdfFieldSignature{} + var sigfields []*PdfFieldSignature for _, f := range form.AllFields() { switch t := f.GetContext().(type) { @@ -91,7 +91,7 @@ func (r *PdfReader) newPdfAcroFormFromDict(d *core.PdfObjectDictionary) (*PdfAcr return nil, fmt.Errorf("Fields not an array (%T)", obj) } - fields := []*PdfField{} + var fields []*PdfField for _, obj := range fieldArray.Elements() { obj, err := r.traceToObject(obj) if err != nil { diff --git a/pdf/model/functions.go b/pdf/model/functions.go index 4d908c4e..96e3afe3 100644 --- a/pdf/model/functions.go +++ b/pdf/model/functions.go @@ -300,7 +300,7 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { decode = this.Range } - indices := []int{} + var indices []int // Start with nearest neighbour interpolation. for i := 0; i < len(x); i++ { xi := x[i] @@ -339,7 +339,7 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { m *= this.NumOutputs // Output values. - outputs := []float64{} + var outputs []float64 for j := 0; j < this.NumOutputs; j++ { rj := this.data[m+j] rjp := interpolate(float64(rj), 0, math.Pow(2, float64(this.BitsPerSample)), decode[2*j], decode[2*j+1]) @@ -534,7 +534,7 @@ func (this *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) { c1 = this.C1 } - y := []float64{} + var y []float64 for i := 0; i < len(c0); i++ { yi := c0[i] + math.Pow(x[0], this.N)*(c1[i]-c0[i]) y = append(y, yi) @@ -744,7 +744,7 @@ func (this *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) { this.executor = ps.NewPSExecutor(this.Program) } - inputs := []ps.PSObject{} + var inputs []ps.PSObject for _, val := range xVec { inputs = append(inputs, ps.MakeReal(val)) } diff --git a/pdf/model/image.go b/pdf/model/image.go index 614b6854..0cf2f1bb 100644 --- a/pdf/model/image.go +++ b/pdf/model/image.go @@ -66,7 +66,7 @@ func (img *Image) GetSamples() []uint32 { // SetSamples convert samples to byte-data and sets for the image. func (img *Image) SetSamples(samples []uint32) { resampled := sampling.ResampleUint32(samples, int(img.BitsPerComponent), 8) - data := []byte{} + var data []byte for _, val := range resampled { data = append(data, byte(val)) } @@ -114,7 +114,7 @@ func (img *Image) Resample(targetBitsPerComponent int64) { } // Write out row by row... - data := []byte{} + var data []byte for i := int64(0); i < img.Height; i++ { ind1 := i * img.Width * int64(img.ColorComponents) ind2 := (i+1)*img.Width*int64(img.ColorComponents) - 1 @@ -239,10 +239,10 @@ func (ih DefaultImageHandler) NewImageFromGoImage(goimg goimage.Image) (*Image, m := goimage.NewRGBA(goimage.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(m, m.Bounds(), goimg, b.Min, draw.Src) - alphaData := []byte{} + var alphaData []byte hasAlpha := false - data := []byte{} + var data []byte for i := 0; i < len(m.Pix); i += 4 { data = append(data, m.Pix[i], m.Pix[i+1], m.Pix[i+2]) diff --git a/pdf/model/optimize/optimize_test.go b/pdf/model/optimize/optimize_test.go index efe95aa1..ea73b16f 100644 --- a/pdf/model/optimize/optimize_test.go +++ b/pdf/model/optimize/optimize_test.go @@ -18,7 +18,7 @@ import ( // parseIndirectObjects parses a sequence of indirect/stream objects sequentially from a `rawpdf` text. func parseIndirectObjects(rawpdf string) ([]core.PdfObject, error) { p := core.NewParserFromString(rawpdf) - indirects := []core.PdfObject{} + var indirects []core.PdfObject for { obj, err := p.ParseIndirectObject() if err != nil { diff --git a/pdf/model/page.go b/pdf/model/page.go index 263b8024..834b7918 100644 --- a/pdf/model/page.go +++ b/pdf/model/page.go @@ -326,7 +326,7 @@ func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotati return nil, fmt.Errorf("Annots not an array") } - annotations := []*PdfAnnotation{} + var annotations []*PdfAnnotation for _, obj := range annotsArr.Elements() { obj, err = reader.traceToObject(obj) if err != nil { @@ -785,7 +785,7 @@ func (this *PdfPage) SetContentStreams(cStreams []string, encoder StreamEncoder) encoder = NewRawEncoder() } - streamObjs := []*PdfObjectStream{} + var streamObjs []*PdfObjectStream for _, cStream := range cStreams { stream := &PdfObjectStream{} @@ -845,7 +845,7 @@ func (this *PdfPage) GetContentStreams() ([]string, error) { contents := TraceToDirectObject(this.Contents) if contArray, isArray := contents.(*PdfObjectArray); isArray { // If an array of content streams, append it. - cstreams := []string{} + var cstreams []string for _, cstreamObj := range contArray.Elements() { cstreamStr, err := getContentStreamAsString(cstreamObj) if err != nil { diff --git a/pdf/model/reader.go b/pdf/model/reader.go index 665411b6..008ac12a 100755 --- a/pdf/model/reader.go +++ b/pdf/model/reader.go @@ -397,8 +397,8 @@ func (this *PdfReader) GetOutlineTree() *PdfOutlineTreeNode { // GetOutlinesFlattened returns a flattened list of tree nodes and titles. func (this *PdfReader) GetOutlinesFlattened() ([]*PdfOutlineTreeNode, []string, error) { - outlineNodeList := []*PdfOutlineTreeNode{} - flattenedTitleList := []string{} + var outlineNodeList []*PdfOutlineTreeNode + var flattenedTitleList []string // Recursive flattening function. var flattenFunc func(*PdfOutlineTreeNode, *[]*PdfOutlineTreeNode, *[]string, int) diff --git a/pdf/model/writer.go b/pdf/model/writer.go index 627b8c3b..21fce00c 100644 --- a/pdf/model/writer.go +++ b/pdf/model/writer.go @@ -492,7 +492,7 @@ func procPage(p *PdfPage) { f := fonts.NewFontHelvetica() p.Resources.SetFontByName("UF1", f.ToPdfObject()) - ops := []string{} + var ops []string ops = append(ops, "q") ops = append(ops, "BT") ops = append(ops, "/UF1 14 Tf") @@ -519,7 +519,7 @@ func (this *PdfWriter) AddOutlineTree(outlineTree *PdfOutlineTreeNode) { // What if something appears on many pages? func (this *PdfWriter) seekByName(obj PdfObject, followKeys []string, key string) ([]PdfObject, error) { common.Log.Trace("Seek by name.. %T", obj) - list := []PdfObject{} + var list []PdfObject if io, isIndirectObj := obj.(*PdfIndirectObject); isIndirectObj { return this.seekByName(io.PdfObject, followKeys, key) } diff --git a/pdf/ps/exec.go b/pdf/ps/exec.go index fb510ec9..36f3bee4 100644 --- a/pdf/ps/exec.go +++ b/pdf/ps/exec.go @@ -28,7 +28,7 @@ func NewPSExecutor(program *PSProgram) *PSExecutor { // PSObjectArrayToFloat64Array converts []PSObject into a []float64 array. Each PSObject must represent a number, // otherwise a ErrTypeCheck error occurs. func PSObjectArrayToFloat64Array(objects []PSObject) ([]float64, error) { - vals := []float64{} + var vals []float64 for _, obj := range objects { if number, is := obj.(*PSInteger); is { diff --git a/pdf/ps/parser.go b/pdf/ps/parser.go index 2616cd70..afbf1e46 100644 --- a/pdf/ps/parser.go +++ b/pdf/ps/parser.go @@ -220,7 +220,7 @@ func (p *PSParser) parseBool() (*PSBoolean, error) { // An operand is a text command represented by a word. func (p *PSParser) parseOperand() (*PSOperand, error) { - bytes := []byte{} + var bytes []byte for { bb, err := p.reader.Peek(1) if err != nil { From 5993a8b1711483792d1370a7b5787bd1392d32c2 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 19:30:13 +0200 Subject: [PATCH 2/7] remove redundant types in literals --- common/license/util.go | 2 +- pdf/creator/toc_line.go | 4 ++-- pdf/internal/cmap/cmap.go | 2 +- pdf/model/font_test.go | 44 +++++++++++++++++++-------------------- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/common/license/util.go b/common/license/util.go index d80d5f0b..9ddba152 100644 --- a/common/license/util.go +++ b/common/license/util.go @@ -12,7 +12,7 @@ import ( ) // Defaults to the open source license. -var licenseKey *LicenseKey = MakeUnlicensedKey() +var licenseKey = MakeUnlicensedKey() // Sets and validates the license key. func SetLicenseKey(content string, customerName string) error { diff --git a/pdf/creator/toc_line.go b/pdf/creator/toc_line.go index 7a56d8a4..0e98a170 100644 --- a/pdf/creator/toc_line.go +++ b/pdf/creator/toc_line.go @@ -156,11 +156,11 @@ func (tl *TOCLine) prepareParagraph(sp *StyledParagraph, ctx DrawContext) { sp.chunks = []*TextChunk{ &tl.Number, - &TextChunk{ + { Text: title, Style: tl.Title.Style, }, - &TextChunk{ + { Text: page, Style: tl.Page.Style, }, diff --git a/pdf/internal/cmap/cmap.go b/pdf/internal/cmap/cmap.go index ec813e15..16312e75 100644 --- a/pdf/internal/cmap/cmap.go +++ b/pdf/internal/cmap/cmap.go @@ -68,7 +68,7 @@ func NewToUnicodeCMap(codeToUnicode map[CharCode]rune) *CMap { Ordering: "UCS", Supplement: 0, }, - codespaces: []Codespace{Codespace{Low: 0, High: 0xffff}}, + codespaces: []Codespace{{Low: 0, High: 0xffff}}, codeToUnicode: codeToUnicode, } } diff --git a/pdf/model/font_test.go b/pdf/model/font_test.go index e3d75b37..4e028c5d 100644 --- a/pdf/model/font_test.go +++ b/pdf/model/font_test.go @@ -113,7 +113,7 @@ func TestNewStandard14Font(t *testing.T) { fonts.CharMetrics } tests := map[model.Standard14Font]expect{ - "Courier": expect{ + "Courier": { subtype: "Type1", basefont: "Courier", CharMetrics: fonts.CharMetrics{Wx: 600, Wy: 0}}, @@ -249,7 +249,7 @@ func TestCharcodeBytesToUnicode(t *testing.T) { } var charcodeBytesToUnicodeTest = []fontFragmentTest{ - fontFragmentTest{"Helvetica built-in", + {"Helvetica built-in", "./testdata/font/simple.txt", 1, []byte{32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, @@ -267,7 +267,7 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ "abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹OEŽ‘’“”•–—˜™š›oežŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·" + "¸¹º»¼½¾¿ÀÁÂÃÄÅAEÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞfzàáâãäåaeçèéêëìíîïðñòóôõö÷øùúûüýþÿ", }, - fontFragmentTest{"Symbol built-in", + {"Symbol built-in", "./testdata/font/simple.txt", 3, []byte{32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, @@ -281,7 +281,7 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ " !∀#∃%&∋()∗+,−./0123456789:;<=>?≅ΑΒΧ∆ΕΦΓΗΙϑΚΛΜΝΟΠΘΡΣΤΥςΩΞΨΖ[∴]⊥_αβχδεφγηιϕκλµνοπθρστυϖω" + "ξψζ{|}∼€ϒ′≤⁄∞ƒ♣♦♥♠↔←↑→↓°±″≥×∝∂•÷≠≡≈…↵ℵℑℜ℘⊗⊕∅∩∪⊃⊇⊄⊂⊆∈∉∠∇∏√⋅¬∧∨⇔⇐⇑⇒⇓◊〈∑〉∫⌠⌡", }, - fontFragmentTest{"ZapfDingbats built-in", + {"ZapfDingbats built-in", "./testdata/font/simple.txt", 4, []byte{32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, @@ -297,7 +297,7 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ "❘❙❚❛❜❝❞❡❢❣❤❥❦❧♣♦♥♠①②③④⑤⑥⑦⑧⑨⑩❶❷❸❹❺❻❼❽❾❿➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓➔→↔↕" + "➘➙➚➛➜➝➞➟➠➡➢➣➤➥➦➧➨➩➪➫➬➭➮➯➱➲➳➴➵➶➷➸➹➺➻➼➽➾", }, - fontFragmentTest{"MacRoman encoding", + {"MacRoman encoding", "./testdata/font/axes.txt", 10, []byte{32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, @@ -315,7 +315,7 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ "abcdefghijklmnopqrstuvwxyz{|}~ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶fz®©™´¨≠AEØ∞" + "±≤≥¥µ∂∑∏π∫ªºΩaeø¿¡¬√ƒ≈∆«»…ÀÃÕOEoe–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", }, - fontFragmentTest{"Test beginbfchar and beginbfrange cmap entries", + {"Test beginbfchar and beginbfrange cmap entries", "./testdata/font/Yemeni.txt", 470, []byte{0x1, 0xa8, 0x1, 0xb3, 0x1, 0xc2, 0x1, 0xcc, 0x1, 0xe7, 0x1, 0xef, 0x1, 0xf3, 0x0, 0x20, 0x1, 0xa2, 0x1, 0xfc, 0x2, 0x8, 0x1, 0xa6, 0x1, 0xe7, 0x0, 0x20, 0x2, 0xb, 0x0, @@ -323,30 +323,30 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ 0xcf, 0x0, 0xd0, 0x0, 0xd1, 0x1, 0xa1, 0x0, 0x20, 0x1, 0xa9, 0x2, 0x1}, "ﺔﺟﺮﺸﻓﻛﻟ ﺎﻨﻴﺒﻓ ﻷ ﻻ ﻉ ٠١٢٣٤ﺍ ﺕﻭ", }, - fontFragmentTest{"TrueType font with ToUnicode cmap", + {"TrueType font with ToUnicode cmap", "./testdata/font/print_alerts.txt", 9, []byte{43, 40, 41, 34, 37, 42, 38, 49, 36, 38, 48, 34, 35, 36, 37, 35, 36, 58}, "Alerts on printing", }, - fontFragmentTest{"Type0 font with ToUnicode cmap", + {"Type0 font with ToUnicode cmap", "./testdata/font/CollazoBio.txt", 7, []byte{255, 50, 255, 65, 255, 78, 255, 68, 255, 79, 255, 77, 0, 32, 0, 32, 255, 77, 255, 65, 255, 84, 255, 82, 255, 73, 255, 67, 255, 69, 255, 83, 0, 46}, "Random matrices.", }, - fontFragmentTest{"Type1 font with FontFile entry", + {"Type1 font with FontFile entry", "./testdata/font/lm.txt", 7, []byte{102, 65, 106, 66, 103}, "{A|B}", }, - fontFragmentTest{"Type1 font with /Encoding with /Differences", + {"Type1 font with /Encoding with /Differences", "./testdata/font/noise-invariant.txt", 102, []byte{96, 247, 39, 32, 147, 231, 148, 32, 232, 32, 193, 111, 180, 32, 105, 116, 169, 115, 32, 204, 195, 196, 197, 198, 199, 168, 202, 206, 226, 234, 172, 244, 173, 151, 177, 151, 178, 179, 183, 185, 188, 205, 184, 189}, "‘ł’ “Ł” Ø `o´ it's ˝ˆ˜¯˘˙¨˚ˇªº‹ı›—–—†‡•„…˛¸‰", }, - fontFragmentTest{"base glyphs′", + {"base glyphs′", "./testdata/font/cover.txt", 11, []byte{44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 65, 66, 67, 68, 69, 70, 71, 72, @@ -355,53 +355,53 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ 114, 115, 116, 117}, ",-.01235678:;ABCDEFGHTUabcdefghijlmnorstu", }, - fontFragmentTest{"tex glyphs 48->′", + {"tex glyphs 48->′", "./testdata/font/noise-contrast.txt", 36, []byte{33, 48, 65, 104, 149, 253}, "!′Ah•ý", }, - fontFragmentTest{"tex2 glyphs ", + {"tex2 glyphs ", "./testdata/font/Weil.txt", 30, []byte{55, 0, 1, 2, 20, 24, 33, 50, 102, 103, 104, 105}, "↦−·×≤∼→∈{}⟨⟩", }, - fontFragmentTest{"additional glyphs", + {"additional glyphs", "./testdata/font/noise-contrast.txt", 34, []byte{32, 40, 48, 64, 80, 88, 65, 104, 149, 253}, "({∑∑h•ý", }, - fontFragmentTest{".notdef glyphs", + {".notdef glyphs", "./testdata/font/lec10.txt", 6, []byte{59, 66}, string([]rune{textencoding.MissingCodeRune, textencoding.MissingCodeRune}), }, - fontFragmentTest{"Numbered glyphs pattern 1", + {"Numbered glyphs pattern 1", "./testdata/font/v14.txt", 14, []byte{24, 25, 26, 27, 29}, " ffifflfffi", }, - fontFragmentTest{"Glyph aliases", + {"Glyph aliases", "./testdata/font/townes.txt", 10, []byte{2, 3, 4, 5, 6, 7, 1, 8, 9, 5, 1, 10, 9, 5, 48}, "Townes van Zan…", }, - fontFragmentTest{"Glyph `.` extensions. e.g. `integral.disp`", + {"Glyph `.` extensions. e.g. `integral.disp`", "./testdata/font/preview.txt", 156, []byte{83, 0, 4, 67, 62, 64, 100, 65}, "∫=≈≥∈", }, - fontFragmentTest{"A potpourri of glyph naming conventions", + {"A potpourri of glyph naming conventions", "./testdata/font/Ingmar.txt", 144, []byte{18, 20, 10, 11, 13, 14, 15, 16, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 33, 12, 17, 19, 24}, "ʼ8ČŽĆřćĐĭűőftffiflfffičž!fbfkffl\u00a0", }, - fontFragmentTest{"Zapf Dingbats", + {"Zapf Dingbats", "./testdata/font/estimation.txt", 122, []byte{2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14}, "✏✮✁☛❄❍❥❇◆✟✙", }, - fontFragmentTest{"Found these by trial and error", + {"Found these by trial and error", "./testdata/font/helminths.txt", 19, []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, @@ -410,7 +410,7 @@ var charcodeBytesToUnicodeTest = []fontFragmentTest{ 75, 76, 77}, " *ﺏﻁﻝﺍﺔﻴﻠﻜ،ﺕﺭﺘﻌﻤﺎﺠﻲﻨﻘﺩﻬ/ﻙﻭﻕﺃﻡﻋﻓﺴ٢٠٣ﻯﻥﺒﺸﺌﺱﻷ,ﺯﺤﺄﻀـﺓﺫ.)٤(٩ل٥٧٨ﻸﻰ%١ﺇ٦ﺡﻫﻱﻅﻐﺼﻑﺨﺀﻊLM", }, - fontFragmentTest{"Tesseract", + {"Tesseract", "./testdata/font/tesseract.txt", 3, []byte{0, 65, 0, 97, 1, 2, 1, 65, 1, 97, From e286eecac9d573350699f054b723a058c45dd159 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 19:37:07 +0200 Subject: [PATCH 3/7] remove unused functions and globals; add todos for unused params --- pdf/annotator/field_appearance.go | 2 + pdf/core/encoding.go | 1 + pdf/core/parser_test.go | 43 +- pdf/creator/paragraph.go | 2 + pdf/fdf/parser.go | 1 - pdf/internal/cmap/const.go | 3 - .../textencoding/glyphs_zapfdingbats.go | 418 ------------------ pdf/model/fontfile.go | 8 - pdf/ps/parser_test.go | 9 - 9 files changed, 24 insertions(+), 463 deletions(-) delete mode 100644 pdf/internal/textencoding/glyphs_zapfdingbats.go diff --git a/pdf/annotator/field_appearance.go b/pdf/annotator/field_appearance.go index d2cfa0c7..79a1291e 100644 --- a/pdf/annotator/field_appearance.go +++ b/pdf/annotator/field_appearance.go @@ -731,6 +731,8 @@ func genFieldTextCombAppearance(wa *model.PdfAnnotationWidget, ftxt *model.PdfFi // genFieldCheckboxAppearance generates an appearance dictionary for a widget annotation `wa` referenced by // a button field `fbtn` with form resources `dr` (DR). func genFieldCheckboxAppearance(wa *model.PdfAnnotationWidget, fbtn *model.PdfFieldButton, dr *model.PdfPageResources, style AppearanceStyle) (*core.PdfObjectDictionary, error) { + // TODO(dennwc): unused parameters + // Get bounding Rect. array, ok := core.GetArray(wa.Rect) if !ok { diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index d60fd0bb..377a0c99 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -1117,6 +1117,7 @@ func (this *RunLengthEncoder) GetFilterName() string { // Create a new run length decoder from a stream object. func newRunLengthEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObjectDictionary) (*RunLengthEncoder, error) { + // TODO(dennwc): unused paramaters return NewRunLengthEncoder(), nil } diff --git a/pdf/core/parser_test.go b/pdf/core/parser_test.go index a29ae3eb..720ba5e3 100644 --- a/pdf/core/parser_test.go +++ b/pdf/core/parser_test.go @@ -44,16 +44,16 @@ var namePairs = map[string]string{ "/Name1": "Name1", "/ASomewhatLongerName": "ASomewhatLongerName", "/A;Name_With-Various***Characters?": "A;Name_With-Various***Characters?", - "/1.2": "1.2", - "/$$": "$$", - "/@pattern": "@pattern", - "/.notdef": ".notdef", - "/Lime#20Green": "Lime Green", - "/paired#28#29parentheses": "paired()parentheses", - "/The_Key_of_F#23_Minor": "The_Key_of_F#_Minor", - "/A#42": "AB", - "/": "", - "/ ": "", + "/1.2": "1.2", + "/$$": "$$", + "/@pattern": "@pattern", + "/.notdef": ".notdef", + "/Lime#20Green": "Lime Green", + "/paired#28#29parentheses": "paired()parentheses", + "/The_Key_of_F#23_Minor": "The_Key_of_F#_Minor", + "/A#42": "AB", + "/": "", + "/ ": "", "/#3CBC88#3E#3CC5ED#3E#3CD544#3E#3CC694#3E": "", } @@ -92,11 +92,6 @@ func TestNameParsing(t *testing.T) { } } -type testStringEntry struct { - raw string - expected string -} - func BenchmarkStringParsing(b *testing.B) { entry := "(Strings may contain balanced parenthesis () and\nspecial characters (*!&}^% and so on).)" parser := makeParserForText(entry) @@ -110,18 +105,18 @@ func BenchmarkStringParsing(b *testing.B) { } var stringPairs = map[string]string{ - "(This is a string)": "This is a string", - "(Strings may contain\n newlines and such)": "Strings may contain\n newlines and such", + "(This is a string)": "This is a string", + "(Strings may contain\n newlines and such)": "Strings may contain\n newlines and such", "(Strings may contain balanced parenthesis () and\nspecial characters (*!&}^% and so on).)": "Strings may contain balanced parenthesis () and\nspecial characters (*!&}^% and so on).", "(These \\\ntwo strings \\\nare the same.)": "These two strings are the same.", "(These two strings are the same.)": "These two strings are the same.", - "(\\\\)": "\\", - "(This string has an end-of-line at the end of it.\n)": "This string has an end-of-line at the end of it.\n", - "(So does this one.\\n)": "So does this one.\n", - "(\\0053)": "\0053", - "(\\53)": "\053", - "(\\053)": "+", - "(\\53\\101)": "+A", + "(\\\\)": "\\", + "(This string has an end-of-line at the end of it.\n)": "This string has an end-of-line at the end of it.\n", + "(So does this one.\\n)": "So does this one.\n", + "(\\0053)": "\0053", + "(\\53)": "\053", + "(\\053)": "+", + "(\\53\\101)": "+A", } func TestStringParsing(t *testing.T) { diff --git a/pdf/creator/paragraph.go b/pdf/creator/paragraph.go index 6327df89..fe2f18ce 100644 --- a/pdf/creator/paragraph.go +++ b/pdf/creator/paragraph.go @@ -69,6 +69,8 @@ type Paragraph struct { // newParagraph create a new text paragraph. Uses default parameters: Helvetica, WinAnsiEncoding and // wrap enabled with a wrap width of 100 points. func newParagraph(text string, style TextStyle) *Paragraph { + // TODO(dennwc): style is unused + p := &Paragraph{} p.text = text diff --git a/pdf/fdf/parser.go b/pdf/fdf/parser.go index 35030b19..6e43f259 100644 --- a/pdf/fdf/parser.go +++ b/pdf/fdf/parser.go @@ -28,7 +28,6 @@ var reNumeric = regexp.MustCompile(`^[\+-.]*([0-9.]+)`) var reExponential = regexp.MustCompile(`^[\+-.]*([0-9.]+)e[\+-.]*([0-9.]+)`) var reReference = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s+R`) var reIndirectObject = regexp.MustCompile(`(\d+)\s+(\d+)\s+obj`) -var reTrailer = regexp.MustCompile(`trailer`) // fdfParser parses a FDF file and provides access to the object structure of the FDF. type fdfParser struct { diff --git a/pdf/internal/cmap/const.go b/pdf/internal/cmap/const.go index 0b6ba486..84355d1a 100644 --- a/pdf/internal/cmap/const.go +++ b/pdf/internal/cmap/const.go @@ -7,7 +7,6 @@ package cmap import ( "errors" - "regexp" ) var ( @@ -34,5 +33,3 @@ const ( cmaptype = "CMapType" cmapversion = "CMapVersion" ) - -var reNumeric = regexp.MustCompile(`^[\+-.]*([0-9.]+)`) diff --git a/pdf/internal/textencoding/glyphs_zapfdingbats.go b/pdf/internal/textencoding/glyphs_zapfdingbats.go deleted file mode 100644 index d19110c6..00000000 --- a/pdf/internal/textencoding/glyphs_zapfdingbats.go +++ /dev/null @@ -1,418 +0,0 @@ -/* - * This file is subject to the terms and conditions defined in - * file 'LICENSE.md', which is part of this source code package. - */ -/* - * The embedded glyph to unicode mappings specified in this file are distributed under the terms listed in - * ./testdata/glyphlist/zapfdingbats.txt. - */ - -package textencoding - -var zapfdingbatsGlyphToRuneMap = map[string]rune{ - "a1": '\u2701', - "a10": '\u2721', - "a100": '\u275e', - "a101": '\u2761', - "a102": '\u2762', - "a103": '\u2763', - "a104": '\u2764', - "a105": '\u2710', - "a106": '\u2765', - "a107": '\u2766', - "a108": '\u2767', - "a109": '\u2660', - "a11": '\u261b', - "a110": '\u2665', - "a111": '\u2666', - "a112": '\u2663', - "a117": '\u2709', - "a118": '\u2708', - "a119": '\u2707', - "a12": '\u261e', - "a120": '\u2460', - "a121": '\u2461', - "a122": '\u2462', - "a123": '\u2463', - "a124": '\u2464', - "a125": '\u2465', - "a126": '\u2466', - "a127": '\u2467', - "a128": '\u2468', - "a129": '\u2469', - "a13": '\u270c', - "a130": '\u2776', - "a131": '\u2777', - "a132": '\u2778', - "a133": '\u2779', - "a134": '\u277a', - "a135": '\u277b', - "a136": '\u277c', - "a137": '\u277d', - "a138": '\u277e', - "a139": '\u277f', - "a14": '\u270d', - "a140": '\u2780', - "a141": '\u2781', - "a142": '\u2782', - "a143": '\u2783', - "a144": '\u2784', - "a145": '\u2785', - "a146": '\u2786', - "a147": '\u2787', - "a148": '\u2788', - "a149": '\u2789', - "a15": '\u270e', - "a150": '\u278a', - "a151": '\u278b', - "a152": '\u278c', - "a153": '\u278d', - "a154": '\u278e', - "a155": '\u278f', - "a156": '\u2790', - "a157": '\u2791', - "a158": '\u2792', - "a159": '\u2793', - "a16": '\u270f', - "a160": '\u2794', - "a161": '\u2192', - "a162": '\u27a3', - "a163": '\u2194', - "a164": '\u2195', - "a165": '\u2799', - "a166": '\u279b', - "a167": '\u279c', - "a168": '\u279d', - "a169": '\u279e', - "a17": '\u2711', - "a170": '\u279f', - "a171": '\u27a0', - "a172": '\u27a1', - "a173": '\u27a2', - "a174": '\u27a4', - "a175": '\u27a5', - "a176": '\u27a6', - "a177": '\u27a7', - "a178": '\u27a8', - "a179": '\u27a9', - "a18": '\u2712', - "a180": '\u27ab', - "a181": '\u27ad', - "a182": '\u27af', - "a183": '\u27b2', - "a184": '\u27b3', - "a185": '\u27b5', - "a186": '\u27b8', - "a187": '\u27ba', - "a188": '\u27bb', - "a189": '\u27bc', - "a19": '\u2713', - "a190": '\u27bd', - "a191": '\u27be', - "a192": '\u279a', - "a193": '\u27aa', - "a194": '\u27b6', - "a195": '\u27b9', - "a196": '\u2798', - "a197": '\u27b4', - "a198": '\u27b7', - "a199": '\u27ac', - "a2": '\u2702', - "a20": '\u2714', - "a200": '\u27ae', - "a201": '\u27b1', - "a202": '\u2703', - "a203": '\u2750', - "a204": '\u2752', - "a205": '\u276e', - "a206": '\u2770', - "a21": '\u2715', - "a22": '\u2716', - "a23": '\u2717', - "a24": '\u2718', - "a25": '\u2719', - "a26": '\u271a', - "a27": '\u271b', - "a28": '\u271c', - "a29": '\u2722', - "a3": '\u2704', - "a30": '\u2723', - "a31": '\u2724', - "a32": '\u2725', - "a33": '\u2726', - "a34": '\u2727', - "a35": '\u2605', - "a36": '\u2729', - "a37": '\u272a', - "a38": '\u272b', - "a39": '\u272c', - "a4": '\u260e', - "a40": '\u272d', - "a41": '\u272e', - "a42": '\u272f', - "a43": '\u2730', - "a44": '\u2731', - "a45": '\u2732', - "a46": '\u2733', - "a47": '\u2734', - "a48": '\u2735', - "a49": '\u2736', - "a5": '\u2706', - "a50": '\u2737', - "a51": '\u2738', - "a52": '\u2739', - "a53": '\u273a', - "a54": '\u273b', - "a55": '\u273c', - "a56": '\u273d', - "a57": '\u273e', - "a58": '\u273f', - "a59": '\u2740', - "a6": '\u271d', - "a60": '\u2741', - "a61": '\u2742', - "a62": '\u2743', - "a63": '\u2744', - "a64": '\u2745', - "a65": '\u2746', - "a66": '\u2747', - "a67": '\u2748', - "a68": '\u2749', - "a69": '\u274a', - "a7": '\u271e', - "a70": '\u274b', - "a71": '\u25cf', - "a72": '\u274d', - "a73": '\u25a0', - "a74": '\u274f', - "a75": '\u2751', - "a76": '\u25b2', - "a77": '\u25bc', - "a78": '\u25c6', - "a79": '\u2756', - "a8": '\u271f', - "a81": '\u25d7', - "a82": '\u2758', - "a83": '\u2759', - "a84": '\u275a', - "a85": '\u276f', - "a86": '\u2771', - "a87": '\u2772', - "a88": '\u2773', - "a89": '\u2768', - "a9": '\u2720', - "a90": '\u2769', - "a91": '\u276c', - "a92": '\u276d', - "a93": '\u276a', - "a94": '\u276b', - "a95": '\u2774', - "a96": '\u2775', - "a97": '\u275b', - "a98": '\u275c', - "a99": '\u275d', -} - -var zapfdingbatsRuneToGlyphMap = map[rune]string{ - '\u2701': "a1", - '\u2721': "a10", - '\u275e': "a100", - '\u2761': "a101", - '\u2762': "a102", - '\u2763': "a103", - '\u2764': "a104", - '\u2710': "a105", - '\u2765': "a106", - '\u2766': "a107", - '\u2767': "a108", - '\u2660': "a109", - '\u261b': "a11", - '\u2665': "a110", - '\u2666': "a111", - '\u2663': "a112", - '\u2709': "a117", - '\u2708': "a118", - '\u2707': "a119", - '\u261e': "a12", - '\u2460': "a120", - '\u2461': "a121", - '\u2462': "a122", - '\u2463': "a123", - '\u2464': "a124", - '\u2465': "a125", - '\u2466': "a126", - '\u2467': "a127", - '\u2468': "a128", - '\u2469': "a129", - '\u270c': "a13", - '\u2776': "a130", - '\u2777': "a131", - '\u2778': "a132", - '\u2779': "a133", - '\u277a': "a134", - '\u277b': "a135", - '\u277c': "a136", - '\u277d': "a137", - '\u277e': "a138", - '\u277f': "a139", - '\u270d': "a14", - '\u2780': "a140", - '\u2781': "a141", - '\u2782': "a142", - '\u2783': "a143", - '\u2784': "a144", - '\u2785': "a145", - '\u2786': "a146", - '\u2787': "a147", - '\u2788': "a148", - '\u2789': "a149", - '\u270e': "a15", - '\u278a': "a150", - '\u278b': "a151", - '\u278c': "a152", - '\u278d': "a153", - '\u278e': "a154", - '\u278f': "a155", - '\u2790': "a156", - '\u2791': "a157", - '\u2792': "a158", - '\u2793': "a159", - '\u270f': "a16", - '\u2794': "a160", - '\u2192': "a161", - '\u27a3': "a162", - '\u2194': "a163", - '\u2195': "a164", - '\u2799': "a165", - '\u279b': "a166", - '\u279c': "a167", - '\u279d': "a168", - '\u279e': "a169", - '\u2711': "a17", - '\u279f': "a170", - '\u27a0': "a171", - '\u27a1': "a172", - '\u27a2': "a173", - '\u27a4': "a174", - '\u27a5': "a175", - '\u27a6': "a176", - '\u27a7': "a177", - '\u27a8': "a178", - '\u27a9': "a179", - '\u2712': "a18", - '\u27ab': "a180", - '\u27ad': "a181", - '\u27af': "a182", - '\u27b2': "a183", - '\u27b3': "a184", - '\u27b5': "a185", - '\u27b8': "a186", - '\u27ba': "a187", - '\u27bb': "a188", - '\u27bc': "a189", - '\u2713': "a19", - '\u27bd': "a190", - '\u27be': "a191", - '\u279a': "a192", - '\u27aa': "a193", - '\u27b6': "a194", - '\u27b9': "a195", - '\u2798': "a196", - '\u27b4': "a197", - '\u27b7': "a198", - '\u27ac': "a199", - '\u2702': "a2", - '\u2714': "a20", - '\u27ae': "a200", - '\u27b1': "a201", - '\u2703': "a202", - '\u2750': "a203", - '\u2752': "a204", - '\u276e': "a205", - '\u2770': "a206", - '\u2715': "a21", - '\u2716': "a22", - '\u2717': "a23", - '\u2718': "a24", - '\u2719': "a25", - '\u271a': "a26", - '\u271b': "a27", - '\u271c': "a28", - '\u2722': "a29", - '\u2704': "a3", - '\u2723': "a30", - '\u2724': "a31", - '\u2725': "a32", - '\u2726': "a33", - '\u2727': "a34", - '\u2605': "a35", - '\u2729': "a36", - '\u272a': "a37", - '\u272b': "a38", - '\u272c': "a39", - '\u260e': "a4", - '\u272d': "a40", - '\u272e': "a41", - '\u272f': "a42", - '\u2730': "a43", - '\u2731': "a44", - '\u2732': "a45", - '\u2733': "a46", - '\u2734': "a47", - '\u2735': "a48", - '\u2736': "a49", - '\u2706': "a5", - '\u2737': "a50", - '\u2738': "a51", - '\u2739': "a52", - '\u273a': "a53", - '\u273b': "a54", - '\u273c': "a55", - '\u273d': "a56", - '\u273e': "a57", - '\u273f': "a58", - '\u2740': "a59", - '\u271d': "a6", - '\u2741': "a60", - '\u2742': "a61", - '\u2743': "a62", - '\u2744': "a63", - '\u2745': "a64", - '\u2746': "a65", - '\u2747': "a66", - '\u2748': "a67", - '\u2749': "a68", - '\u274a': "a69", - '\u271e': "a7", - '\u274b': "a70", - '\u25cf': "a71", - '\u274d': "a72", - '\u25a0': "a73", - '\u274f': "a74", - '\u2751': "a75", - '\u25b2': "a76", - '\u25bc': "a77", - '\u25c6': "a78", - '\u2756': "a79", - '\u271f': "a8", - '\u25d7': "a81", - '\u2758': "a82", - '\u2759': "a83", - '\u275a': "a84", - '\u276f': "a85", - '\u2771': "a86", - '\u2772': "a87", - '\u2773': "a88", - '\u2768': "a89", - '\u2720': "a9", - '\u2769': "a90", - '\u276c': "a91", - '\u276d': "a92", - '\u276a': "a93", - '\u276b': "a94", - '\u2774': "a95", - '\u2775': "a96", - '\u275b': "a97", - '\u275c': "a98", - '\u275d': "a99", -} diff --git a/pdf/model/fontfile.go b/pdf/model/fontfile.go index 8dcdc0df..0a22de4c 100644 --- a/pdf/model/fontfile.go +++ b/pdf/model/fontfile.go @@ -272,11 +272,3 @@ func isBinary(data []byte) bool { } return false } - -// truncate returns the first `n` characters f string `s`. -func truncate(s string, n int) string { - if len(s) < n { - return s - } - return s[:n] -} diff --git a/pdf/ps/parser_test.go b/pdf/ps/parser_test.go index 75b41c76..7dad5444 100644 --- a/pdf/ps/parser_test.go +++ b/pdf/ps/parser_test.go @@ -6,8 +6,6 @@ package ps import ( - "bufio" - "bytes" "errors" "fmt" "math" @@ -21,13 +19,6 @@ func init() { //common.SetLogger(common.NewConsoleLogger(common.LogLevelTrace)) } -func makeReaderForText(txt string) *bufio.Reader { - buf := []byte(txt) - bufReader := bytes.NewReader(buf) - bufferedReader := bufio.NewReader(bufReader) - return bufferedReader -} - func quickEval(progText string) (PSObject, error) { parser := NewPSParser([]byte(progText)) From 6d2c39043c08d07b255150a90992376d3d85aca3 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 20:22:33 +0200 Subject: [PATCH 4/7] make sure comments begin with a type/function name --- common/license/util.go | 2 +- common/logging.go | 4 +- common/version.go | 2 +- doc.go | 2 +- pdf/annotator/circle.go | 3 +- pdf/annotator/line.go | 6 +- pdf/annotator/rectangle.go | 6 +- pdf/contentstream/draw/bezier_curve.go | 4 +- pdf/contentstream/draw/path.go | 2 +- pdf/contentstream/draw/point.go | 2 +- pdf/contentstream/draw/utils.go | 4 +- pdf/contentstream/draw/vector.go | 2 +- pdf/contentstream/inline-image.go | 10 +-- pdf/contentstream/processor.go | 2 +- pdf/core/encoding.go | 110 +++++++++++-------------- pdf/core/parser.go | 6 +- pdf/core/primitives.go | 6 +- pdf/creator/drawable.go | 2 +- pdf/creator/table.go | 16 ++-- pdf/internal/sampling/resample.go | 4 +- pdf/model/colorspace.go | 61 +++++++------- pdf/model/fields.go | 5 ++ pdf/model/fonts/ttfparser.go | 6 +- pdf/model/functions.go | 18 ++-- pdf/model/image.go | 6 +- pdf/model/outlines.go | 5 +- pdf/model/page.go | 20 ++--- pdf/model/pattern.go | 16 ++-- pdf/model/resources.go | 32 +++---- pdf/model/shading.go | 18 ++-- pdf/model/structures.go | 6 +- pdf/model/writer.go | 2 +- pdf/model/xobject.go | 24 +++--- 33 files changed, 200 insertions(+), 214 deletions(-) diff --git a/common/license/util.go b/common/license/util.go index 9ddba152..c40e22ef 100644 --- a/common/license/util.go +++ b/common/license/util.go @@ -14,7 +14,7 @@ import ( // Defaults to the open source license. var licenseKey = MakeUnlicensedKey() -// Sets and validates the license key. +// SetLicenseKey sets and validates the license key. func SetLicenseKey(content string, customerName string) error { lk, err := licenseKeyDecode(content) if err != nil { diff --git a/common/logging.go b/common/logging.go index ae374229..87dc3efc 100644 --- a/common/logging.go +++ b/common/logging.go @@ -21,7 +21,7 @@ type Logger interface { Trace(format string, args ...interface{}) } -// Dummy Logger does nothing. +// DummyLogger does nothing. type DummyLogger struct{} func (this DummyLogger) Error(format string, args ...interface{}) { @@ -42,7 +42,7 @@ func (this DummyLogger) Debug(format string, args ...interface{}) { func (this DummyLogger) Trace(format string, args ...interface{}) { } -// Simple Console Logger that the tests use. +// LogLevel is the verbosity level for logging. type LogLevel int const ( diff --git a/common/version.go b/common/version.go index ce5fa222..1c0fa11e 100644 --- a/common/version.go +++ b/common/version.go @@ -16,7 +16,7 @@ const releaseDay = 14 const releaseHour = 19 const releaseMin = 40 -// Holds version information, when bumping this make sure to bump the released at stamp also. +// Version holds version information, when bumping this make sure to bump the released at stamp also. const Version = "2.1.1" var ReleasedAt = time.Date(releaseYear, releaseMonth, releaseDay, releaseHour, releaseMin, 0, 0, time.UTC) diff --git a/doc.go b/doc.go index edb7870a..c881630f 100644 --- a/doc.go +++ b/doc.go @@ -3,7 +3,7 @@ * file 'LICENSE.md', which is part of this source code package. */ -// UniDoc is a comprehensive PDF library for Go (golang). The library has advanced capabilities for generating, +// Package unidoc is a comprehensive PDF library for Go (golang). The library has advanced capabilities for generating, // processing and modifying PDFs. UniDoc is written and supported by the owners of the // FoxyUtils.com website, where the library is used to power many of the PDF services offered. // diff --git a/pdf/annotator/circle.go b/pdf/annotator/circle.go index 47681a12..59deeca3 100644 --- a/pdf/annotator/circle.go +++ b/pdf/annotator/circle.go @@ -26,7 +26,8 @@ type CircleAnnotationDef struct { Opacity float64 // Alpha value (0-1). } -// Creates a circle/ellipse annotation object with appearance stream that can be added to page PDF annotations. +// CreateCircleAnnotation creates a circle/ellipse annotation object with appearance stream that can be added to +// page PDF annotations. func CreateCircleAnnotation(circDef CircleAnnotationDef) (*pdf.PdfAnnotation, error) { circAnnotation := pdf.NewPdfAnnotationCircle() diff --git a/pdf/annotator/line.go b/pdf/annotator/line.go index cea9f60f..5d33b77b 100644 --- a/pdf/annotator/line.go +++ b/pdf/annotator/line.go @@ -12,8 +12,8 @@ import ( pdf "github.com/unidoc/unidoc/pdf/model" ) -// Defines a line between point 1 (X1,Y1) and point 2 (X2,Y2). The line ending styles can be none (regular line), -// or arrows at either end. The line also has a specified width, color and opacity. +// LineAnnotationDef defines a line between point 1 (X1,Y1) and point 2 (X2,Y2). The line ending styles can be none +// (regular line), or arrows at either end. The line also has a specified width, color and opacity. type LineAnnotationDef struct { X1 float64 Y1 float64 @@ -26,7 +26,7 @@ type LineAnnotationDef struct { LineEndingStyle2 draw.LineEndingStyle // Line ending style of point 2. } -// Creates a line annotation object that can be added to page PDF annotations. +// CreateLineAnnotation creates a line annotation object that can be added to page PDF annotations. func CreateLineAnnotation(lineDef LineAnnotationDef) (*pdf.PdfAnnotation, error) { // Line annotation. lineAnnotation := pdf.NewPdfAnnotationLine() diff --git a/pdf/annotator/rectangle.go b/pdf/annotator/rectangle.go index 2c6943c5..2d8798f4 100644 --- a/pdf/annotator/rectangle.go +++ b/pdf/annotator/rectangle.go @@ -13,8 +13,8 @@ import ( pdf "github.com/unidoc/unidoc/pdf/model" ) -// A rectangle defined with a specified Width and Height and a lower left corner at (X,Y). The rectangle can -// optionally have a border and a filling color. +// RectangleAnnotationDef is a rectangle defined with a specified Width and Height and a lower left corner at (X,Y). +// The rectangle can optionally have a border and a filling color. // The Width/Height includes the border (if any specified). type RectangleAnnotationDef struct { X float64 @@ -29,7 +29,7 @@ type RectangleAnnotationDef struct { Opacity float64 // Alpha value (0-1). } -// Creates a rectangle annotation object that can be added to page PDF annotations. +// CreateRectangleAnnotation creates a rectangle annotation object that can be added to page PDF annotations. func CreateRectangleAnnotation(rectDef RectangleAnnotationDef) (*pdf.PdfAnnotation, error) { rectAnnotation := pdf.NewPdfAnnotationSquare() diff --git a/pdf/contentstream/draw/bezier_curve.go b/pdf/contentstream/draw/bezier_curve.go index a32f89d6..b319bc4c 100644 --- a/pdf/contentstream/draw/bezier_curve.go +++ b/pdf/contentstream/draw/bezier_curve.go @@ -11,7 +11,7 @@ import ( "github.com/unidoc/unidoc/pdf/model" ) -// Cubic bezier curves are defined by: +// CubicBezierCurve is defined by: // R(t) = P0*(1-t)^3 + P1*3*t*(1-t)^2 + P2*3*t^2*(1-t) + P3*t^3 // where P0 is the current point, P1, P2 control points and P3 the final point. type CubicBezierCurve struct { @@ -30,7 +30,7 @@ func NewCubicBezierCurve(x0, y0, x1, y1, x2, y2, x3, y3 float64) CubicBezierCurv return curve } -// Add X,Y offset to all points on a curve. +// AddOffsetXY adds X,Y offset to all points on a curve. func (curve CubicBezierCurve) AddOffsetXY(offX, offY float64) CubicBezierCurve { curve.P0.X += offX curve.P1.X += offX diff --git a/pdf/contentstream/draw/path.go b/pdf/contentstream/draw/path.go index c0f1dacf..b82d3a99 100644 --- a/pdf/contentstream/draw/path.go +++ b/pdf/contentstream/draw/path.go @@ -5,7 +5,7 @@ package draw -// A path consists of straight line connections between each point defined in an array of points. +// Path consists of straight line connections between each point defined in an array of points. type Path struct { Points []Point } diff --git a/pdf/contentstream/draw/point.go b/pdf/contentstream/draw/point.go index eb5265c3..b7bd03a5 100644 --- a/pdf/contentstream/draw/point.go +++ b/pdf/contentstream/draw/point.go @@ -25,7 +25,7 @@ func (p Point) Add(dx, dy float64) Point { return p } -// Add vector to a point. +// AddVector adds vector to a point. func (this Point) AddVector(v Vector) Point { this.X += v.Dx this.Y += v.Dy diff --git a/pdf/contentstream/draw/utils.go b/pdf/contentstream/draw/utils.go index c54ae18e..56b426f0 100644 --- a/pdf/contentstream/draw/utils.go +++ b/pdf/contentstream/draw/utils.go @@ -4,7 +4,7 @@ import ( pdfcontent "github.com/unidoc/unidoc/pdf/contentstream" ) -// Make the path with the content creator. +// DrawPathWithCreator makes the path with the content creator. // Adds the PDF commands to draw the path to the creator instance. func DrawPathWithCreator(path Path, creator *pdfcontent.ContentCreator) { for idx, p := range path.Points { @@ -16,7 +16,7 @@ func DrawPathWithCreator(path Path, creator *pdfcontent.ContentCreator) { } } -// Make the bezier path with the content creator. +// DrawBezierPathWithCreator makes the bezier path with the content creator. // Adds the PDF commands to draw the path to the creator instance. func DrawBezierPathWithCreator(bpath CubicBezierPath, creator *pdfcontent.ContentCreator) { for idx, c := range bpath.Curves { diff --git a/pdf/contentstream/draw/vector.go b/pdf/contentstream/draw/vector.go index b8afc699..c97bc41c 100644 --- a/pdf/contentstream/draw/vector.go +++ b/pdf/contentstream/draw/vector.go @@ -47,7 +47,7 @@ func (v Vector) Rotate(phi float64) Vector { return NewVectorPolar(mag, angle+phi) } -// Change the sign of the vector: -vector. +// Flip changes the sign of the vector: -vector. func (this Vector) Flip() Vector { mag := this.Magnitude() theta := this.GetPolarAngle() diff --git a/pdf/contentstream/inline-image.go b/pdf/contentstream/inline-image.go index f778e4de..47d4d6b2 100644 --- a/pdf/contentstream/inline-image.go +++ b/pdf/contentstream/inline-image.go @@ -15,7 +15,7 @@ import ( "github.com/unidoc/unidoc/pdf/model" ) -// A representation of an inline image in a Content stream. Everything between the BI and EI operands. +// ContentStreamInlineImage is a representation of an inline image in a Content stream. Everything between the BI and EI operands. // ContentStreamInlineImage implements the core.PdfObject interface although strictly it is not a PDF object. type ContentStreamInlineImage struct { BitsPerComponent core.PdfObject @@ -31,7 +31,7 @@ type ContentStreamInlineImage struct { stream []byte } -// Make a new content stream inline image object from an image. +// NewInlineImageFromImage makes a new content stream inline image object from an image. func NewInlineImageFromImage(img model.Image, encoder core.StreamEncoder) (*ContentStreamInlineImage, error) { if encoder == nil { encoder = core.NewRawEncoder() @@ -198,7 +198,7 @@ func (img *ContentStreamInlineImage) GetEncoder() (core.StreamEncoder, error) { return newEncoderFromInlineImage(img) } -// Is a mask ? +// IsMask check if an image is a mask. // The image mask entry in the image dictionary specifies that the image data shall be used as a stencil // mask for painting in the current color. The mask data is 1bpc, grayscale. func (img *ContentStreamInlineImage) IsMask() (bool, error) { @@ -216,7 +216,7 @@ func (img *ContentStreamInlineImage) IsMask() (bool, error) { } -// Export the inline image to Image which can be transformed or exported easily. +// ToImage export the inline image to Image which can be transformed or exported easily. // Page resources are needed to look up colorspace information. func (img *ContentStreamInlineImage) ToImage(resources *model.PdfPageResources) (*model.Image, error) { // Decode the imaging data if encoded. @@ -297,7 +297,7 @@ func (img *ContentStreamInlineImage) ToImage(resources *model.PdfPageResources) return image, nil } -// Parse an inline image from a content stream, both read its properties and binary data. +// ParseInlineImage parses an inline image from a content stream, both read its properties and binary data. // When called, "BI" has already been read from the stream. This function // finishes reading through "EI" and then returns the ContentStreamInlineImage. func (csp *ContentStreamParser) ParseInlineImage() (*ContentStreamInlineImage, error) { diff --git a/pdf/contentstream/processor.go b/pdf/contentstream/processor.go index e10b8ca1..8bce425c 100644 --- a/pdf/contentstream/processor.go +++ b/pdf/contentstream/processor.go @@ -13,7 +13,7 @@ import ( "github.com/unidoc/unidoc/pdf/model" ) -// Basic graphics state implementation. +// GraphicsState is a basic graphics state implementation. // Initially only implementing and tracking a portion of the information specified. Easy to add more. type GraphicsState struct { ColorspaceStroking model.PdfColorspace diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index 377a0c99..151c19e6 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -63,7 +63,7 @@ type StreamEncoder interface { DecodeStream(streamObj *PdfObjectStream) ([]byte, error) } -// Flate encoding. +// FlateEncoder represents Flate encoding. type FlateEncoder struct { Predictor int BitsPerComponent int @@ -72,7 +72,7 @@ type FlateEncoder struct { Colors int } -// Make a new flate encoder with default parameters, predictor 1 and bits per component 8. +// NewFlateEncoder makes a new flate encoder with default parameters, predictor 1 and bits per component 8. func NewFlateEncoder() *FlateEncoder { encoder := &FlateEncoder{} @@ -88,7 +88,7 @@ func NewFlateEncoder() *FlateEncoder { return encoder } -// Set the predictor function. Specify the number of columns per row. +// SetPredictor sets the predictor function. Specify the number of columns per row. // The columns indicates the number of samples per row. // Used for grouping data together for compression. func (this *FlateEncoder) SetPredictor(columns int) { @@ -122,7 +122,7 @@ func (this *FlateEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set and the DecodeParms. func (this *FlateEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() @@ -246,7 +246,7 @@ func (this *FlateEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return outBuf.Bytes(), nil } -// Decode a FlateEncoded stream object and give back decoded bytes. +// DecodeStream decodes a FlateEncoded stream object and give back decoded bytes. func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { // TODO: Handle more filter bytes and support more values of BitsPerComponent. @@ -398,7 +398,7 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro return outData, nil } -// Encode a bytes array and return the encoded value based on the encoder parameters. +// EncodeBytes encodes a bytes array and return the encoded value based on the encoder parameters. func (this *FlateEncoder) EncodeBytes(data []byte) ([]byte, error) { if this.Predictor != 1 && this.Predictor != 11 { common.Log.Debug("Encoding error: FlateEncoder Predictor = 1, 11 only supported") @@ -445,7 +445,7 @@ func (this *FlateEncoder) EncodeBytes(data []byte) ([]byte, error) { return b.Bytes(), nil } -// LZW encoding/decoding functionality. +// LZWEncoder provides LZW encoding/decoding functionality. type LZWEncoder struct { Predictor int BitsPerComponent int @@ -456,7 +456,7 @@ type LZWEncoder struct { EarlyChange int } -// Make a new LZW encoder with default parameters. +// NewLZWEncoder makes a new LZW encoder with default parameters. func NewLZWEncoder() *LZWEncoder { encoder := &LZWEncoder{} @@ -497,7 +497,7 @@ func (this *LZWEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set and the DecodeParms. func (this *LZWEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() @@ -770,7 +770,7 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) return outData, nil } -// Support for encoding LZW. Currently not supporting predictors (raw compressed data only). +// EncodeBytes implements support for LZW encoding. Currently not supporting predictors (raw compressed data only). // Only supports the Early change = 1 algorithm (compress/lzw) as the other implementation // does not have a write method. // TODO: Consider refactoring compress/lzw to allow both. @@ -791,8 +791,7 @@ func (this *LZWEncoder) EncodeBytes(data []byte) ([]byte, error) { return b.Bytes(), nil } -// -// DCT (JPG) encoding/decoding functionality for images. +// DCTEncoder provides a DCT (JPG) encoding/decoding functionality for images. type DCTEncoder struct { ColorComponents int // 1 (gray), 3 (rgb), 4 (cmyk) BitsPerComponent int // 8 or 16 bit @@ -801,7 +800,7 @@ type DCTEncoder struct { Quality int } -// Make a new DCT encoder with default parameters. +// NewDCTEncoder makes a new DCT encoder with default parameters. func NewDCTEncoder() *DCTEncoder { encoder := &DCTEncoder{} @@ -822,7 +821,7 @@ func (this *DCTEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set. Some other parameters are generated elsewhere. func (this *DCTEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() @@ -1102,11 +1101,11 @@ func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { return buf.Bytes(), nil } -// Run length encoding. +// RunLengthEncoder represents Run length encoding. type RunLengthEncoder struct { } -// Make a new run length encoder +// NewRunLengthEncoder makes a new run length encoder func NewRunLengthEncoder() *RunLengthEncoder { return &RunLengthEncoder{} } @@ -1117,19 +1116,20 @@ func (this *RunLengthEncoder) GetFilterName() string { // Create a new run length decoder from a stream object. func newRunLengthEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObjectDictionary) (*RunLengthEncoder, error) { - // TODO(dennwc): unused paramaters + // TODO(dennwc): unused paramaters; should verify that they are empty? return NewRunLengthEncoder(), nil } -/* - 7.4.5 RunLengthDecode Filter - The RunLengthDecode filter decodes data that has been encoded in a simple byte-oriented format based on run length. - The encoded data shall be a sequence of runs, where each run shall consist of a length byte followed by 1 to 128 - bytes of data. If the length byte is in the range 0 to 127, the following length + 1 (1 to 128) bytes shall be - copied literally during decompression. If length is in the range 129 to 255, the following single byte shall be - copied 257 - length (2 to 128) times during decompression. A length value of 128 shall denote EOD. -*/ +// DecodeBytes decodes a byte slice from Run length encoding. +// +// 7.4.5 RunLengthDecode Filter +// The RunLengthDecode filter decodes data that has been encoded in a simple byte-oriented format based on run length. +// The encoded data shall be a sequence of runs, where each run shall consist of a length byte followed by 1 to 128 +// bytes of data. If the length byte is in the range 0 to 127, the following length + 1 (1 to 128) bytes shall be +// copied literally during decompression. If length is in the range 129 to 255, the following single byte shall be +// copied 257 - length (2 to 128) times during decompression. A length value of 128 shall denote EOD. func (this *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { + // TODO(dennwc): use encoded slice directly, instead of wrapping it into a Reader bufReader := bytes.NewReader(encoded) var inb []byte for { @@ -1161,12 +1161,12 @@ func (this *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return inb, nil } -// Decode RunLengthEncoded stream object and give back decoded bytes. +// DecodeStream decodes RunLengthEncoded stream object and give back decoded bytes. func (this *RunLengthEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { return this.DecodeBytes(streamObj.Stream) } -// Encode a bytes array and return the encoded value based on the encoder parameters. +// EncodeBytes encodes a bytes array and return the encoded value based on the encoder parameters. func (this *RunLengthEncoder) EncodeBytes(data []byte) ([]byte, error) { bufReader := bytes.NewReader(data) var inb []byte @@ -1238,19 +1238,18 @@ func (this *RunLengthEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *RunLengthEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() dict.Set("Filter", MakeName(this.GetFilterName())) return dict } -///// -// ASCII hex encoder/decoder. +// ASCIIHexEncoder implements ASCII hex encoder/decoder. type ASCIIHexEncoder struct { } -// Make a new ASCII hex encoder. +// NewASCIIHexEncoder makes a new ASCII hex encoder. func NewASCIIHexEncoder() *ASCIIHexEncoder { encoder := &ASCIIHexEncoder{} return encoder @@ -1264,7 +1263,7 @@ func (this *ASCIIHexEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *ASCIIHexEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() dict.Set("Filter", MakeName(this.GetFilterName())) @@ -1304,7 +1303,7 @@ func (this *ASCIIHexEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return outb, nil } -// ASCII hex decoding. +// DecodeStream implements ASCII hex decoding. func (this *ASCIIHexEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { return this.DecodeBytes(streamObj.Stream) } @@ -1320,13 +1319,11 @@ func (this *ASCIIHexEncoder) EncodeBytes(data []byte) ([]byte, error) { return encoded.Bytes(), nil } -// -// ASCII85 encoder/decoder. -// +// ASCII85Encoder implements ASCII85 encoder/decoder. type ASCII85Encoder struct { } -// Make a new ASCII85 encoder. +// NewASCII85Encoder makes a new ASCII85 encoder. func NewASCII85Encoder() *ASCII85Encoder { encoder := &ASCII85Encoder{} return encoder @@ -1340,14 +1337,14 @@ func (this *ASCII85Encoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict make a new instance of an encoding dictionary for a stream object. func (this *ASCII85Encoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() dict.Set("Filter", MakeName(this.GetFilterName())) return dict } -// 5 ASCII characters -> 4 raw binary bytes +// DecodeBytes decodes byte array with ASCII85. 5 ASCII characters -> 4 raw binary bytes func (this *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { var decoded []byte @@ -1425,7 +1422,7 @@ func (this *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { return decoded, nil } -// ASCII85 stream decoding. +// DecodeStream implements ASCII85 stream decoding. func (this *ASCII85Encoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { return this.DecodeBytes(streamObj.Stream) } @@ -1449,7 +1446,7 @@ func (this *ASCII85Encoder) base256Tobase85(base256val uint32) [5]byte { return base85 } -// Encode data into ASCII85 encoded format. +// EncodeBytes encodes data into ASCII85 encoded format. func (this *ASCII85Encoder) EncodeBytes(data []byte) ([]byte, error) { var encoded bytes.Buffer @@ -1492,9 +1489,7 @@ func (this *ASCII85Encoder) EncodeBytes(data []byte) ([]byte, error) { return encoded.Bytes(), nil } -// -// Raw encoder/decoder (no encoding, pass through) -// +// RawEncoder implements Raw encoder/decoder (no encoding, pass through) type RawEncoder struct{} func NewRawEncoder() *RawEncoder { @@ -1509,7 +1504,7 @@ func (this *RawEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *RawEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } @@ -1526,9 +1521,8 @@ func (this *RawEncoder) EncodeBytes(data []byte) ([]byte, error) { return data, nil } -// -// CCITTFax encoder/decoder (dummy, for now) -// +// CCITTFaxEncoder implements CCITTFax encoder/decoder (dummy, for now) +// FIXME: implement type CCITTFaxEncoder struct{} func NewCCITTFaxEncoder() *CCITTFaxEncoder { @@ -1543,7 +1537,7 @@ func (this *CCITTFaxEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *CCITTFaxEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } @@ -1563,9 +1557,8 @@ func (this *CCITTFaxEncoder) EncodeBytes(data []byte) ([]byte, error) { return data, ErrNoCCITTFaxDecode } -// -// JBIG2 encoder/decoder (dummy, for now) -// +// JBIG2Encoder implements JBIG2 encoder/decoder (dummy, for now) +// FIXME: implement type JBIG2Encoder struct{} func NewJBIG2Encoder() *JBIG2Encoder { @@ -1580,7 +1573,7 @@ func (this *JBIG2Encoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *JBIG2Encoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } @@ -1600,9 +1593,8 @@ func (this *JBIG2Encoder) EncodeBytes(data []byte) ([]byte, error) { return data, ErrNoJBIG2Decode } -// -// JPX encoder/decoder (dummy, for now) -// +// JPXEncoder implements JPX encoder/decoder (dummy, for now) +// FIXME: implement type JPXEncoder struct{} func NewJPXEncoder() *JPXEncoder { @@ -1617,7 +1609,7 @@ func (this *JPXEncoder) MakeDecodeParams() PdfObject { return nil } -// Make a new instance of an encoding dictionary for a stream object. +// MakeStreamDict makes a new instance of an encoding dictionary for a stream object. func (this *JPXEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } @@ -1637,9 +1629,7 @@ func (this *JPXEncoder) EncodeBytes(data []byte) ([]byte, error) { return data, ErrNoJPXDecode } -// -// Multi encoder: support serial encoding. -// +// MultiEncoder supports serial encoding. type MultiEncoder struct { // Encoders in the order that they are to be applied. encoders []StreamEncoder diff --git a/pdf/core/parser.go b/pdf/core/parser.go index f8418bba..109016ec 100755 --- a/pdf/core/parser.go +++ b/pdf/core/parser.go @@ -589,7 +589,7 @@ func (parser *PdfParser) parseObject() (PdfObject, error) { } } -// Reads and parses a PDF dictionary object enclosed with '<<' and '>>' +// ParseDict reads and parses a PDF dictionary object enclosed with '<<' and '>>' // TODO: Unexport (v3). func (parser *PdfParser) ParseDict() (*PdfObjectDictionary, error) { common.Log.Trace("Reading PDF Dict!") @@ -1325,7 +1325,7 @@ func (parser *PdfParser) traceStreamLength(lengthObj PdfObject) (PdfObject, erro return slo, nil } -// Parse an indirect object from the input stream. Can also be an object stream. +// ParseIndirectObject parses an indirect object from the input stream. Can also be an object stream. // Returns the indirect object (*PdfIndirectObject) or the stream object (*PdfObjectStream). // TODO: Unexport (v3). func (parser *PdfParser) ParseIndirectObject() (PdfObject, error) { @@ -1504,7 +1504,7 @@ func (parser *PdfParser) ParseIndirectObject() (PdfObject, error) { return &indirect, nil } -// For testing purposes. +// NewParserFromString is used for testing purposes. // TODO: Unexport (v3) or move to test files, if needed by external test cases. func NewParserFromString(txt string) *PdfParser { parser := PdfParser{} diff --git a/pdf/core/primitives.go b/pdf/core/primitives.go index 3daae1d2..80366915 100644 --- a/pdf/core/primitives.go +++ b/pdf/core/primitives.go @@ -17,10 +17,10 @@ import ( // PdfObject is an interface which all primitive PDF objects must implement. type PdfObject interface { - // Output a string representation of the primitive (for debugging). + // String outputs a string representation of the primitive (for debugging). String() string - // Output the PDF primitive as written to file as expected by the standard. + // DefaultWriteString outputs the PDF primitive as written to file as expected by the standard. DefaultWriteString() string } @@ -869,7 +869,7 @@ func GetStringVal(obj PdfObject) (val string, found bool) { return } -// GetStringVal is like GetStringVal except that it returns the string as a []byte. +// GetStringBytes is like GetStringVal except that it returns the string as a []byte. // It is for convenience. func GetStringBytes(obj PdfObject) (val []byte, found bool) { so, found := TraceToDirectObject(obj).(*PdfObjectString) diff --git a/pdf/creator/drawable.go b/pdf/creator/drawable.go index 1243a8c6..9812300b 100644 --- a/pdf/creator/drawable.go +++ b/pdf/creator/drawable.go @@ -7,7 +7,7 @@ package creator // Drawable is a widget that can be used to draw with the Creator. type Drawable interface { - // Draw onto blocks representing Page contents. As the content can wrap over many pages, multiple + // GeneratePageBlocks draw onto blocks representing Page contents. As the content can wrap over many pages, multiple // templates are returned, one per Page. The function also takes a draw context containing information // where to draw (if relative positioning) and the available height to draw on accounting for Margins etc. GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, error) diff --git a/pdf/creator/table.go b/pdf/creator/table.go index cc32c8f0..238d491c 100644 --- a/pdf/creator/table.go +++ b/pdf/creator/table.go @@ -468,10 +468,10 @@ type CellBorderStyle int // Currently supported table styles are: None (no border) and boxed (line along each side). const ( - // No border - CellBorderStyleNone CellBorderStyle = iota + CellBorderStyleNone CellBorderStyle = iota // no border // Borders along all sides (boxed). + CellBorderStyleSingle CellBorderStyleDouble ) @@ -501,13 +501,13 @@ type CellHorizontalAlignment int // Table cells have three horizontal alignment modes: left, center and right. const ( - // Align cell content on the left (with specified indent); unused space on the right. + // CellHorizontalAlignmentLeft aligns cell content on the left (with specified indent); unused space on the right. CellHorizontalAlignmentLeft CellHorizontalAlignment = iota - // Align cell content in the middle (unused space divided equally on the left/right). + // CellHorizontalAlignmentCenter aligns cell content in the middle (unused space divided equally on the left/right). CellHorizontalAlignmentCenter - // Align the cell content on the right; unsued space on the left. + // CellHorizontalAlignmentRight aligns the cell content on the right; unsued space on the left. CellHorizontalAlignmentRight ) @@ -516,13 +516,13 @@ type CellVerticalAlignment int // Table cells have three vertical alignment modes: top, middle and bottom. const ( - // Align cell content vertically to the top; unused space below. + // CellVerticalAlignmentTop aligns cell content vertically to the top; unused space below. CellVerticalAlignmentTop CellVerticalAlignment = iota - // Align cell content in the middle; unused space divided equally above and below. + // CellVerticalAlignmentMiddle aligns cell content in the middle; unused space divided equally above and below. CellVerticalAlignmentMiddle - // Align cell content on the bottom; unused space above. + // CellVerticalAlignmentBottom aligns cell content on the bottom; unused space above. CellVerticalAlignmentBottom ) diff --git a/pdf/internal/sampling/resample.go b/pdf/internal/sampling/resample.go index e9447f88..c4d2247e 100644 --- a/pdf/internal/sampling/resample.go +++ b/pdf/internal/sampling/resample.go @@ -5,7 +5,7 @@ package sampling -// Resample the raw data which is in 8-bit (byte) format as a different +// ResampleBytes resamples the raw data which is in 8-bit (byte) format as a different // bit count per sample, up to 32 bits (uint32). func ResampleBytes(data []byte, bitsPerSample int) []uint32 { var samples []uint32 @@ -96,7 +96,7 @@ func ResampleBytes(data []byte, bitsPerSample int) []uint32 { return samples } -// Resample the raw data which is in <=32-bit (uint32) format as a different +// ResampleUint32 resamples the raw data which is in <=32-bit (uint32) format as a different // bit count per sample, up to 32 bits (uint32). // // bitsPerOutputSample is the number of bits for each output sample (up to 32) diff --git a/pdf/model/colorspace.go b/pdf/model/colorspace.go index 9b908976..a0c1c690 100644 --- a/pdf/model/colorspace.go +++ b/pdf/model/colorspace.go @@ -219,7 +219,7 @@ func (this *PdfColorDeviceGray) Val() float64 { return float64(*this) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorDeviceGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return uint32(maxVal * this.Val()) @@ -282,7 +282,7 @@ func (this *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (P return this.ColorFromFloats(floats) } -// Convert gray -> rgb for a single color component. +// ColorToRGB converts gray -> rgb for a single color component. func (this *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) { gray, ok := color.(*PdfColorDeviceGray) if !ok { @@ -293,7 +293,7 @@ func (this *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error return NewPdfColorDeviceRGB(float64(*gray), float64(*gray), float64(*gray)), nil } -// Convert 1-component grayscale data to 3-component RGB. +// ImageToRGB convert 1-component grayscale data to 3-component RGB. func (this *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { rgbImage := img @@ -343,7 +343,7 @@ func (this *PdfColorDeviceRGB) B() float64 { return float64(this[2]) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorDeviceRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return [3]uint32{uint32(maxVal * this.R()), uint32(maxVal * this.G()), uint32(maxVal * this.B())} @@ -412,7 +412,7 @@ func (this *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, e } -// Get the color from a series of pdf objects (3 for rgb). +// ColorFromPdfObjects gets the color from a series of pdf objects (3 for rgb). func (this *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") @@ -473,7 +473,7 @@ func (this *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { // C, M, Y, K components. // No other parameters. -// Each component is defined in the range 0.0 - 1.0 where 1.0 is the primary intensity. +// PdfColorDeviceCMYK is a CMYK color, where each component is defined in the range 0.0 - 1.0 where 1.0 is the primary intensity. type PdfColorDeviceCMYK [4]float64 func NewPdfColorDeviceCMYK(c, m, y, k float64) *PdfColorDeviceCMYK { @@ -501,7 +501,7 @@ func (this *PdfColorDeviceCMYK) K() float64 { return float64(this[3]) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorDeviceCMYK) ToInteger(bits int) [4]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return [4]uint32{uint32(maxVal * this.C()), uint32(maxVal * this.M()), uint32(maxVal * this.Y()), uint32(maxVal * this.K())} @@ -563,7 +563,7 @@ func (this *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, return color, nil } -// Get the color from a series of pdf objects (4 for cmyk). +// ColorFromPdfObjects gets the color from a series of pdf objects (4 for cmyk). func (this *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 4 { return nil, errors.New("Range check") @@ -679,13 +679,13 @@ func (this *PdfColorCalGray) Val() float64 { return float64(*this) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorCalGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return uint32(maxVal * this.Val()) } -// CalGray color space. +// PdfColorspaceCalGray represents CalGray color space. type PdfColorspaceCalGray struct { WhitePoint []float64 // [XW, YW, ZW]: Required BlackPoint []float64 // [XB, YB, ZB] @@ -886,7 +886,7 @@ func (this *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { return NewPdfColorDeviceRGB(r, g, b), nil } -// A, B, C -> X, Y, Z +// ImageToRGB converts image in CalGray color space to RGB (A, B, C -> X, Y, Z). func (this *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { rgbImage := img @@ -956,13 +956,13 @@ func (this *PdfColorCalRGB) C() float64 { return float64(this[2]) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorCalRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return [3]uint32{uint32(maxVal * this.A()), uint32(maxVal * this.B()), uint32(maxVal * this.C())} } -// A, B, C components +// PdfColorspaceCalRGB stores A, B, C components type PdfColorspaceCalRGB struct { WhitePoint []float64 BlackPoint []float64 @@ -973,8 +973,8 @@ type PdfColorspaceCalRGB struct { container *PdfIndirectObject } -// require parameters? func NewPdfColorspaceCalRGB() *PdfColorspaceCalRGB { + // TODO: require parameters? cs := &PdfColorspaceCalRGB{} // Set optional parameters to default values. @@ -1106,7 +1106,7 @@ func newPdfColorspaceCalRGBFromPdfObject(obj PdfObject) (*PdfColorspaceCalRGB, e return cs, nil } -// Return as PDF object format [name dictionary] +// ToPdfObject returns colorspace in a PDF object format [name dictionary] func (this *PdfColorspaceCalRGB) ToPdfObject() PdfObject { // CalRGB color space dictionary.. cspace := &PdfObjectArray{} @@ -1289,13 +1289,13 @@ func (this *PdfColorLab) B() float64 { return float64(this[2]) } -// Convert to an integer format. +// ToInteger convert to an integer format. func (this *PdfColorLab) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 return [3]uint32{uint32(maxVal * this.L()), uint32(maxVal * this.A()), uint32(maxVal * this.B())} } -// L*, a*, b* 3 component colorspace. +// PdfColorspaceLab is a L*, a*, b* 3 component colorspace. type PdfColorspaceLab struct { WhitePoint []float64 // Required. BlackPoint []float64 @@ -1327,8 +1327,8 @@ func (this *PdfColorspaceLab) DecodeArray() []float64 { return decode } -// require parameters? func NewPdfColorspaceLab() *PdfColorspaceLab { + // TODO: require parameters? cs := &PdfColorspaceLab{} // Set optional parameters to default values. @@ -1429,7 +1429,7 @@ func newPdfColorspaceLabFromPdfObject(obj PdfObject) (*PdfColorspaceLab, error) return cs, nil } -// Return as PDF object format [name dictionary] +// ToPdfObject returns colorspace in a PDF object format [name dictionary] func (this *PdfColorspaceLab) ToPdfObject() PdfObject { // CalRGB color space dictionary.. csObj := MakeArray() @@ -1668,7 +1668,7 @@ func (this *PdfColorICCBased) ToInteger(bits int) []uint32 { */ // See p. 157 for calculations... -// format [/ICCBased stream] +// PdfColorspaceICCBased format [/ICCBased stream] // // The stream shall contain the ICC profile. // A conforming reader shall support ICC.1:2004:10 as required by PDF 1.7, which will enable it @@ -1801,7 +1801,7 @@ func newPdfColorspaceICCBasedFromPdfObject(obj PdfObject) (*PdfColorspaceICCBase return cs, nil } -// Return as PDF object format [name stream] +// ToPdfObject returns colorspace in a PDF object format [name stream] func (this *PdfColorspaceICCBased) ToPdfObject() PdfObject { csObj := &PdfObjectArray{} @@ -1955,7 +1955,7 @@ type PdfColorPattern struct { PatternName PdfObjectName // Name of the pattern (reference via resource dicts). } -// Pattern colorspace. +// PdfColorspaceSpecialPattern is a Pattern colorspace. // Can be defined either as /Pattern or with an underlying colorspace [/Pattern cs]. type PdfColorspaceSpecialPattern struct { UnderlyingCS PdfColorspace @@ -2053,6 +2053,7 @@ func (this *PdfColorspaceSpecialPattern) ColorFromFloats(vals []float64) (PdfCol return this.UnderlyingCS.ColorFromFloats(vals) } +// ColorFromPdfObjects loads the color from PDF objects. // The first objects (if present) represent the color in underlying colorspace. The last one represents // the name of the pattern. func (this *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { @@ -2087,7 +2088,7 @@ func (this *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject return patternColor, nil } -// Only converts color used with uncolored patterns (defined in underlying colorspace). Does not go into the +// ColorToRGB only converts color used with uncolored patterns (defined in underlying colorspace). Does not go into the // pattern objects and convert those. If that is desired, needs to be done separately. See for example // grayscale conversion example in unidoc-examples repo. func (this *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, error) { @@ -2109,15 +2110,14 @@ func (this *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, e return this.UnderlyingCS.ColorToRGB(patternColor.Color) } -// An image cannot be defined in a pattern colorspace, returns an error. +// ImageToRGB returns an error since an image cannot be defined in a pattern colorspace. func (this *PdfColorspaceSpecialPattern) ImageToRGB(img Image) (Image, error) { common.Log.Debug("Error: Image cannot be specified in Pattern colorspace") return img, errors.New("Invalid colorspace for image (pattern)") } -////////////////////// -// Indexed colorspace. An indexed color space is a lookup table, where the input element is an index to the lookup -// table and the output is a color defined in the lookup table in the Base colorspace. +// PdfColorspaceSpecialIndexed is an indexed color space is a lookup table, where the input element is an index to the +// lookup table and the output is a color defined in the lookup table in the Base colorspace. // [/Indexed base hival lookup] type PdfColorspaceSpecialIndexed struct { Base PdfColorspace @@ -2284,7 +2284,7 @@ func (this *PdfColorspaceSpecialIndexed) ColorToRGB(color PdfColor) (PdfColor, e return this.Base.ColorToRGB(color) } -// Convert an indexed image to RGB. +// ImageToRGB convert an indexed image to RGB. func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { //baseImage := img // Make a new representation of the image to be converted with the base colorspace. @@ -2329,7 +2329,7 @@ func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { return this.Base.ImageToRGB(baseImage) } -// [/Indexed base hival lookup] +// ToPdfObject converts colorspace to a PDF object. [/Indexed base hival lookup] func (this *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { csObj := MakeArray(MakeName("Indexed")) csObj.Append(this.Base.ToPdfObject()) @@ -2344,8 +2344,7 @@ func (this *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { return csObj } -////////////////////// -// Separation colorspace. +// PdfColorspaceSpecialSeparation is a Separation colorspace. // At the moment the colour space is set to a Separation space, the conforming reader shall determine whether the // device has an available colorant (e.g. dye) corresponding to the name of the requested space. If so, the conforming // reader shall ignore the alternateSpace and tintTransform parameters; subsequent painting operations within the diff --git a/pdf/model/fields.go b/pdf/model/fields.go index dee44309..678e6a67 100644 --- a/pdf/model/fields.go +++ b/pdf/model/fields.go @@ -25,17 +25,20 @@ const ( FieldFlagClear FieldFlag = 0 // Flags for all field types. + FieldFlagReadOnly FieldFlag = 1 FieldFlagRequired FieldFlag = (1 << 1) FieldFlagNoExport FieldFlag = (2 << 1) // Flags for button fields only. + FieldFlagNoToggleToOff FieldFlag = (1 << 14) FieldFlagRadio FieldFlag = (1 << 15) FieldFlagPushbutton FieldFlag = (1 << 16) FieldFlagRadiosInUnision FieldFlag = (1 << 25) // Flags for text fields only. + FieldFlagMultiline FieldFlag = (1 << 12) FieldFlagPassword FieldFlag = (1 << 13) FieldFlagFileSelect FieldFlag = (1 << 20) @@ -44,9 +47,11 @@ const ( FieldFlagRichText FieldFlag = (1 << 25) // Flags for text and choice fields. + FieldFlagDoNotSpellCheck FieldFlag = (1 << 22) // Flags for choice fields only. + FieldFlagCombo FieldFlag = (1 << 17) FieldFlagEdit FieldFlag = (1 << 18) FieldFlagSort FieldFlag = (1 << 19) diff --git a/pdf/model/fonts/ttfparser.go b/pdf/model/fonts/ttfparser.go index 0c86cf5d..303348ca 100644 --- a/pdf/model/fonts/ttfparser.go +++ b/pdf/model/fonts/ttfparser.go @@ -157,7 +157,7 @@ func NewFontFile2FromPdfObject(obj core.PdfObject) (TtfType, error) { return t.Parse() } -// NewFontFile2FromPdfObject returns a TtfType describing the TrueType font file in disk file `fileStr`. +// TtfParse returns a TtfType describing the TrueType font file in disk file `fileStr`. func TtfParse(fileStr string) (TtfType, error) { f, err := os.Open(fileStr) if err != nil { @@ -169,7 +169,7 @@ func TtfParse(fileStr string) (TtfType, error) { return t.Parse() } -// NewFontFile2FromPdfObject returns a TtfType describing the TrueType font file in io.Reader `t`.f. +// Parse returns a TtfType describing the TrueType font file in io.Reader `t`.f. func (t *ttfParser) Parse() (TtfType, error) { version, err := t.ReadStr(4) @@ -813,7 +813,7 @@ func (t *ttfParser) ReadULong() (val uint32) { return val } -// ReadULong reads 4 bytes and returns them as a float, the first 2 bytes for the whole number and +// Read32Fixed reads 4 bytes and returns them as a float, the first 2 bytes for the whole number and // the second 2 bytes for the fraction. func (t *ttfParser) Read32Fixed() float64 { whole := float64(t.ReadShort()) diff --git a/pdf/model/functions.go b/pdf/model/functions.go index 96e3afe3..2d39b65d 100644 --- a/pdf/model/functions.go +++ b/pdf/model/functions.go @@ -95,11 +95,9 @@ func interpolate(x, xmin, xmax, ymin, ymax float64) float64 { return y } -// -// Type 0 functions use a sequence of sample values (contained in a stream) to provide an approximation +// PdfFunctionType0 uses a sequence of sample values (contained in a stream) to provide an approximation // for functions whose domains and ranges are bounded. The samples are organized as an m-dimensional // table in which each entry has n components -// type PdfFunctionType0 struct { Domain []float64 // required; 2*m length; where m is the number of input values Range []float64 // required (type 0); 2*n length; where n is the number of output values @@ -360,13 +358,11 @@ func (this *PdfFunctionType0) processSamples() error { return nil } -// -// Type 2 functions define an exponential interpolation of one input value and n +// PdfFunctionType2 defines an exponential interpolation of one input value and n // output values: // f(x) = y_0, ..., y_(n-1) // y_j = C0_j + x^N * (C1_j - C0_j); for 0 <= j < n // When N=1 ; linear interpolation between C0 and C1. -// type PdfFunctionType2 struct { Domain []float64 Range []float64 @@ -543,10 +539,8 @@ func (this *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) { return y, nil } -// -// Type 3 functions define stitching of the subdomains of serveral 1-input functions to produce +// PdfFunctionType3 defines stitching of the subdomains of serveral 1-input functions to produce // a single new 1-input function. -// type PdfFunctionType3 struct { Domain []float64 Range []float64 @@ -724,9 +718,7 @@ func (this *PdfFunctionType3) ToPdfObject() PdfObject { } } -// -// Type 4. Postscript calculator functions. -// +// PdfFunctionType4 is a Postscript calculator functions. type PdfFunctionType4 struct { Domain []float64 Range []float64 @@ -738,7 +730,7 @@ type PdfFunctionType4 struct { container *PdfObjectStream } -// Input [x1 x2 x3] +// Evaluate runs the function. Input is [x1 x2 x3]. func (this *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) { if this.executor == nil { this.executor = ps.NewPSExecutor(this.Program) diff --git a/pdf/model/image.go b/pdf/model/image.go index 0cf2f1bb..0d5ba0ed 100644 --- a/pdf/model/image.go +++ b/pdf/model/image.go @@ -221,7 +221,7 @@ type ImageHandler interface { // Read any image type and load into a new Image object. Read(r io.Reader) (*Image, error) - // Load a unidoc Image from a standard Go image structure. + // NewImageFromGoImage load a unidoc Image from a standard Go image structure. NewImageFromGoImage(goimg goimage.Image) (*Image, error) // Compress an image. @@ -231,7 +231,7 @@ type ImageHandler interface { // DefaultImageHandler is the default implementation of the ImageHandler using the standard go library. type DefaultImageHandler struct{} -// Create a unidoc Image from a golang Image. +// NewImageFromGoImage creates a unidoc Image from a golang Image. func (ih DefaultImageHandler) NewImageFromGoImage(goimg goimage.Image) (*Image, error) { // Speed up jpeg encoding by converting to RGBA first. // Will not be required once the golang image/jpeg package is optimized. @@ -289,7 +289,7 @@ func (ih DefaultImageHandler) Compress(input *Image, quality int64) (*Image, err return input, nil } -// ImageHandler is used for handling images. +// ImageHandling is used for handling images. var ImageHandling ImageHandler = DefaultImageHandler{} // SetImageHandler sets the image handler used by the package. diff --git a/pdf/model/outlines.go b/pdf/model/outlines.go index 6f43e95c..0deb28cb 100644 --- a/pdf/model/outlines.go +++ b/pdf/model/outlines.go @@ -233,7 +233,7 @@ func (this *PdfOutline) GetContainingPdfObject() PdfObject { return this.primitive } -// Recursively build the Outline tree PDF object. +// ToPdfObject recursively builds the Outline tree PDF object. func (this *PdfOutline) ToPdfObject() PdfObject { container := this.primitive dict := container.PdfObject.(*PdfObjectDictionary) @@ -260,8 +260,7 @@ func (this *PdfOutlineItem) GetContainingPdfObject() PdfObject { return this.primitive } -// Outline item. -// Recursively build the Outline tree PDF object. +// ToPdfObject recursively builds the Outline tree PDF object. func (this *PdfOutlineItem) ToPdfObject() PdfObject { container := this.primitive dict := container.PdfObject.(*PdfObjectDictionary) diff --git a/pdf/model/page.go b/pdf/model/page.go index 834b7918..d73526bb 100644 --- a/pdf/model/page.go +++ b/pdf/model/page.go @@ -362,7 +362,7 @@ func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotati return annotations, nil } -// Get the inheritable media box value, either from the page +// GetMediaBox gets the inheritable media box value, either from the page // or a higher up page/pages struct. func (this *PdfPage) GetMediaBox() (*PdfRectangle, error) { if this.MediaBox != nil { @@ -441,7 +441,7 @@ func (this *PdfPage) getResources() (*PdfPageResources, error) { return nil, nil } -// Convert the Page to a PDF object dictionary. +// GetPageDict convert the Page to a PDF object dictionary. func (this *PdfPage) GetPageDict() *PdfObjectDictionary { p := this.pageDict p.Clear() @@ -547,7 +547,7 @@ func (this *PdfPage) AddImageResource(name PdfObjectName, ximg *XObjectImage) er return nil } -// Check if has XObject resource by name. +// HasXObjectByName checks if has XObject resource by name. func (this *PdfPage) HasXObjectByName(name PdfObjectName) bool { xresDict, has := this.Resources.XObject.(*PdfObjectDictionary) if !has { @@ -561,7 +561,7 @@ func (this *PdfPage) HasXObjectByName(name PdfObjectName) bool { } } -// Get XObject by name. +// GetXObjectByName get XObject by name. func (this *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { xresDict, has := this.Resources.XObject.(*PdfObjectDictionary) if !has { @@ -575,7 +575,7 @@ func (this *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { } } -// Check if has font resource by name. +// HasFontByName checks if has font resource by name. func (this *PdfPage) HasFontByName(name PdfObjectName) bool { fontDict, has := this.Resources.Font.(*PdfObjectDictionary) if !has { @@ -589,7 +589,7 @@ func (this *PdfPage) HasFontByName(name PdfObjectName) bool { } } -// Check if ExtGState name is available. +// HasExtGState checks if ExtGState name is available. func (this *PdfPage) HasExtGState(name PdfObjectName) bool { if this.Resources == nil { return false @@ -612,7 +612,7 @@ func (this *PdfPage) HasExtGState(name PdfObjectName) bool { return has } -// Add a graphics state to the XObject resources. +// AddExtGState adds a graphics state to the XObject resources. func (this *PdfPage) AddExtGState(name PdfObjectName, egs *PdfObjectDictionary) error { if this.Resources == nil { //this.Resources = &PdfPageResources{} @@ -633,7 +633,7 @@ func (this *PdfPage) AddExtGState(name PdfObjectName, egs *PdfObjectDictionary) return nil } -// Add a font dictionary to the Font resources. +// AddFont adds a font dictionary to the Font resources. func (this *PdfPage) AddFont(name PdfObjectName, font PdfObject) error { if this.Resources == nil { this.Resources = NewPdfPageResources() @@ -661,7 +661,7 @@ type WatermarkImageOptions struct { PreserveAspectRatio bool } -// Add a watermark to the page. +// AddWatermarkImage add a watermark to the page. func (this *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOptions) error { // Page dimensions. bbox, err := this.GetMediaBox() @@ -865,7 +865,7 @@ func (this *PdfPage) GetContentStreams() ([]string, error) { } } -// Get all the content streams for a page as one string. +// GetAllContentStreams gets all the content streams for a page as one string. func (this *PdfPage) GetAllContentStreams() (string, error) { cstreams, err := this.GetContentStreams() if err != nil { diff --git a/pdf/model/pattern.go b/pdf/model/pattern.go index c55ab90e..a9847569 100644 --- a/pdf/model/pattern.go +++ b/pdf/model/pattern.go @@ -30,12 +30,12 @@ func (this *PdfPattern) GetContainingPdfObject() PdfObject { return this.container } -// Context in this case is a reference to the subpattern entry: either PdfTilingPattern or PdfShadingPattern. +// GetContext returns a reference to the subpattern entry: either PdfTilingPattern or PdfShadingPattern. func (this *PdfPattern) GetContext() PdfModel { return this.context } -// Set the sub pattern (context). Either PdfTilingPattern or PdfShadingPattern. +// SetContext sets the sub pattern (context). Either PdfTilingPattern or PdfShadingPattern. func (this *PdfPattern) SetContext(ctx PdfModel) { this.context = ctx } @@ -48,17 +48,17 @@ func (this *PdfPattern) IsShading() bool { return this.PatternType == 2 } -// Check with IsTiling() prior to using this to ensure is a tiling pattern. +// GetAsTilingPattern returns a tiling pattern. Check with IsTiling() prior to using this. func (this *PdfPattern) GetAsTilingPattern() *PdfTilingPattern { return this.context.(*PdfTilingPattern) } -// Check with IsShading() prior to using this, to ensure is a shading pattern. +// GetAsShadingPattern returns a shading pattern. Check with IsShading() prior to using this. func (this *PdfPattern) GetAsShadingPattern() *PdfShadingPattern { return this.context.(*PdfShadingPattern) } -// A Tiling pattern consists of repetitions of a pattern cell with defined intervals. +// PdfTilingPattern is a Tiling pattern that consists of repetitions of a pattern cell with defined intervals. // It is a type 1 pattern. (PatternType = 1). // A tiling pattern is represented by a stream object, where the stream content is // a content stream that describes the pattern cell. @@ -111,7 +111,7 @@ func (this *PdfTilingPattern) GetContentStreamWithEncoder() ([]byte, StreamEncod return decoded, encoder, nil } -// Set the pattern cell's content stream. +// SetContentStream sets the pattern cell's content stream. func (this *PdfTilingPattern) SetContentStream(content []byte, encoder StreamEncoder) error { streamObj, ok := this.container.(*PdfObjectStream) if !ok { @@ -144,8 +144,8 @@ func (this *PdfTilingPattern) SetContentStream(content []byte, encoder StreamEnc return nil } -// Shading patterns provide a smooth transition between colors across an area to be painted, i.e. -// color(x,y) = f(x,y) at each point. +// PdfShadingPattern is a Shading patterns that provide a smooth transition between colors across an area to be painted, +// i.e. color(x,y) = f(x,y) at each point. // It is a type 2 pattern (PatternType = 2). type PdfShadingPattern struct { *PdfPattern diff --git a/pdf/model/resources.go b/pdf/model/resources.go index a0941489..4f936a84 100644 --- a/pdf/model/resources.go +++ b/pdf/model/resources.go @@ -13,7 +13,7 @@ import ( . "github.com/unidoc/unidoc/pdf/core" ) -// Page resources model. +// PdfPageResources is a Page resources model. // Implements PdfModel. type PdfPageResources struct { ExtGState PdfObject @@ -89,8 +89,8 @@ func (r *PdfPageResources) ToPdfObject() PdfObject { return d } -// Add External Graphics State (GState). The gsDict can be specified either directly as a dictionary or an indirect -// object containing a dictionary. +// AddExtGState add External Graphics State (GState). The gsDict can be specified either directly as a dictionary or an +// indirect object containing a dictionary. func (r *PdfPageResources) AddExtGState(gsName PdfObjectName, gsDict PdfObject) error { if r.ExtGState == nil { r.ExtGState = MakeDict() @@ -107,7 +107,7 @@ func (r *PdfPageResources) AddExtGState(gsName PdfObjectName, gsDict PdfObject) return nil } -// Get the ExtGState specified by keyName. Returns a bool indicating whether it was found or not. +// GetExtGState gets the ExtGState specified by keyName. Returns a bool indicating whether it was found or not. func (r *PdfPageResources) GetExtGState(keyName PdfObjectName) (PdfObject, bool) { if r.ExtGState == nil { return nil, false @@ -126,14 +126,14 @@ func (r *PdfPageResources) GetExtGState(keyName PdfObjectName) (PdfObject, bool) } } -// Check whether a font is defined by the specified keyName. +// HasExtGState checks whether a font is defined by the specified keyName. func (r *PdfPageResources) HasExtGState(keyName PdfObjectName) bool { _, has := r.GetFontByName(keyName) return has } -// Get the shading specified by keyName. Returns nil if not existing. The bool flag indicated whether it was found -// or not. +// GetShadingByName gets the shading specified by keyName. Returns nil if not existing. The bool flag indicated whether +// it was found or not. func (r *PdfPageResources) GetShadingByName(keyName PdfObjectName) (*PdfShading, bool) { if r.Shading == nil { return nil, false @@ -157,7 +157,7 @@ func (r *PdfPageResources) GetShadingByName(keyName PdfObjectName) (*PdfShading, } } -// Set a shading resource specified by keyName. +// SetShadingByName sets a shading resource specified by keyName. func (r *PdfPageResources) SetShadingByName(keyName PdfObjectName, shadingObj PdfObject) error { if r.Shading == nil { r.Shading = MakeDict() @@ -172,8 +172,8 @@ func (r *PdfPageResources) SetShadingByName(keyName PdfObjectName, shadingObj Pd return nil } -// Get the pattern specified by keyName. Returns nil if not existing. The bool flag indicated whether it was found -// or not. +// GetPatternByName gets the pattern specified by keyName. Returns nil if not existing. The bool flag indicated whether +// it was found or not. func (r *PdfPageResources) GetPatternByName(keyName PdfObjectName) (*PdfPattern, bool) { if r.Pattern == nil { return nil, false @@ -198,7 +198,7 @@ func (r *PdfPageResources) GetPatternByName(keyName PdfObjectName) (*PdfPattern, } } -// Set a pattern resource specified by keyName. +// SetPatternByName sets a pattern resource specified by keyName. func (r *PdfPageResources) SetPatternByName(keyName PdfObjectName, pattern PdfObject) error { if r.Pattern == nil { r.Pattern = MakeDict() @@ -213,7 +213,7 @@ func (r *PdfPageResources) SetPatternByName(keyName PdfObjectName, pattern PdfOb return nil } -// Get the font specified by keyName. Returns the PdfObject which the entry refers to. +// GetFontByName gets the font specified by keyName. Returns the PdfObject which the entry refers to. // Returns a bool value indicating whether or not the entry was found. func (r *PdfPageResources) GetFontByName(keyName PdfObjectName) (PdfObject, bool) { if r.Font == nil { @@ -233,13 +233,13 @@ func (r *PdfPageResources) GetFontByName(keyName PdfObjectName) (PdfObject, bool } } -// Check whether a font is defined by the specified keyName. +// HasFontByName checks whether a font is defined by the specified keyName. func (r *PdfPageResources) HasFontByName(keyName PdfObjectName) bool { _, has := r.GetFontByName(keyName) return has } -// Set the font specified by keyName to the given object. +// SetFontByName sets the font specified by keyName to the given object. func (r *PdfPageResources) SetFontByName(keyName PdfObjectName, obj PdfObject) error { if r.Font == nil { // Create if not existing. @@ -287,7 +287,7 @@ func (r *PdfPageResources) SetColorspaceByName(keyName PdfObjectName, cs PdfColo return nil } -// Check if an XObject with a specified keyName is defined. +// HasXObjectByName checks if an XObject with a specified keyName is defined. func (r *PdfPageResources) HasXObjectByName(keyName PdfObjectName) bool { obj, _ := r.GetXObjectByName(keyName) if obj != nil { @@ -321,7 +321,7 @@ const ( XObjectTypeUnknown XObjectType = iota ) -// Returns the XObject with the specified keyName and the object type. +// GetXObjectByName returns the XObject with the specified keyName and the object type. func (r *PdfPageResources) GetXObjectByName(keyName PdfObjectName) (*PdfObjectStream, XObjectType) { if r.XObject == nil { return nil, XObjectTypeUndefined diff --git a/pdf/model/shading.go b/pdf/model/shading.go index 3a6d708a..ba71320b 100644 --- a/pdf/model/shading.go +++ b/pdf/model/shading.go @@ -37,12 +37,12 @@ func (this *PdfShading) GetContainingPdfObject() PdfObject { return this.container } -// Context in this case is a reference to the subshading entry as represented by PdfShadingType1-7. +// GetContext returns a reference to the subshading entry as represented by PdfShadingType1-7. func (this *PdfShading) GetContext() PdfModel { return this.context } -// Set the sub annotation (context). +// SetContext set the sub annotation (context). func (this *PdfShading) SetContext(ctx PdfModel) { this.context = ctx } @@ -67,7 +67,7 @@ func (this *PdfShading) getShadingDict() (*PdfObjectDictionary, error) { } } -// Shading type 1: Function-based shading. +// PdfShadingType1 is a Function-based shading. type PdfShadingType1 struct { *PdfShading Domain *PdfObjectArray @@ -75,7 +75,7 @@ type PdfShadingType1 struct { Function []PdfFunction } -// Shading type 2: Axial shading. +// PdfShadingType2 is a Axial shading. type PdfShadingType2 struct { *PdfShading Coords *PdfObjectArray @@ -84,7 +84,7 @@ type PdfShadingType2 struct { Extend *PdfObjectArray } -// Shading type 3: Radial shading. +// PdfShadingType3 is a Radial shading. type PdfShadingType3 struct { *PdfShading Coords *PdfObjectArray @@ -93,7 +93,7 @@ type PdfShadingType3 struct { Extend *PdfObjectArray } -// Shading type 4: Free-form Gouraud-shaded triangle mesh. +// PdfShadingType4 is a Free-form Gouraud-shaded triangle mesh. type PdfShadingType4 struct { *PdfShading BitsPerCoordinate *PdfObjectInteger @@ -103,7 +103,7 @@ type PdfShadingType4 struct { Function []PdfFunction } -// Shading type 5: Lattice-form Gouraud-shaded triangle mesh. +// PdfShadingType5 is a Lattice-form Gouraud-shaded triangle mesh. type PdfShadingType5 struct { *PdfShading BitsPerCoordinate *PdfObjectInteger @@ -113,7 +113,7 @@ type PdfShadingType5 struct { Function []PdfFunction } -// Shading type 6: Coons patch mesh. +// PdfShadingType6 is a Coons patch mesh. type PdfShadingType6 struct { *PdfShading BitsPerCoordinate *PdfObjectInteger @@ -123,7 +123,7 @@ type PdfShadingType6 struct { Function []PdfFunction } -// Shading type 7: Tensor-product patch mesh. +// PdfShadingType7 is a Tensor-product patch mesh. type PdfShadingType7 struct { *PdfShading BitsPerCoordinate *PdfObjectInteger diff --git a/pdf/model/structures.go b/pdf/model/structures.go index 9bac263a..4fdbffe7 100644 --- a/pdf/model/structures.go +++ b/pdf/model/structures.go @@ -17,7 +17,7 @@ import ( . "github.com/unidoc/unidoc/pdf/core" ) -// Definition of a rectangle. +// PdfRectangle is a definition of a rectangle. type PdfRectangle struct { Llx float64 // Lower left corner (ll). Lly float64 @@ -58,7 +58,7 @@ func NewPdfRectangle(arr PdfObjectArray) (*PdfRectangle, error) { return &rect, nil } -// Convert to a PDF object. +// ToPdfObject convert rectangle to a PDF object. func (rect *PdfRectangle) ToPdfObject() PdfObject { arr := MakeArray(MakeFloat(rect.Llx), MakeFloat(rect.Lly), MakeFloat(rect.Urx), MakeFloat(rect.Ury)) return arr @@ -120,7 +120,7 @@ func NewPdfDate(dateStr string) (PdfDate, error) { return d, nil } -// Convert to a PDF string object. +// ToPdfObject converts date to a PDF string object. func (date *PdfDate) ToPdfObject() PdfObject { str := fmt.Sprintf("D:%.4d%.2d%.2d%.2d%.2d%.2d%c%.2d'%.2d'", date.year, date.month, date.day, date.hour, date.minute, date.second, diff --git a/pdf/model/writer.go b/pdf/model/writer.go index 21fce00c..7ff19b5e 100644 --- a/pdf/model/writer.go +++ b/pdf/model/writer.go @@ -250,7 +250,7 @@ func (this *PdfWriter) copyObjects() { } } -// Set the PDF version of the output file. +// SetVersion sets the PDF version of the output file. func (this *PdfWriter) SetVersion(majorVersion, minorVersion int) { this.majorVersion = majorVersion this.minorVersion = minorVersion diff --git a/pdf/model/xobject.go b/pdf/model/xobject.go index e0143320..8e96d820 100644 --- a/pdf/model/xobject.go +++ b/pdf/model/xobject.go @@ -37,7 +37,7 @@ type XObjectForm struct { primitive *PdfObjectStream } -// Create a brand new XObject Form. Creates a new underlying PDF object stream primitive. +// NewXObjectForm creates a brand new XObject Form. Creates a new underlying PDF object stream primitive. func NewXObjectForm() *XObjectForm { xobj := &XObjectForm{} stream := &PdfObjectStream{} @@ -46,8 +46,8 @@ func NewXObjectForm() *XObjectForm { return xobj } -// Build the Form XObject from a stream object. -// XXX: Should this be exposed? Consider different access points. +// NewXObjectFormFromStream builds the Form XObject from a stream object. +// TODO: Should this be exposed? Consider different access points. func NewXObjectFormFromStream(stream *PdfObjectStream) (*XObjectForm, error) { form := &XObjectForm{} form.primitive = stream @@ -127,8 +127,8 @@ func (xform *XObjectForm) GetContentStream() ([]byte, error) { return decoded, nil } -// Update the content stream with specified encoding. If encoding is null, will use the xform.Filter object -// or Raw encoding if not set. +// SetContentStream updates the content stream with specified encoding. If encoding is null, will use the xform.Filter +// object or Raw encoding if not set. func (xform *XObjectForm) SetContentStream(content []byte, encoder StreamEncoder) error { encoded := content @@ -152,7 +152,7 @@ func (xform *XObjectForm) SetContentStream(content []byte, encoder StreamEncoder return nil } -// Return a stream object. +// ToPdfObject return a stream object. func (xform *XObjectForm) ToPdfObject() PdfObject { stream := xform.primitive @@ -226,7 +226,7 @@ func NewXObjectImage() *XObjectImage { return xobj } -// Creates a new XObject Image from an image object with default options. +// NewXObjectImageFromImage creates a new XObject Image from an image object with default options. // If encoder is nil, uses raw encoding (none). func NewXObjectImageFromImage(img *Image, cs PdfColorspace, encoder StreamEncoder) (*XObjectImage, error) { xobj := NewXObjectImage() @@ -367,7 +367,7 @@ func toGray(matte *PdfObjectArray) (float64, error) { return 0.0, err } -// Build the image xobject from a stream object. +// NewXObjectImageFromStream build the image xobject from a stream object. // An image dictionary is the dictionary portion of a stream object representing an image XObject. func NewXObjectImageFromStream(stream *PdfObjectStream) (*XObjectImage, error) { img := &XObjectImage{} @@ -445,7 +445,7 @@ func NewXObjectImageFromStream(stream *PdfObjectStream) (*XObjectImage, error) { return img, nil } -// Update XObject Image with new image data. +// SetImage update XObject Image with new image data. func (ximg *XObjectImage) SetImage(img *Image, cs PdfColorspace) error { encoded, err := ximg.Filter.EncodeBytes(img.Data) if err != nil { @@ -477,7 +477,7 @@ func (ximg *XObjectImage) SetImage(img *Image, cs PdfColorspace) error { return nil } -// Set compression filter. Decodes with current filter sets and encodes the data with the new filter. +// SetFilter sets compression filter. Decodes with current filter sets and encodes the data with the new filter. func (ximg *XObjectImage) SetFilter(encoder StreamEncoder) error { encoded := ximg.Stream decoded, err := ximg.Filter.DecodeBytes(encoded) @@ -495,7 +495,7 @@ func (ximg *XObjectImage) SetFilter(encoder StreamEncoder) error { return nil } -// This will convert to an Image which can be transformed or saved out. +// ToImage converts an object to an Image which can be transformed or saved out. // The image data is decoded and the Image returned. func (ximg *XObjectImage) ToImage() (*Image, error) { image := &Image{} @@ -543,7 +543,7 @@ func (ximg *XObjectImage) GetContainingPdfObject() PdfObject { return ximg.primitive } -// Return a stream object. +// ToPdfObject return a stream object. func (ximg *XObjectImage) ToPdfObject() PdfObject { stream := ximg.primitive From 9f0df8945d55b81a96e0da4a6e9d7086911403c5 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 21:37:27 +0200 Subject: [PATCH 5/7] don't use XXX for TODOs --- pdf/contentstream/encoding.go | 2 +- pdf/contentstream/inline-image.go | 2 +- pdf/core/crypt.go | 2 +- pdf/core/encoding.go | 4 ++-- pdf/creator/block.go | 4 ++-- pdf/creator/creator_test.go | 2 +- pdf/creator/image.go | 2 +- pdf/creator/paragraph.go | 16 ++++++++-------- pdf/creator/styled_paragraph.go | 18 +++++++++--------- pdf/creator/table.go | 2 +- pdf/extractor/text.go | 2 +- pdf/internal/textencoding/glyphs_glyphlist.go | 16 ++++++++-------- pdf/model/font.go | 2 +- pdf/model/fontfile.go | 4 ++-- pdf/model/fonts/ttfparser.go | 4 ++-- pdf/model/functions_test.go | 4 ++-- pdf/model/image.go | 2 +- pdf/model/outlines.go | 4 ++-- pdf/model/page.go | 2 +- pdf/model/reader.go | 2 +- pdf/model/signature.go | 2 +- pdf/model/writer.go | 2 +- pdf/ps/parser.go | 2 +- 23 files changed, 51 insertions(+), 51 deletions(-) diff --git a/pdf/contentstream/encoding.go b/pdf/contentstream/encoding.go index 7de12745..e2bea7b6 100644 --- a/pdf/contentstream/encoding.go +++ b/pdf/contentstream/encoding.go @@ -360,7 +360,7 @@ func newMultiEncoderFromInlineImage(inlineImage *ContentStreamInlineImage) (*cor } if *name == core.StreamEncodingFilterNameFlate || *name == "Fl" { - // XXX: need to separate out the DecodeParms.. + // TODO: need to separate out the DecodeParms.. encoder, err := newFlateEncoderFromInlineImage(inlineImage, dParams) if err != nil { return nil, err diff --git a/pdf/contentstream/inline-image.go b/pdf/contentstream/inline-image.go index 47d4d6b2..a38487c7 100644 --- a/pdf/contentstream/inline-image.go +++ b/pdf/contentstream/inline-image.go @@ -63,7 +63,7 @@ func NewInlineImageFromImage(img model.Image, encoder core.StreamEncoder) (*Cont if filterName != core.StreamEncodingFilterNameRaw { inlineImage.Filter = core.MakeName(filterName) } - // XXX/FIXME: Add decode params? + // FIXME: Add decode params? return &inlineImage, nil } diff --git a/pdf/core/crypt.go b/pdf/core/crypt.go index 3402d4b0..2e255915 100644 --- a/pdf/core/crypt.go +++ b/pdf/core/crypt.go @@ -315,7 +315,7 @@ func (crypt *PdfCrypt) loadCryptFilters(ed *PdfObjectDictionary) error { crypt.cryptFilters = cryptFilters{} obj := ed.Get("CF") - obj = TraceToDirectObject(obj) // XXX may need to resolve reference... + obj = TraceToDirectObject(obj) // TODO: may need to resolve reference... if ref, isRef := obj.(*PdfObjectReference); isRef { o, err := crypt.parser.LookupByReference(*ref) if err != nil { diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index 151c19e6..eea359c7 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -974,7 +974,7 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { // indicates that either the jpeg package is converting the raw // data into YCbCr with some kind of mapping, or that the original // data is not in R,G,B... - // XXX: This is not good as it means we end up with R, G, B... even + // TODO: This is not good as it means we end up with R, G, B... even // if the original colormap was different. Unless calling the RGBA() // call exactly reverses the previous conversion to YCbCr (even if // real data is not rgb)... ? @@ -1716,7 +1716,7 @@ func newMultiEncoderFromStream(streamObj *PdfObjectStream) (*MultiEncoder, error common.Log.Trace("Next name: %s, dp: %v, dParams: %v", *name, dp, dParams) if *name == StreamEncodingFilterNameFlate { - // XXX: need to separate out the DecodeParms.. + // TODO: need to separate out the DecodeParms.. encoder, err := newFlateEncoderFromStream(streamObj, dParams) if err != nil { return nil, err diff --git a/pdf/creator/block.go b/pdf/creator/block.go index 65b5d5d0..bb49986d 100644 --- a/pdf/creator/block.go +++ b/pdf/creator/block.go @@ -135,7 +135,7 @@ func (blk *Block) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, er cc.Translate(ctx.X, ctx.PageHeight-ctx.Y-blk.height) if blk.angle != 0 { // Make the rotation about the upper left corner. - // XXX/TODO: Account for rotation origin. (Consider). + // TODO: Account for rotation origin. (Consider). cc.Translate(0, blk.Height()) cc.RotateDeg(blk.angle) cc.Translate(0, -blk.Height()) @@ -154,7 +154,7 @@ func (blk *Block) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, er cc.Translate(blk.xPos, ctx.PageHeight-blk.yPos-blk.height) if blk.angle != 0 { // Make the rotation about the upper left corner. - // XXX/TODO: Consider supporting specification of rotation origin. + // TODO: Consider supporting specification of rotation origin. cc.Translate(0, blk.Height()) cc.RotateDeg(blk.angle) cc.Translate(0, -blk.Height()) diff --git a/pdf/creator/creator_test.go b/pdf/creator/creator_test.go index 0bd42e6f..aa0b368f 100644 --- a/pdf/creator/creator_test.go +++ b/pdf/creator/creator_test.go @@ -44,7 +44,7 @@ const testRobotoRegularTTFFile = "./testdata/roboto/Roboto-Regular.ttf" const testRobotoBoldTTFFile = "./testdata/roboto/Roboto-Bold.ttf" const testWts11TTFFile = "./testdata/wts11.ttf" -// XXX(peterwilliams97): /tmp/2_p_multi.pdf which is created in this test gives an error message +// TODO(peterwilliams97): /tmp/2_p_multi.pdf which is created in this test gives an error message // when opened in Adobe Reader: The font FreeSans contains bad Widths. // This problem did not occur when I replaced FreeSans.ttf with LiberationSans-Regular.ttf const testFreeSansTTFFile = "./testdata/FreeSans.ttf" diff --git a/pdf/creator/image.go b/pdf/creator/image.go index 1ec898af..7bcde067 100644 --- a/pdf/creator/image.go +++ b/pdf/creator/image.go @@ -212,7 +212,7 @@ func (img *Image) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, er // Absolute drawing should not affect context. ctx = origCtx } else { - // XXX/TODO: Use projected height. + // TODO: Use projected height. ctx.Y += img.margins.bottom ctx.Height -= img.margins.bottom } diff --git a/pdf/creator/paragraph.go b/pdf/creator/paragraph.go index fe2f18ce..f953901b 100644 --- a/pdf/creator/paragraph.go +++ b/pdf/creator/paragraph.go @@ -217,7 +217,7 @@ func (p *Paragraph) getTextWidth() float64 { glyph, found := p.textFont.Encoder().RuneToGlyph(r) if !found { common.Log.Debug("ERROR: Glyph not found for rune: 0x%04x=%c", r, r) - return -1 // XXX/FIXME: return error. + return -1 // FIXME: return error. } // Ignore newline for this.. Handles as if all in one line. @@ -228,7 +228,7 @@ func (p *Paragraph) getTextWidth() float64 { metrics, found := p.textFont.GetGlyphCharMetrics(glyph) if !found { common.Log.Debug("ERROR: Glyph char metrics not found! %q (rune 0x%04x=%c)", glyph, r, r) - return -1 // XXX/FIXME: return error. + return -1 // FIXME: return error. } w += p.fontSize * metrics.Wx } @@ -243,7 +243,7 @@ func (p *Paragraph) getTextLineWidth(line string) float64 { glyph, found := p.textFont.Encoder().RuneToGlyph(r) if !found { common.Log.Debug("ERROR: Glyph not found for rune: 0x%04x=%c", r, r) - return -1 // XXX/FIXME: return error. + return -1 // FIXME: return error. } // Ignore newline for this.. Handles as if all in one line. @@ -254,7 +254,7 @@ func (p *Paragraph) getTextLineWidth(line string) float64 { metrics, found := p.textFont.GetGlyphCharMetrics(glyph) if !found { common.Log.Debug("ERROR: Glyph char metrics not found! %q (rune 0x%04x=%c)", glyph, r, r) - return -1 // XXX/FIXME: return error. + return -1 // FIXME: return error. } width += p.fontSize * metrics.Wx @@ -281,7 +281,7 @@ func (p *Paragraph) getMaxLineWidth() float64 { } // Simple algorithm to wrap the text into lines (greedy algorithm - fill the lines). -// XXX/TODO: Consider the Knuth/Plass algorithm or an alternative. +// TODO: Consider the Knuth/Plass algorithm or an alternative. func (p *Paragraph) wrapText() error { if !p.enableWrap || int(p.wrapWidth) <= 0 { p.textLines = []string{p.text} @@ -331,7 +331,7 @@ func (p *Paragraph) wrapText() error { // Breaks on the character. idx := -1 for i := len(glyphs) - 1; i >= 0; i-- { - if glyphs[i] == "space" { // XXX: What about other space glyphs like controlHT? + if glyphs[i] == "space" { // TODO: What about other space glyphs like controlHT? idx = i break } @@ -396,7 +396,7 @@ func (p *Paragraph) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawContext, if p.Height() > ctx.Height { // Goes out of the bounds. Write on a new template instead and create a new context at // upper left corner. - // XXX/TODO: Handle case when Paragraph is larger than the Page... + // TODO: Handle case when Paragraph is larger than the Page... // Should be fine if we just break on the paragraph, i.e. splitting it up over 2+ pages blocks = append(blocks, blk) @@ -541,7 +541,7 @@ func drawParagraphOnBlock(blk *Block, p *Paragraph, ctx DrawContext) (DrawContex return ctx, errors.New("Unsupported rune in text encoding") } - if glyph == "space" { // XXX: What about \t and other spaces. + if glyph == "space" { // TODO: What about \t and other spaces. if len(encoded) > 0 { objs = append(objs, core.MakeStringFromBytes(encoded)) encoded = []byte{} diff --git a/pdf/creator/styled_paragraph.go b/pdf/creator/styled_paragraph.go index da953da5..cf2c43d1 100644 --- a/pdf/creator/styled_paragraph.go +++ b/pdf/creator/styled_paragraph.go @@ -238,7 +238,7 @@ func (p *StyledParagraph) getTextWidth() float64 { if !found { common.Log.Debug("Error! Glyph not found for rune: %s\n", rune) - // XXX/FIXME: return error. + // FIXME: return error. return -1 } @@ -251,7 +251,7 @@ func (p *StyledParagraph) getTextWidth() float64 { if !found { common.Log.Debug("Glyph char metrics not found! %s\n", glyph) - // XXX/FIXME: return error. + // FIXME: return error. return -1 } @@ -273,7 +273,7 @@ func (p *StyledParagraph) getTextLineWidth(line []*TextChunk) float64 { if !found { common.Log.Debug("Error! Glyph not found for rune: %s\n", r) - // XXX/FIXME: return error. + // FIXME: return error. return -1 } @@ -286,7 +286,7 @@ func (p *StyledParagraph) getTextLineWidth(line []*TextChunk) float64 { if !found { common.Log.Debug("Glyph char metrics not found! %s\n", glyph) - // XXX/FIXME: return error. + // FIXME: return error. return -1 } @@ -329,7 +329,7 @@ func (p *StyledParagraph) getTextHeight() float64 { // wrapText splits text into lines. It uses a simple greedy algorithm to wrap // fill the lines. -// XXX/TODO: Consider the Knuth/Plass algorithm or an alternative. +// TODO: Consider the Knuth/Plass algorithm or an alternative. func (p *StyledParagraph) wrapText() error { if !p.enableWrap || int(p.wrapWidth) <= 0 { p.lines = [][]*TextChunk{p.chunks} @@ -362,7 +362,7 @@ func (p *StyledParagraph) wrapText() error { if !found { common.Log.Debug("Error! Glyph not found for rune: %v\n", r) - // XXX/FIXME: return error. + // FIXME: return error. return errors.New("Glyph not found for rune") } @@ -388,7 +388,7 @@ func (p *StyledParagraph) wrapText() error { if !found { common.Log.Debug("Glyph char metrics not found! %s\n", glyph) - // XXX/FIXME: return error. + // FIXME: return error. return errors.New("Glyph char metrics missing") } @@ -396,7 +396,7 @@ func (p *StyledParagraph) wrapText() error { if lineWidth+w > p.wrapWidth*1000.0 { // Goes out of bounds: Wrap. // Breaks on the character. - // XXX/TODO: when goes outside: back up to next space, + // TODO: when goes outside: back up to next space, // otherwise break on the character. idx := -1 for j := len(glyphs) - 1; j >= 0; j-- { @@ -479,7 +479,7 @@ func (p *StyledParagraph) GeneratePageBlocks(ctx DrawContext) ([]*Block, DrawCon if p.Height() > ctx.Height { // Goes out of the bounds. Write on a new template instead and create a new context at upper // left corner. - // XXX/TODO: Handle case when Paragraph is larger than the Page... + // TODO: Handle case when Paragraph is larger than the Page... // Should be fine if we just break on the paragraph, i.e. splitting it up over 2+ pages blocks = append(blocks, blk) diff --git a/pdf/creator/table.go b/pdf/creator/table.go index 238d491c..a494f883 100644 --- a/pdf/creator/table.go +++ b/pdf/creator/table.go @@ -65,7 +65,7 @@ func newTable(cols int) *Table { t.rowHeights = []float64{} // Default row height - // XXX/TODO: Base on contents instead? + // TODO: Base on contents instead? t.defaultRowHeight = 10.0 t.cells = []*TableCell{} diff --git a/pdf/extractor/text.go b/pdf/extractor/text.go index 28b18ca6..ab2c0984 100644 --- a/pdf/extractor/text.go +++ b/pdf/extractor/text.go @@ -380,7 +380,7 @@ func (to *textObject) setFont(name string, size float64) error { (*to.fontStack)[len(*to.fontStack)-1] = font } } else if err == model.ErrFontNotSupported { - // XXX: Do we need to handle this case in a special way? + // TODO: Do we need to handle this case in a special way? return err } else { return err diff --git a/pdf/internal/textencoding/glyphs_glyphlist.go b/pdf/internal/textencoding/glyphs_glyphlist.go index fdffb21d..8276f792 100644 --- a/pdf/internal/textencoding/glyphs_glyphlist.go +++ b/pdf/internal/textencoding/glyphs_glyphlist.go @@ -21,14 +21,14 @@ import ( const MissingCodeRune = '\ufffd' // � // GlyphToRune returns the rune corresponding to glyph `glyph` if there is one. -// XXX: TODO: Can we return a string here? e.g. When we are extracting text, we want to get "ffi" -// rather than 'ffi'. We only need a glyph ➞ rune map when we need to convert back to -// glyphs. -// We are currently applying RuneToString to the output of functions that call -// GlyphToRune. While this gives the same result, it makes the calling code complex and -// fragile. -// XXX: TODO: Can we combine all the tables glyphAliases, glyphlistGlyphToRuneMap, -// texGlyphlistGlyphToStringMap, additionalGlyphlistGlyphToRuneMap and ".notdef"? +// TODO: Can we return a string here? e.g. When we are extracting text, we want to get "ffi" +// rather than 'ffi'. We only need a glyph ➞ rune map when we need to convert back to +// glyphs. +// We are currently applying RuneToString to the output of functions that call +// GlyphToRune. While this gives the same result, it makes the calling code complex and +// fragile. +// TODO: Can we combine all the tables glyphAliases, glyphlistGlyphToRuneMap, +// texGlyphlistGlyphToStringMap, additionalGlyphlistGlyphToRuneMap and ".notdef"? func GlyphToRune(glyph GlyphName) (rune, bool) { // We treat glyph "eight.lf" the same as glyph "eight". // See contrib/testdata/font/Ingmar.txt diff --git a/pdf/model/font.go b/pdf/model/font.go index 94bcc938..b92a156c 100644 --- a/pdf/model/font.go +++ b/pdf/model/font.go @@ -374,7 +374,7 @@ func (font PdfFont) Encoder() textencoding.TextEncoder { t := font.actualFont() if t == nil { common.Log.Debug("ERROR: Encoder not implemented for font type=%#T", font.context) - // XXX: Should we return a default encoding? + // TODO: Should we return a default encoding? return nil } return t.Encoder() diff --git a/pdf/model/fontfile.go b/pdf/model/fontfile.go index 0a22de4c..30de1c12 100644 --- a/pdf/model/fontfile.go +++ b/pdf/model/fontfile.go @@ -68,7 +68,7 @@ func newFontFileFromPdfObject(obj core.PdfObject) (*fontFile, error) { if !ok { fontfile.subtype = subtype if subtype == "Type1C" { - // XXX: TODO Add Type1C support + // TODO: Add Type1C support common.Log.Debug("Type1C fonts are currently not supported") return nil, ErrType1CFontNotSupported } @@ -153,7 +153,7 @@ func (fontfile *fontFile) parseAsciiPart(data []byte) error { } encoder, err := textencoding.NewCustomSimpleTextEncoder(encodings, nil) if err != nil { - // XXX: Logging an error because we need to fix all these misses. + // TODO: Logging an error because we need to fix all these misses. common.Log.Error("UNKNOWN GLYPH: err=%v", err) return nil } diff --git a/pdf/model/fonts/ttfparser.go b/pdf/model/fonts/ttfparser.go index 303348ca..de1eb574 100644 --- a/pdf/model/fonts/ttfparser.go +++ b/pdf/model/fonts/ttfparser.go @@ -99,7 +99,7 @@ type TtfType struct { } // MakeToUnicode returns a ToUnicode CMap based on the encoding of `ttf`. -// XXX(peterwilliams97): This currently gives a bad text mapping for creator_test.go but leads to an +// TODO(peterwilliams97): This currently gives a bad text mapping for creator_test.go but leads to an // otherwise valid PDF file that Adobe Reader displays without error. func (ttf *TtfType) MakeToUnicode() *cmap.CMap { codeToUnicode := make(map[cmap.CharCode]rune) @@ -504,7 +504,7 @@ func (t *ttfParser) parseCmapVersion(offset int64) error { return t.parseCmapFormat12() default: common.Log.Debug("ERROR: Unsupported cmap format=%d", format) - return nil // XXX(peterwilliams97): Can't return an error here if creator_test.go is to pass. + return nil // TODO(peterwilliams97): Can't return an error here if creator_test.go is to pass. } } diff --git a/pdf/model/functions_test.go b/pdf/model/functions_test.go index 73b4a60c..f636674d 100644 --- a/pdf/model/functions_test.go +++ b/pdf/model/functions_test.go @@ -1,5 +1,5 @@ // Test functions -// XXX: We need tests of type 0, type 2, type 3, type 4 functions. Particularly type 0 is complex and +// TODO: We need tests of type 0, type 2, type 3, type 4 functions. Particularly type 0 is complex and // needs comprehensive tests. package model @@ -23,7 +23,7 @@ type Type4TestCase struct { Expected []float64 } -// TODO/XXX: Implement example 2 from page 167. +// TODO: Implement example 2 from page 167. func TestType4Function1(t *testing.T) { rawText := ` diff --git a/pdf/model/image.go b/pdf/model/image.go index 0d5ba0ed..fdc638aa 100644 --- a/pdf/model/image.go +++ b/pdf/model/image.go @@ -150,7 +150,7 @@ func (img *Image) ToGoImage() (goimage.Image, error) { } else if img.ColorComponents == 4 { imgout = goimage.NewCMYK(bounds) } else { - // XXX? Force RGB convert? + // TODO: Force RGB convert? common.Log.Debug("Unsupported number of colors components per sample: %d", img.ColorComponents) return nil, errors.New("Unsupported colors") } diff --git a/pdf/model/outlines.go b/pdf/model/outlines.go index 0deb28cb..95ac108c 100644 --- a/pdf/model/outlines.go +++ b/pdf/model/outlines.go @@ -182,7 +182,7 @@ func (this *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirec } } if obj := dict.Get("SE"); obj != nil { - // XXX: To add structure element support. + // TODO: To add structure element support. // Currently not supporting structure elements. item.SE = nil /* @@ -270,7 +270,7 @@ func (this *PdfOutlineItem) ToPdfObject() PdfObject { dict.Set("A", this.A) } if obj := dict.Get("SE"); obj != nil { - // XXX: Currently not supporting structure element hierarchy. + // TODO: Currently not supporting structure element hierarchy. // Remove it. dict.Remove("SE") // delete(*dict, "SE") diff --git a/pdf/model/page.go b/pdf/model/page.go index d73526bb..bbcee163 100644 --- a/pdf/model/page.go +++ b/pdf/model/page.go @@ -90,7 +90,7 @@ func (this *PdfPage) Duplicate() *PdfPage { // Note that a new container is created (indirect object). func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, error) { page := NewPdfPage() - page.pageDict = p //XXX? + page.pageDict = p // TODO d := *p diff --git a/pdf/model/reader.go b/pdf/model/reader.go index 008ac12a..ba87bfe4 100755 --- a/pdf/model/reader.go +++ b/pdf/model/reader.go @@ -695,7 +695,7 @@ func (this *PdfReader) GetPageAsIndirectObject(pageNumber int) (PdfObject, error page := this.pageList[pageNumber-1] // Look up all references related to page and load everything. - // XXX/TODO: Use of traverse object data will be limited when lazy-loading is supported. + // TODO: Use of traverse object data will be limited when lazy-loading is supported. err := this.traverseObjectData(page) if err != nil { return nil, err diff --git a/pdf/model/signature.go b/pdf/model/signature.go index 35afc4fb..55972db5 100644 --- a/pdf/model/signature.go +++ b/pdf/model/signature.go @@ -91,7 +91,7 @@ func (sig *PdfSignature) ToPdfObject() core.PdfObject { dict.Set("ContactInfo", sig.ContactInfo) } - // XXX/FIXME: ByteRange and Contents need to be updated dynamically. + // FIXME: ByteRange and Contents need to be updated dynamically. return container } diff --git a/pdf/model/writer.go b/pdf/model/writer.go index 7ff19b5e..3c9be2ee 100644 --- a/pdf/model/writer.go +++ b/pdf/model/writer.go @@ -574,7 +574,7 @@ func (this *PdfWriter) writeObject(num int, obj PdfObject) { return } - // XXX/TODO: Add a default encoder if Filter not specified? + // TODO: Add a default encoder if Filter not specified? // Still need to make sure is encrypted. if pobj, isStream := obj.(*PdfObjectStream); isStream { this.crossReferenceMap[num] = crossReference{Type: 1, Offset: this.writePos, Generation: pobj.GenerationNumber} diff --git a/pdf/ps/parser.go b/pdf/ps/parser.go index afbf1e46..e865c8ab 100644 --- a/pdf/ps/parser.go +++ b/pdf/ps/parser.go @@ -175,7 +175,7 @@ func (p *PSParser) parseNumber() (PSObject, error) { isFloat = true } else if bb[0] == 'e' { // Exponential number format. - // XXX Is this supported in PS? + // TODO: Is this supported in PS? b, _ := p.reader.ReadByte() numStr += string(b) isFloat = true From 0a8b46daff3008be9736a2a90a23cc6663ef6344 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sun, 9 Dec 2018 21:25:30 +0200 Subject: [PATCH 6/7] don't use generic receiver names; make sure receiver name is consistent --- common/license/key.go | 58 +-- common/logging.go | 50 +- pdf/contentstream/draw/bezier_curve.go | 22 +- pdf/contentstream/draw/path.go | 46 +- pdf/contentstream/draw/point.go | 13 +- pdf/contentstream/draw/vector.go | 32 +- pdf/contentstream/processor.go | 8 +- pdf/core/encoding.go | 362 +++++++------- pdf/model/colorspace.go | 642 ++++++++++++------------- pdf/model/flatten.go | 10 +- pdf/model/font.go | 142 +++--- pdf/model/fonts/ttfparser.go | 12 +- pdf/model/functions.go | 166 +++---- pdf/model/outlines.go | 108 ++--- pdf/model/page.go | 292 +++++------ pdf/model/pattern.go | 120 ++--- pdf/model/reader.go | 200 ++++---- pdf/model/shading.go | 250 +++++----- pdf/model/writer.go | 279 ++++++----- 19 files changed, 1403 insertions(+), 1409 deletions(-) diff --git a/common/license/key.go b/common/license/key.go index aef42833..d0738a03 100644 --- a/common/license/key.go +++ b/common/license/key.go @@ -40,92 +40,92 @@ type LicenseKey struct { CreatorEmail string `json:"creator_email"` } -func (this *LicenseKey) isExpired() bool { - if this.ExpiresAt == nil { +func (k *LicenseKey) isExpired() bool { + if k.ExpiresAt == nil { return false } - if this.CreatedAt.Before(startCheckingExpiry) { + if k.CreatedAt.Before(startCheckingExpiry) { return false } utcNow := time.Now().UTC() - return utcNow.After(*this.ExpiresAt) + return utcNow.After(*k.ExpiresAt) } -func (this *LicenseKey) Validate() error { - if len(this.LicenseId) < 10 { +func (k *LicenseKey) Validate() error { + if len(k.LicenseId) < 10 { return fmt.Errorf("Invalid license: License Id") } - if len(this.CustomerId) < 10 { + if len(k.CustomerId) < 10 { return fmt.Errorf("Invalid license: Customer Id") } - if len(this.CustomerName) < 1 { + if len(k.CustomerName) < 1 { return fmt.Errorf("Invalid license: Customer Name") } - if testTime.After(this.CreatedAt) { + if testTime.After(k.CreatedAt) { return fmt.Errorf("Invalid license: Created At is invalid") } - if this.ExpiresAt != nil { - if this.CreatedAt.After(*this.ExpiresAt) { + if k.ExpiresAt != nil { + if k.CreatedAt.After(*k.ExpiresAt) { return fmt.Errorf("Invalid license: Created At cannot be Greater than Expires At") } } - if this.isExpired() { + if k.isExpired() { return fmt.Errorf("Invalid license: The license has already expired") } - if len(this.CreatorName) < 1 { + if len(k.CreatorName) < 1 { return fmt.Errorf("Invalid license: Creator name") } - if len(this.CreatorEmail) < 1 { + if len(k.CreatorEmail) < 1 { return fmt.Errorf("Invalid license: Creator email") } return nil } -func (this *LicenseKey) TypeToString() string { - if this.Tier == LicenseTierUnlicensed { +func (k *LicenseKey) TypeToString() string { + if k.Tier == LicenseTierUnlicensed { return "Unlicensed" } - if this.Tier == LicenseTierCommunity { + if k.Tier == LicenseTierCommunity { return "AGPLv3 Open Source Community License" } - if this.Tier == LicenseTierIndividual || this.Tier == "indie" { + if k.Tier == LicenseTierIndividual || k.Tier == "indie" { return "Commercial License - Individual" } return "Commercial License - Business" } -func (this *LicenseKey) ToString() string { - str := fmt.Sprintf("License Id: %s\n", this.LicenseId) - str += fmt.Sprintf("Customer Id: %s\n", this.CustomerId) - str += fmt.Sprintf("Customer Name: %s\n", this.CustomerName) - str += fmt.Sprintf("Tier: %s\n", this.Tier) - str += fmt.Sprintf("Created At: %s\n", common.UtcTimeFormat(this.CreatedAt)) +func (k *LicenseKey) ToString() string { + str := fmt.Sprintf("License Id: %s\n", k.LicenseId) + str += fmt.Sprintf("Customer Id: %s\n", k.CustomerId) + str += fmt.Sprintf("Customer Name: %s\n", k.CustomerName) + str += fmt.Sprintf("Tier: %s\n", k.Tier) + str += fmt.Sprintf("Created At: %s\n", common.UtcTimeFormat(k.CreatedAt)) - if this.ExpiresAt == nil { + if k.ExpiresAt == nil { str += fmt.Sprintf("Expires At: Never\n") } else { - str += fmt.Sprintf("Expires At: %s\n", common.UtcTimeFormat(*this.ExpiresAt)) + str += fmt.Sprintf("Expires At: %s\n", common.UtcTimeFormat(*k.ExpiresAt)) } - str += fmt.Sprintf("Creator: %s <%s>\n", this.CreatorName, this.CreatorEmail) + str += fmt.Sprintf("Creator: %s <%s>\n", k.CreatorName, k.CreatorEmail) return str } -func (lk *LicenseKey) IsLicensed() bool { - return lk.Tier != LicenseTierUnlicensed +func (k *LicenseKey) IsLicensed() bool { + return k.Tier != LicenseTierUnlicensed } func MakeUnlicensedKey() *LicenseKey { diff --git a/common/logging.go b/common/logging.go index 87dc3efc..1a8eaef8 100644 --- a/common/logging.go +++ b/common/logging.go @@ -24,22 +24,22 @@ type Logger interface { // DummyLogger does nothing. type DummyLogger struct{} -func (this DummyLogger) Error(format string, args ...interface{}) { +func (DummyLogger) Error(format string, args ...interface{}) { } -func (this DummyLogger) Warning(format string, args ...interface{}) { +func (DummyLogger) Warning(format string, args ...interface{}) { } -func (this DummyLogger) Notice(format string, args ...interface{}) { +func (DummyLogger) Notice(format string, args ...interface{}) { } -func (this DummyLogger) Info(format string, args ...interface{}) { +func (DummyLogger) Info(format string, args ...interface{}) { } -func (this DummyLogger) Debug(format string, args ...interface{}) { +func (DummyLogger) Debug(format string, args ...interface{}) { } -func (this DummyLogger) Trace(format string, args ...interface{}) { +func (DummyLogger) Trace(format string, args ...interface{}) { } // LogLevel is the verbosity level for logging. @@ -64,45 +64,45 @@ func NewConsoleLogger(logLevel LogLevel) *ConsoleLogger { return &logger } -func (this ConsoleLogger) Error(format string, args ...interface{}) { - if this.LogLevel >= LogLevelError { +func (l ConsoleLogger) Error(format string, args ...interface{}) { + if l.LogLevel >= LogLevelError { prefix := "[ERROR] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } -func (this ConsoleLogger) Warning(format string, args ...interface{}) { - if this.LogLevel >= LogLevelWarning { +func (l ConsoleLogger) Warning(format string, args ...interface{}) { + if l.LogLevel >= LogLevelWarning { prefix := "[WARNING] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } -func (this ConsoleLogger) Notice(format string, args ...interface{}) { - if this.LogLevel >= LogLevelNotice { +func (l ConsoleLogger) Notice(format string, args ...interface{}) { + if l.LogLevel >= LogLevelNotice { prefix := "[NOTICE] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } -func (this ConsoleLogger) Info(format string, args ...interface{}) { - if this.LogLevel >= LogLevelInfo { +func (l ConsoleLogger) Info(format string, args ...interface{}) { + if l.LogLevel >= LogLevelInfo { prefix := "[INFO] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } -func (this ConsoleLogger) Debug(format string, args ...interface{}) { - if this.LogLevel >= LogLevelDebug { +func (l ConsoleLogger) Debug(format string, args ...interface{}) { + if l.LogLevel >= LogLevelDebug { prefix := "[DEBUG] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } -func (this ConsoleLogger) Trace(format string, args ...interface{}) { - if this.LogLevel >= LogLevelTrace { +func (l ConsoleLogger) Trace(format string, args ...interface{}) { + if l.LogLevel >= LogLevelTrace { prefix := "[TRACE] " - this.output(os.Stdout, prefix, format, args...) + l.output(os.Stdout, prefix, format, args...) } } @@ -113,7 +113,7 @@ func SetLogger(logger Logger) { } // output writes `format`, `args` log message prefixed by the source file name, line and `prefix` -func (this ConsoleLogger) output(f *os.File, prefix string, format string, args ...interface{}) { +func (l ConsoleLogger) output(f *os.File, prefix string, format string, args ...interface{}) { _, file, line, ok := runtime.Caller(2) if !ok { file = "???" diff --git a/pdf/contentstream/draw/bezier_curve.go b/pdf/contentstream/draw/bezier_curve.go index b319bc4c..e06cfe94 100644 --- a/pdf/contentstream/draw/bezier_curve.go +++ b/pdf/contentstream/draw/bezier_curve.go @@ -94,35 +94,35 @@ func NewCubicBezierPath() CubicBezierPath { return bpath } -func (this CubicBezierPath) AppendCurve(curve CubicBezierCurve) CubicBezierPath { - this.Curves = append(this.Curves, curve) - return this +func (p CubicBezierPath) AppendCurve(curve CubicBezierCurve) CubicBezierPath { + p.Curves = append(p.Curves, curve) + return p } -func (bpath CubicBezierPath) Copy() CubicBezierPath { +func (p CubicBezierPath) Copy() CubicBezierPath { bpathcopy := CubicBezierPath{} bpathcopy.Curves = []CubicBezierCurve{} - for _, c := range bpath.Curves { + for _, c := range p.Curves { bpathcopy.Curves = append(bpathcopy.Curves, c) } return bpathcopy } -func (bpath CubicBezierPath) Offset(offX, offY float64) CubicBezierPath { - for i, c := range bpath.Curves { - bpath.Curves[i] = c.AddOffsetXY(offX, offY) +func (p CubicBezierPath) Offset(offX, offY float64) CubicBezierPath { + for i, c := range p.Curves { + p.Curves[i] = c.AddOffsetXY(offX, offY) } - return bpath + return p } -func (bpath CubicBezierPath) GetBoundingBox() Rectangle { +func (p CubicBezierPath) GetBoundingBox() Rectangle { bbox := Rectangle{} minX := 0.0 maxX := 0.0 minY := 0.0 maxY := 0.0 - for idx, c := range bpath.Curves { + for idx, c := range p.Curves { curveBounds := c.GetBounds() if idx == 0 { minX = curveBounds.Llx diff --git a/pdf/contentstream/draw/path.go b/pdf/contentstream/draw/path.go index b82d3a99..9553e453 100644 --- a/pdf/contentstream/draw/path.go +++ b/pdf/contentstream/draw/path.go @@ -11,61 +11,59 @@ type Path struct { } func NewPath() Path { - path := Path{} - path.Points = []Point{} - return path + return Path{} } -func (this Path) AppendPoint(point Point) Path { - this.Points = append(this.Points, point) - return this +func (p Path) AppendPoint(point Point) Path { + p.Points = append(p.Points, point) + return p } -func (this Path) RemovePoint(number int) Path { - if number < 1 || number > len(this.Points) { - return this +func (p Path) RemovePoint(number int) Path { + if number < 1 || number > len(p.Points) { + return p } idx := number - 1 - this.Points = append(this.Points[:idx], this.Points[idx+1:]...) - return this + p.Points = append(p.Points[:idx], p.Points[idx+1:]...) + return p } -func (this Path) Length() int { - return len(this.Points) +func (p Path) Length() int { + return len(p.Points) } -func (this Path) GetPointNumber(number int) Point { - if number < 1 || number > len(this.Points) { +func (p Path) GetPointNumber(number int) Point { + if number < 1 || number > len(p.Points) { return Point{} } - return this.Points[number-1] + return p.Points[number-1] } -func (path Path) Copy() Path { +func (p Path) Copy() Path { pathcopy := Path{} pathcopy.Points = []Point{} - for _, p := range path.Points { + for _, p := range p.Points { pathcopy.Points = append(pathcopy.Points, p) } return pathcopy } -func (path Path) Offset(offX, offY float64) Path { - for i, p := range path.Points { - path.Points[i] = p.Add(offX, offY) +func (p Path) Offset(offX, offY float64) Path { + for i, pt := range p.Points { + p.Points[i] = pt.Add(offX, offY) } - return path + return p } -func (path Path) GetBoundingBox() BoundingBox { +func (p Path) GetBoundingBox() BoundingBox { bbox := BoundingBox{} minX := 0.0 maxX := 0.0 minY := 0.0 maxY := 0.0 - for idx, p := range path.Points { + for idx, p := range p.Points { if idx == 0 { minX = p.X maxX = p.X diff --git a/pdf/contentstream/draw/point.go b/pdf/contentstream/draw/point.go index b7bd03a5..a22e5b5e 100644 --- a/pdf/contentstream/draw/point.go +++ b/pdf/contentstream/draw/point.go @@ -13,10 +13,7 @@ type Point struct { } func NewPoint(x, y float64) Point { - point := Point{} - point.X = x - point.Y = y - return point + return Point{X: x, Y: y} } func (p Point) Add(dx, dy float64) Point { @@ -26,10 +23,10 @@ func (p Point) Add(dx, dy float64) Point { } // AddVector adds vector to a point. -func (this Point) AddVector(v Vector) Point { - this.X += v.Dx - this.Y += v.Dy - return this +func (p Point) AddVector(v Vector) Point { + p.X += v.Dx + p.Y += v.Dy + return p } func (p Point) String() string { diff --git a/pdf/contentstream/draw/vector.go b/pdf/contentstream/draw/vector.go index c97bc41c..0a87a6de 100644 --- a/pdf/contentstream/draw/vector.go +++ b/pdf/contentstream/draw/vector.go @@ -48,13 +48,13 @@ func (v Vector) Rotate(phi float64) Vector { } // Flip changes the sign of the vector: -vector. -func (this Vector) Flip() Vector { - mag := this.Magnitude() - theta := this.GetPolarAngle() +func (v Vector) Flip() Vector { + mag := v.Magnitude() + theta := v.GetPolarAngle() - this.Dx = mag * math.Cos(theta+math.Pi) - this.Dy = mag * math.Sin(theta+math.Pi) - return this + v.Dx = mag * math.Cos(theta+math.Pi) + v.Dy = mag * math.Sin(theta+math.Pi) + return v } func (v Vector) FlipY() Vector { @@ -67,19 +67,19 @@ func (v Vector) FlipX() Vector { return v } -func (this Vector) Scale(factor float64) Vector { - mag := this.Magnitude() - theta := this.GetPolarAngle() +func (v Vector) Scale(factor float64) Vector { + mag := v.Magnitude() + theta := v.GetPolarAngle() - this.Dx = factor * mag * math.Cos(theta) - this.Dy = factor * mag * math.Sin(theta) - return this + v.Dx = factor * mag * math.Cos(theta) + v.Dy = factor * mag * math.Sin(theta) + return v } -func (this Vector) Magnitude() float64 { - return math.Sqrt(math.Pow(this.Dx, 2.0) + math.Pow(this.Dy, 2.0)) +func (v Vector) Magnitude() float64 { + return math.Sqrt(math.Pow(v.Dx, 2.0) + math.Pow(v.Dy, 2.0)) } -func (this Vector) GetPolarAngle() float64 { - return math.Atan2(this.Dy, this.Dx) +func (v Vector) GetPolarAngle() float64 { + return math.Atan2(v.Dy, v.Dx) } diff --git a/pdf/contentstream/processor.go b/pdf/contentstream/processor.go index 8bce425c..cccc4b27 100644 --- a/pdf/contentstream/processor.go +++ b/pdf/contentstream/processor.go @@ -56,12 +56,12 @@ type HandlerEntry struct { type HandlerConditionEnum int -func (this HandlerConditionEnum) All() bool { - return this == HandlerConditionEnumAllOperands +func (h HandlerConditionEnum) All() bool { + return h == HandlerConditionEnumAllOperands } -func (this HandlerConditionEnum) Operand() bool { - return this == HandlerConditionEnumOperand +func (h HandlerConditionEnum) Operand() bool { + return h == HandlerConditionEnumOperand } const ( diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index eea359c7..1e5231ca 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -91,30 +91,30 @@ func NewFlateEncoder() *FlateEncoder { // SetPredictor sets the predictor function. Specify the number of columns per row. // The columns indicates the number of samples per row. // Used for grouping data together for compression. -func (this *FlateEncoder) SetPredictor(columns int) { +func (enc *FlateEncoder) SetPredictor(columns int) { // Only supporting PNG sub predictor for encoding. - this.Predictor = 11 - this.Columns = columns + enc.Predictor = 11 + enc.Columns = columns } -func (this *FlateEncoder) GetFilterName() string { +func (enc *FlateEncoder) GetFilterName() string { return StreamEncodingFilterNameFlate } -func (this *FlateEncoder) MakeDecodeParams() PdfObject { - if this.Predictor > 1 { +func (enc *FlateEncoder) MakeDecodeParams() PdfObject { + if enc.Predictor > 1 { decodeParams := MakeDict() - decodeParams.Set("Predictor", MakeInteger(int64(this.Predictor))) + decodeParams.Set("Predictor", MakeInteger(int64(enc.Predictor))) // Only add if not default option. - if this.BitsPerComponent != 8 { - decodeParams.Set("BitsPerComponent", MakeInteger(int64(this.BitsPerComponent))) + if enc.BitsPerComponent != 8 { + decodeParams.Set("BitsPerComponent", MakeInteger(int64(enc.BitsPerComponent))) } - if this.Columns != 1 { - decodeParams.Set("Columns", MakeInteger(int64(this.Columns))) + if enc.Columns != 1 { + decodeParams.Set("Columns", MakeInteger(int64(enc.Columns))) } - if this.Colors != 1 { - decodeParams.Set("Colors", MakeInteger(int64(this.Colors))) + if enc.Colors != 1 { + decodeParams.Set("Colors", MakeInteger(int64(enc.Colors))) } return decodeParams } @@ -124,11 +124,11 @@ func (this *FlateEncoder) MakeDecodeParams() PdfObject { // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set and the DecodeParms. -func (this *FlateEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *FlateEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) - decodeParams := this.MakeDecodeParams() + decodeParams := enc.MakeDecodeParams() if decodeParams != nil { dict.Set("DecodeParms", decodeParams) } @@ -225,7 +225,7 @@ func newFlateEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObje return encoder, nil } -func (this *FlateEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *FlateEncoder) DecodeBytes(encoded []byte) ([]byte, error) { common.Log.Trace("FlateDecode bytes") bufReader := bytes.NewReader(encoded) @@ -247,28 +247,28 @@ func (this *FlateEncoder) DecodeBytes(encoded []byte) ([]byte, error) { } // DecodeStream decodes a FlateEncoded stream object and give back decoded bytes. -func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { +func (enc *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { // TODO: Handle more filter bytes and support more values of BitsPerComponent. common.Log.Trace("FlateDecode stream") - common.Log.Trace("Predictor: %d", this.Predictor) - if this.BitsPerComponent != 8 { - return nil, fmt.Errorf("Invalid BitsPerComponent=%d (only 8 supported)", this.BitsPerComponent) + common.Log.Trace("Predictor: %d", enc.Predictor) + if enc.BitsPerComponent != 8 { + return nil, fmt.Errorf("Invalid BitsPerComponent=%d (only 8 supported)", enc.BitsPerComponent) } - outData, err := this.DecodeBytes(streamObj.Stream) + outData, err := enc.DecodeBytes(streamObj.Stream) if err != nil { return nil, err } common.Log.Trace("En: % x\n", streamObj.Stream) common.Log.Trace("De: % x\n", outData) - if this.Predictor > 1 { - if this.Predictor == 2 { // TIFF encoding: Needs some tests. + if enc.Predictor > 1 { + if enc.Predictor == 2 { // TIFF encoding: Needs some tests. common.Log.Trace("Tiff encoding") - common.Log.Trace("Colors: %d", this.Colors) + common.Log.Trace("Colors: %d", enc.Colors) - rowLength := int(this.Columns) * this.Colors + rowLength := int(enc.Columns) * enc.Colors if rowLength < 1 { // No data. Return empty set. return []byte{}, nil @@ -278,8 +278,8 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro common.Log.Debug("ERROR: TIFF encoding: Invalid row length...") return nil, fmt.Errorf("Invalid row length (%d/%d)", len(outData), rowLength) } - if rowLength%this.Colors != 0 { - return nil, fmt.Errorf("Invalid row length (%d) for colors %d", rowLength, this.Colors) + if rowLength%enc.Colors != 0 { + return nil, fmt.Errorf("Invalid row length (%d) for colors %d", rowLength, enc.Colors) } if rowLength > len(outData) { common.Log.Debug("Row length cannot be longer than data length (%d/%d)", rowLength, len(outData)) @@ -294,19 +294,19 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro rowData := outData[rowLength*i : rowLength*(i+1)] // Predicts the same as the sample to the left. // Interleaved by colors. - for j := this.Colors; j < rowLength; j++ { - rowData[j] = byte(int(rowData[j]+rowData[j-this.Colors]) % 256) + for j := enc.Colors; j < rowLength; j++ { + rowData[j] = byte(int(rowData[j]+rowData[j-enc.Colors]) % 256) } pOutBuffer.Write(rowData) } pOutData := pOutBuffer.Bytes() common.Log.Trace("POutData (%d): % x", len(pOutData), pOutData) return pOutData, nil - } else if this.Predictor >= 10 && this.Predictor <= 15 { + } else if enc.Predictor >= 10 && enc.Predictor <= 15 { common.Log.Trace("PNG Encoding") // Columns represents the number of samples per row; Each sample can contain multiple color // components. - rowLength := int(this.Columns*this.Colors + 1) // 1 byte to specify predictor algorithms per row. + rowLength := int(enc.Columns*enc.Colors + 1) // 1 byte to specify predictor algorithms per row. rows := len(outData) / rowLength if len(outData)%rowLength != 0 { return nil, fmt.Errorf("Invalid row length (%d/%d)", len(outData), rowLength) @@ -318,7 +318,7 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro pOutBuffer := bytes.NewBuffer(nil) - common.Log.Trace("Predictor columns: %d", this.Columns) + common.Log.Trace("Predictor columns: %d", enc.Columns) common.Log.Trace("Length: %d / %d = %d rows", len(outData), rowLength, rows) prevRowData := make([]byte, rowLength) for i := 0; i < rowLength; i++ { @@ -390,8 +390,8 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro pOutData := pOutBuffer.Bytes() return pOutData, nil } else { - common.Log.Debug("ERROR: Unsupported predictor (%d)", this.Predictor) - return nil, fmt.Errorf("Unsupported predictor (%d)", this.Predictor) + common.Log.Debug("ERROR: Unsupported predictor (%d)", enc.Predictor) + return nil, fmt.Errorf("Unsupported predictor (%d)", enc.Predictor) } } @@ -399,17 +399,17 @@ func (this *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, erro } // EncodeBytes encodes a bytes array and return the encoded value based on the encoder parameters. -func (this *FlateEncoder) EncodeBytes(data []byte) ([]byte, error) { - if this.Predictor != 1 && this.Predictor != 11 { +func (enc *FlateEncoder) EncodeBytes(data []byte) ([]byte, error) { + if enc.Predictor != 1 && enc.Predictor != 11 { common.Log.Debug("Encoding error: FlateEncoder Predictor = 1, 11 only supported") return nil, ErrUnsupportedEncodingParameters } - if this.Predictor == 11 { + if enc.Predictor == 11 { // The length of each output row in number of samples. // N.B. Each output row has one extra sample as compared to the input to indicate the // predictor type. - rowLength := int(this.Columns) + rowLength := int(enc.Columns) rows := len(data) / rowLength if len(data)%rowLength != 0 { common.Log.Error("Invalid column length") @@ -473,24 +473,24 @@ func NewLZWEncoder() *LZWEncoder { return encoder } -func (this *LZWEncoder) GetFilterName() string { +func (enc *LZWEncoder) GetFilterName() string { return StreamEncodingFilterNameLZW } -func (this *LZWEncoder) MakeDecodeParams() PdfObject { - if this.Predictor > 1 { +func (enc *LZWEncoder) MakeDecodeParams() PdfObject { + if enc.Predictor > 1 { decodeParams := MakeDict() - decodeParams.Set("Predictor", MakeInteger(int64(this.Predictor))) + decodeParams.Set("Predictor", MakeInteger(int64(enc.Predictor))) // Only add if not default option. - if this.BitsPerComponent != 8 { - decodeParams.Set("BitsPerComponent", MakeInteger(int64(this.BitsPerComponent))) + if enc.BitsPerComponent != 8 { + decodeParams.Set("BitsPerComponent", MakeInteger(int64(enc.BitsPerComponent))) } - if this.Columns != 1 { - decodeParams.Set("Columns", MakeInteger(int64(this.Columns))) + if enc.Columns != 1 { + decodeParams.Set("Columns", MakeInteger(int64(enc.Columns))) } - if this.Colors != 1 { - decodeParams.Set("Colors", MakeInteger(int64(this.Colors))) + if enc.Colors != 1 { + decodeParams.Set("Colors", MakeInteger(int64(enc.Colors))) } return decodeParams } @@ -499,17 +499,17 @@ func (this *LZWEncoder) MakeDecodeParams() PdfObject { // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set and the DecodeParms. -func (this *LZWEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *LZWEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) - decodeParams := this.MakeDecodeParams() + decodeParams := enc.MakeDecodeParams() if decodeParams != nil { dict.Set("DecodeParms", decodeParams) } - dict.Set("EarlyChange", MakeInteger(int64(this.EarlyChange))) + dict.Set("EarlyChange", MakeInteger(int64(enc.EarlyChange))) return dict } @@ -623,12 +623,12 @@ func newLZWEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObject return encoder, nil } -func (this *LZWEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *LZWEncoder) DecodeBytes(encoded []byte) ([]byte, error) { var outBuf bytes.Buffer bufReader := bytes.NewReader(encoded) var r io.ReadCloser - if this.EarlyChange == 1 { + if enc.EarlyChange == 1 { // LZW implementation with code length increases one code early (1). r = lzw1.NewReader(bufReader, lzw1.MSB, 8) } else { @@ -645,16 +645,16 @@ func (this *LZWEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return outBuf.Bytes(), nil } -func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { +func (enc *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { // Revamp this support to handle TIFF predictor (2). // Also handle more filter bytes and check // BitsPerComponent. Default value is 8, currently we are only // supporting that one. common.Log.Trace("LZW Decoding") - common.Log.Trace("Predictor: %d", this.Predictor) + common.Log.Trace("Predictor: %d", enc.Predictor) - outData, err := this.DecodeBytes(streamObj.Stream) + outData, err := enc.DecodeBytes(streamObj.Stream) if err != nil { return nil, err } @@ -662,11 +662,11 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) common.Log.Trace(" IN: (%d) % x", len(streamObj.Stream), streamObj.Stream) common.Log.Trace("OUT: (%d) % x", len(outData), outData) - if this.Predictor > 1 { - if this.Predictor == 2 { // TIFF encoding: Needs some tests. + if enc.Predictor > 1 { + if enc.Predictor == 2 { // TIFF encoding: Needs some tests. common.Log.Trace("Tiff encoding") - rowLength := int(this.Columns) * this.Colors + rowLength := int(enc.Columns) * enc.Colors if rowLength < 1 { // No data. Return empty set. return []byte{}, nil @@ -678,8 +678,8 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) return nil, fmt.Errorf("Invalid row length (%d/%d)", len(outData), rowLength) } - if rowLength%this.Colors != 0 { - return nil, fmt.Errorf("Invalid row length (%d) for colors %d", rowLength, this.Colors) + if rowLength%enc.Colors != 0 { + return nil, fmt.Errorf("Invalid row length (%d) for colors %d", rowLength, enc.Colors) } if rowLength > len(outData) { @@ -695,8 +695,8 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) rowData := outData[rowLength*i : rowLength*(i+1)] // Predicts the same as the sample to the left. // Interleaved by colors. - for j := this.Colors; j < rowLength; j++ { - rowData[j] = byte(int(rowData[j]+rowData[j-this.Colors]) % 256) + for j := enc.Colors; j < rowLength; j++ { + rowData[j] = byte(int(rowData[j]+rowData[j-enc.Colors]) % 256) } // GH: Appears that this is not working as expected... @@ -705,11 +705,11 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) pOutData := pOutBuffer.Bytes() common.Log.Trace("POutData (%d): % x", len(pOutData), pOutData) return pOutData, nil - } else if this.Predictor >= 10 && this.Predictor <= 15 { + } else if enc.Predictor >= 10 && enc.Predictor <= 15 { common.Log.Trace("PNG Encoding") // Columns represents the number of samples per row; Each sample can contain multiple color // components. - rowLength := int(this.Columns*this.Colors + 1) // 1 byte to specify predictor algorithms per row. + rowLength := int(enc.Columns*enc.Colors + 1) // 1 byte to specify predictor algorithms per row. if rowLength < 1 { // No data. Return empty set. return []byte{}, nil @@ -725,7 +725,7 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) pOutBuffer := bytes.NewBuffer(nil) - common.Log.Trace("Predictor columns: %d", this.Columns) + common.Log.Trace("Predictor columns: %d", enc.Columns) common.Log.Trace("Length: %d / %d = %d rows", len(outData), rowLength, rows) prevRowData := make([]byte, rowLength) for i := 0; i < rowLength; i++ { @@ -762,8 +762,8 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) pOutData := pOutBuffer.Bytes() return pOutData, nil } else { - common.Log.Debug("ERROR: Unsupported predictor (%d)", this.Predictor) - return nil, fmt.Errorf("Unsupported predictor (%d)", this.Predictor) + common.Log.Debug("ERROR: Unsupported predictor (%d)", enc.Predictor) + return nil, fmt.Errorf("Unsupported predictor (%d)", enc.Predictor) } } @@ -774,12 +774,12 @@ func (this *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) // Only supports the Early change = 1 algorithm (compress/lzw) as the other implementation // does not have a write method. // TODO: Consider refactoring compress/lzw to allow both. -func (this *LZWEncoder) EncodeBytes(data []byte) ([]byte, error) { - if this.Predictor != 1 { +func (enc *LZWEncoder) EncodeBytes(data []byte) ([]byte, error) { + if enc.Predictor != 1 { return nil, fmt.Errorf("LZW Predictor = 1 only supported yet") } - if this.EarlyChange == 1 { + if enc.EarlyChange == 1 { return nil, fmt.Errorf("LZW Early Change = 0 only supported yet") } @@ -812,21 +812,21 @@ func NewDCTEncoder() *DCTEncoder { return encoder } -func (this *DCTEncoder) GetFilterName() string { +func (enc *DCTEncoder) GetFilterName() string { return StreamEncodingFilterNameDCT } -func (this *DCTEncoder) MakeDecodeParams() PdfObject { +func (enc *DCTEncoder) MakeDecodeParams() PdfObject { // Does not have decode params. return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. // Has the Filter set. Some other parameters are generated elsewhere. -func (this *DCTEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *DCTEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) return dict } @@ -897,7 +897,7 @@ func newDCTEncoderFromStream(streamObj *PdfObjectStream, multiEnc *MultiEncoder) return encoder, nil } -func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { bufReader := bytes.NewReader(encoded) //img, _, err := goimage.Decode(bufReader) img, err := jpeg.Decode(bufReader) @@ -907,7 +907,7 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { } bounds := img.Bounds() - var decoded = make([]byte, bounds.Dx()*bounds.Dy()*this.ColorComponents*this.BitsPerComponent/8) + var decoded = make([]byte, bounds.Dx()*bounds.Dy()*enc.ColorComponents*enc.BitsPerComponent/8) index := 0 for j := bounds.Min.Y; j < bounds.Max.Y; j++ { @@ -915,8 +915,8 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { color := img.At(i, j) // Gray scale. - if this.ColorComponents == 1 { - if this.BitsPerComponent == 16 { + if enc.ColorComponents == 1 { + if enc.BitsPerComponent == 16 { // Gray - 16 bit. val, ok := color.(gocolor.Gray16) if !ok { @@ -935,8 +935,8 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { decoded[index] = byte(val.Y & 0xff) index++ } - } else if this.ColorComponents == 3 { - if this.BitsPerComponent == 16 { + } else if enc.ColorComponents == 3 { + if enc.BitsPerComponent == 16 { val, ok := color.(gocolor.RGBA64) if !ok { return nil, errors.New("Color type error") @@ -987,7 +987,7 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { index++ } } - } else if this.ColorComponents == 4 { + } else if enc.ColorComponents == 4 { // CMYK - 8 bit. val, ok := color.(gocolor.CMYK) if !ok { @@ -1010,8 +1010,8 @@ func (this *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return decoded, nil } -func (this *DCTEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - return this.DecodeBytes(streamObj.Stream) +func (enc *DCTEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + return enc.DecodeBytes(streamObj.Stream) } // DrawableImage is same as golang image/draw's Image interface that allow drawing images. @@ -1022,22 +1022,22 @@ type DrawableImage interface { Set(x, y int, c gocolor.Color) } -func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { - bounds := goimage.Rect(0, 0, this.Width, this.Height) +func (enc *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { + bounds := goimage.Rect(0, 0, enc.Width, enc.Height) var img DrawableImage - if this.ColorComponents == 1 { - if this.BitsPerComponent == 16 { + if enc.ColorComponents == 1 { + if enc.BitsPerComponent == 16 { img = goimage.NewGray16(bounds) } else { img = goimage.NewGray(bounds) } - } else if this.ColorComponents == 3 { - if this.BitsPerComponent == 16 { + } else if enc.ColorComponents == 3 { + if enc.BitsPerComponent == 16 { img = goimage.NewRGBA64(bounds) } else { img = goimage.NewRGBA(bounds) } - } else if this.ColorComponents == 4 { + } else if enc.ColorComponents == 4 { img = goimage.NewCMYK(bounds) } else { return nil, errors.New("Unsupported") @@ -1046,19 +1046,19 @@ func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { // Draw the data on the image.. x := 0 y := 0 - bytesPerColor := this.ColorComponents * this.BitsPerComponent / 8 + bytesPerColor := enc.ColorComponents * enc.BitsPerComponent / 8 for i := 0; i+bytesPerColor-1 < len(data); i += bytesPerColor { var c gocolor.Color - if this.ColorComponents == 1 { - if this.BitsPerComponent == 16 { + if enc.ColorComponents == 1 { + if enc.BitsPerComponent == 16 { val := uint16(data[i])<<8 | uint16(data[i+1]) c = gocolor.Gray16{val} } else { val := uint8(data[i] & 0xff) c = gocolor.Gray{val} } - } else if this.ColorComponents == 3 { - if this.BitsPerComponent == 16 { + } else if enc.ColorComponents == 3 { + if enc.BitsPerComponent == 16 { r := uint16(data[i])<<8 | uint16(data[i+1]) g := uint16(data[i+2])<<8 | uint16(data[i+3]) b := uint16(data[i+4])<<8 | uint16(data[i+5]) @@ -1069,7 +1069,7 @@ func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { b := uint8(data[i+2] & 0xff) c = gocolor.RGBA{R: r, G: g, B: b, A: 0} } - } else if this.ColorComponents == 4 { + } else if enc.ColorComponents == 4 { c1 := uint8(data[i] & 0xff) m1 := uint8(data[i+1] & 0xff) y1 := uint8(data[i+2] & 0xff) @@ -1079,7 +1079,7 @@ func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { img.Set(x, y, c) x++ - if x == this.Width { + if x == enc.Width { x = 0 y++ } @@ -1090,7 +1090,7 @@ func (this *DCTEncoder) EncodeBytes(data []byte) ([]byte, error) { // This is not related to the DPI, but rather inherent transformation losses. opt := jpeg.Options{} - opt.Quality = this.Quality + opt.Quality = enc.Quality var buf bytes.Buffer err := jpeg.Encode(&buf, img, &opt) @@ -1110,7 +1110,7 @@ func NewRunLengthEncoder() *RunLengthEncoder { return &RunLengthEncoder{} } -func (this *RunLengthEncoder) GetFilterName() string { +func (enc *RunLengthEncoder) GetFilterName() string { return StreamEncodingFilterNameRunLength } @@ -1128,7 +1128,7 @@ func newRunLengthEncoderFromStream(streamObj *PdfObjectStream, decodeParams *Pdf // bytes of data. If the length byte is in the range 0 to 127, the following length + 1 (1 to 128) bytes shall be // copied literally during decompression. If length is in the range 129 to 255, the following single byte shall be // copied 257 - length (2 to 128) times during decompression. A length value of 128 shall denote EOD. -func (this *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { // TODO(dennwc): use encoded slice directly, instead of wrapping it into a Reader bufReader := bytes.NewReader(encoded) var inb []byte @@ -1162,12 +1162,12 @@ func (this *RunLengthEncoder) DecodeBytes(encoded []byte) ([]byte, error) { } // DecodeStream decodes RunLengthEncoded stream object and give back decoded bytes. -func (this *RunLengthEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - return this.DecodeBytes(streamObj.Stream) +func (enc *RunLengthEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + return enc.DecodeBytes(streamObj.Stream) } // EncodeBytes encodes a bytes array and return the encoded value based on the encoder parameters. -func (this *RunLengthEncoder) EncodeBytes(data []byte) ([]byte, error) { +func (enc *RunLengthEncoder) EncodeBytes(data []byte) ([]byte, error) { bufReader := bytes.NewReader(data) var inb []byte var literal []byte @@ -1234,14 +1234,14 @@ func (this *RunLengthEncoder) EncodeBytes(data []byte) ([]byte, error) { return inb, nil } -func (this *RunLengthEncoder) MakeDecodeParams() PdfObject { +func (enc *RunLengthEncoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *RunLengthEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *RunLengthEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) return dict } @@ -1255,22 +1255,22 @@ func NewASCIIHexEncoder() *ASCIIHexEncoder { return encoder } -func (this *ASCIIHexEncoder) GetFilterName() string { +func (enc *ASCIIHexEncoder) GetFilterName() string { return StreamEncodingFilterNameASCIIHex } -func (this *ASCIIHexEncoder) MakeDecodeParams() PdfObject { +func (enc *ASCIIHexEncoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *ASCIIHexEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *ASCIIHexEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) return dict } -func (this *ASCIIHexEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *ASCIIHexEncoder) DecodeBytes(encoded []byte) ([]byte, error) { bufReader := bytes.NewReader(encoded) var inb []byte for { @@ -1304,11 +1304,11 @@ func (this *ASCIIHexEncoder) DecodeBytes(encoded []byte) ([]byte, error) { } // DecodeStream implements ASCII hex decoding. -func (this *ASCIIHexEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - return this.DecodeBytes(streamObj.Stream) +func (enc *ASCIIHexEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + return enc.DecodeBytes(streamObj.Stream) } -func (this *ASCIIHexEncoder) EncodeBytes(data []byte) ([]byte, error) { +func (enc *ASCIIHexEncoder) EncodeBytes(data []byte) ([]byte, error) { var encoded bytes.Buffer for _, b := range data { @@ -1329,23 +1329,23 @@ func NewASCII85Encoder() *ASCII85Encoder { return encoder } -func (this *ASCII85Encoder) GetFilterName() string { +func (enc *ASCII85Encoder) GetFilterName() string { return StreamEncodingFilterNameASCII85 } -func (this *ASCII85Encoder) MakeDecodeParams() PdfObject { +func (enc *ASCII85Encoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict make a new instance of an encoding dictionary for a stream object. -func (this *ASCII85Encoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *ASCII85Encoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) return dict } // DecodeBytes decodes byte array with ASCII85. 5 ASCII characters -> 4 raw binary bytes -func (this *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { var decoded []byte common.Log.Trace("ASCII85 Decode") @@ -1423,15 +1423,15 @@ func (this *ASCII85Encoder) DecodeBytes(encoded []byte) ([]byte, error) { } // DecodeStream implements ASCII85 stream decoding. -func (this *ASCII85Encoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - return this.DecodeBytes(streamObj.Stream) +func (enc *ASCII85Encoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + return enc.DecodeBytes(streamObj.Stream) } // Convert a base 256 number to a series of base 85 values (5 codes). // 85^5 = 4437053125 > 256^4 = 4294967296 // So 5 base-85 numbers will always be enough to cover 4 base-256 numbers. // The base 256 value is already converted to an uint32 value. -func (this *ASCII85Encoder) base256Tobase85(base256val uint32) [5]byte { +func (enc *ASCII85Encoder) base256Tobase85(base256val uint32) [5]byte { base85 := [5]byte{0, 0, 0, 0, 0} remainder := base256val for i := 0; i < 5; i++ { @@ -1447,7 +1447,7 @@ func (this *ASCII85Encoder) base256Tobase85(base256val uint32) [5]byte { } // EncodeBytes encodes data into ASCII85 encoded format. -func (this *ASCII85Encoder) EncodeBytes(data []byte) ([]byte, error) { +func (enc *ASCII85Encoder) EncodeBytes(data []byte) ([]byte, error) { var encoded bytes.Buffer for i := 0; i < len(data); i += 4 { @@ -1477,7 +1477,7 @@ func (this *ASCII85Encoder) EncodeBytes(data []byte) ([]byte, error) { if base256 == 0 { encoded.WriteByte('z') } else { - base85vals := this.base256Tobase85(base256) + base85vals := enc.base256Tobase85(base256) for _, val := range base85vals[:n+1] { encoded.WriteByte(val + '!') } @@ -1496,28 +1496,28 @@ func NewRawEncoder() *RawEncoder { return &RawEncoder{} } -func (this *RawEncoder) GetFilterName() string { +func (enc *RawEncoder) GetFilterName() string { return StreamEncodingFilterNameRaw } -func (this *RawEncoder) MakeDecodeParams() PdfObject { +func (enc *RawEncoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *RawEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *RawEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } -func (this *RawEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *RawEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return encoded, nil } -func (this *RawEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { +func (enc *RawEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { return streamObj.Stream, nil } -func (this *RawEncoder) EncodeBytes(data []byte) ([]byte, error) { +func (enc *RawEncoder) EncodeBytes(data []byte) ([]byte, error) { return data, nil } @@ -1529,31 +1529,31 @@ func NewCCITTFaxEncoder() *CCITTFaxEncoder { return &CCITTFaxEncoder{} } -func (this *CCITTFaxEncoder) GetFilterName() string { +func (enc *CCITTFaxEncoder) GetFilterName() string { return StreamEncodingFilterNameCCITTFax } -func (this *CCITTFaxEncoder) MakeDecodeParams() PdfObject { +func (enc *CCITTFaxEncoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *CCITTFaxEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *CCITTFaxEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } -func (this *CCITTFaxEncoder) DecodeBytes(encoded []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *CCITTFaxEncoder) DecodeBytes(encoded []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return encoded, ErrNoCCITTFaxDecode } -func (this *CCITTFaxEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *CCITTFaxEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return streamObj.Stream, ErrNoCCITTFaxDecode } -func (this *CCITTFaxEncoder) EncodeBytes(data []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *CCITTFaxEncoder) EncodeBytes(data []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return data, ErrNoCCITTFaxDecode } @@ -1565,31 +1565,31 @@ func NewJBIG2Encoder() *JBIG2Encoder { return &JBIG2Encoder{} } -func (this *JBIG2Encoder) GetFilterName() string { +func (enc *JBIG2Encoder) GetFilterName() string { return StreamEncodingFilterNameJBIG2 } -func (this *JBIG2Encoder) MakeDecodeParams() PdfObject { +func (enc *JBIG2Encoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *JBIG2Encoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *JBIG2Encoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } -func (this *JBIG2Encoder) DecodeBytes(encoded []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JBIG2Encoder) DecodeBytes(encoded []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return encoded, ErrNoJBIG2Decode } -func (this *JBIG2Encoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JBIG2Encoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return streamObj.Stream, ErrNoJBIG2Decode } -func (this *JBIG2Encoder) EncodeBytes(data []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JBIG2Encoder) EncodeBytes(data []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return data, ErrNoJBIG2Decode } @@ -1601,31 +1601,31 @@ func NewJPXEncoder() *JPXEncoder { return &JPXEncoder{} } -func (this *JPXEncoder) GetFilterName() string { +func (enc *JPXEncoder) GetFilterName() string { return StreamEncodingFilterNameJPX } -func (this *JPXEncoder) MakeDecodeParams() PdfObject { +func (enc *JPXEncoder) MakeDecodeParams() PdfObject { return nil } // MakeStreamDict makes a new instance of an encoding dictionary for a stream object. -func (this *JPXEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *JPXEncoder) MakeStreamDict() *PdfObjectDictionary { return MakeDict() } -func (this *JPXEncoder) DecodeBytes(encoded []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JPXEncoder) DecodeBytes(encoded []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return encoded, ErrNoJPXDecode } -func (this *JPXEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JPXEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return streamObj.Stream, ErrNoJPXDecode } -func (this *JPXEncoder) EncodeBytes(data []byte) ([]byte, error) { - common.Log.Debug("Error: Attempting to use unsupported encoding %s", this.GetFilterName()) +func (enc *JPXEncoder) EncodeBytes(data []byte) ([]byte, error) { + common.Log.Debug("Error: Attempting to use unsupported encoding %s", enc.GetFilterName()) return data, ErrNoJPXDecode } @@ -1751,28 +1751,28 @@ func newMultiEncoderFromStream(streamObj *PdfObjectStream) (*MultiEncoder, error return mencoder, nil } -func (this *MultiEncoder) GetFilterName() string { +func (enc *MultiEncoder) GetFilterName() string { name := "" - for idx, encoder := range this.encoders { + for idx, encoder := range enc.encoders { name += encoder.GetFilterName() - if idx < len(this.encoders)-1 { + if idx < len(enc.encoders)-1 { name += " " } } return name } -func (this *MultiEncoder) MakeDecodeParams() PdfObject { - if len(this.encoders) == 0 { +func (enc *MultiEncoder) MakeDecodeParams() PdfObject { + if len(enc.encoders) == 0 { return nil } - if len(this.encoders) == 1 { - return this.encoders[0].MakeDecodeParams() + if len(enc.encoders) == 1 { + return enc.encoders[0].MakeDecodeParams() } array := MakeArray() - for _, encoder := range this.encoders { + for _, encoder := range enc.encoders { decodeParams := encoder.MakeDecodeParams() if decodeParams == nil { array.Append(MakeNull()) @@ -1784,16 +1784,16 @@ func (this *MultiEncoder) MakeDecodeParams() PdfObject { return array } -func (this *MultiEncoder) AddEncoder(encoder StreamEncoder) { - this.encoders = append(this.encoders, encoder) +func (enc *MultiEncoder) AddEncoder(encoder StreamEncoder) { + enc.encoders = append(enc.encoders, encoder) } -func (this *MultiEncoder) MakeStreamDict() *PdfObjectDictionary { +func (enc *MultiEncoder) MakeStreamDict() *PdfObjectDictionary { dict := MakeDict() - dict.Set("Filter", MakeName(this.GetFilterName())) + dict.Set("Filter", MakeName(enc.GetFilterName())) // Pass all values from children, except Filter and DecodeParms. - for _, encoder := range this.encoders { + for _, encoder := range enc.encoders { encDict := encoder.MakeStreamDict() for _, key := range encDict.Keys() { val := encDict.Get(key) @@ -1804,7 +1804,7 @@ func (this *MultiEncoder) MakeStreamDict() *PdfObjectDictionary { } // Make the decode params array or dict. - decodeParams := this.MakeDecodeParams() + decodeParams := enc.MakeDecodeParams() if decodeParams != nil { dict.Set("DecodeParms", decodeParams) } @@ -1812,11 +1812,11 @@ func (this *MultiEncoder) MakeStreamDict() *PdfObjectDictionary { return dict } -func (this *MultiEncoder) DecodeBytes(encoded []byte) ([]byte, error) { +func (enc *MultiEncoder) DecodeBytes(encoded []byte) ([]byte, error) { decoded := encoded var err error // Apply in forward order. - for _, encoder := range this.encoders { + for _, encoder := range enc.encoders { common.Log.Trace("Multi Encoder Decode: Applying Filter: %v %T", encoder, encoder) decoded, err = encoder.DecodeBytes(decoded) @@ -1828,17 +1828,17 @@ func (this *MultiEncoder) DecodeBytes(encoded []byte) ([]byte, error) { return decoded, nil } -func (this *MultiEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { - return this.DecodeBytes(streamObj.Stream) +func (enc *MultiEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) { + return enc.DecodeBytes(streamObj.Stream) } -func (this *MultiEncoder) EncodeBytes(data []byte) ([]byte, error) { +func (enc *MultiEncoder) EncodeBytes(data []byte) ([]byte, error) { encoded := data var err error // Apply in inverse order. - for i := len(this.encoders) - 1; i >= 0; i-- { - encoder := this.encoders[i] + for i := len(enc.encoders) - 1; i >= 0; i-- { + encoder := enc.encoders[i] encoded, err = encoder.EncodeBytes(encoded) if err != nil { return nil, err diff --git a/pdf/model/colorspace.go b/pdf/model/colorspace.go index a0c1c690..3ba1b4d3 100644 --- a/pdf/model/colorspace.go +++ b/pdf/model/colorspace.go @@ -211,18 +211,18 @@ func NewPdfColorDeviceGray(grayVal float64) *PdfColorDeviceGray { } // GetNumComponents returns the number of color components (1 for grayscale). -func (this *PdfColorDeviceGray) GetNumComponents() int { +func (cl *PdfColorDeviceGray) GetNumComponents() int { return 1 } -func (this *PdfColorDeviceGray) Val() float64 { - return float64(*this) +func (cl *PdfColorDeviceGray) Val() float64 { + return float64(*cl) } // ToInteger convert to an integer format. -func (this *PdfColorDeviceGray) ToInteger(bits int) uint32 { +func (cl *PdfColorDeviceGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return uint32(maxVal * this.Val()) + return uint32(maxVal * cl.Val()) } type PdfColorspaceDeviceGray struct{} @@ -231,24 +231,24 @@ func NewPdfColorspaceDeviceGray() *PdfColorspaceDeviceGray { return &PdfColorspaceDeviceGray{} } -func (this *PdfColorspaceDeviceGray) GetNumComponents() int { +func (cl *PdfColorspaceDeviceGray) GetNumComponents() int { return 1 } // DecodeArray returns the range of color component values in DeviceGray colorspace. -func (this *PdfColorspaceDeviceGray) DecodeArray() []float64 { +func (cl *PdfColorspaceDeviceGray) DecodeArray() []float64 { return []float64{0, 1.0} } -func (this *PdfColorspaceDeviceGray) ToPdfObject() PdfObject { +func (cl *PdfColorspaceDeviceGray) ToPdfObject() PdfObject { return MakeName("DeviceGray") } -func (this *PdfColorspaceDeviceGray) String() string { +func (cl *PdfColorspaceDeviceGray) String() string { return "DeviceGray" } -func (this *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } @@ -269,7 +269,7 @@ func (this *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, return NewPdfColorDeviceGray(val), nil } -func (this *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -279,11 +279,11 @@ func (this *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (P return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } // ColorToRGB converts gray -> rgb for a single color component. -func (this *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) { gray, ok := color.(*PdfColorDeviceGray) if !ok { common.Log.Debug("Input color not device gray %T", color) @@ -294,7 +294,7 @@ func (this *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error } // ImageToRGB convert 1-component grayscale data to 3-component RGB. -func (this *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -327,31 +327,31 @@ func NewPdfColorDeviceRGB(r, g, b float64) *PdfColorDeviceRGB { return &color } -func (this *PdfColorDeviceRGB) GetNumComponents() int { +func (cl *PdfColorDeviceRGB) GetNumComponents() int { return 3 } -func (this *PdfColorDeviceRGB) R() float64 { - return float64(this[0]) +func (cl *PdfColorDeviceRGB) R() float64 { + return float64(cl[0]) } -func (this *PdfColorDeviceRGB) G() float64 { - return float64(this[1]) +func (cl *PdfColorDeviceRGB) G() float64 { + return float64(cl[1]) } -func (this *PdfColorDeviceRGB) B() float64 { - return float64(this[2]) +func (cl *PdfColorDeviceRGB) B() float64 { + return float64(cl[2]) } // ToInteger convert to an integer format. -func (this *PdfColorDeviceRGB) ToInteger(bits int) [3]uint32 { +func (cl *PdfColorDeviceRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * this.R()), uint32(maxVal * this.G()), uint32(maxVal * this.B())} + return [3]uint32{uint32(maxVal * cl.R()), uint32(maxVal * cl.G()), uint32(maxVal * cl.B())} } -func (this *PdfColorDeviceRGB) ToGray() *PdfColorDeviceGray { +func (cl *PdfColorDeviceRGB) ToGray() *PdfColorDeviceGray { // Calculate grayValue [0-1] - grayValue := 0.3*this.R() + 0.59*this.G() + 0.11*this.B() + grayValue := 0.3*cl.R() + 0.59*cl.G() + 0.11*cl.B() // Clip to [0-1] grayValue = math.Min(math.Max(grayValue, 0.0), 1.0) @@ -367,24 +367,24 @@ func NewPdfColorspaceDeviceRGB() *PdfColorspaceDeviceRGB { return &PdfColorspaceDeviceRGB{} } -func (this *PdfColorspaceDeviceRGB) String() string { +func (cl *PdfColorspaceDeviceRGB) String() string { return "DeviceRGB" } -func (this *PdfColorspaceDeviceRGB) GetNumComponents() int { +func (cl *PdfColorspaceDeviceRGB) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in DeviceRGB colorspace. -func (this *PdfColorspaceDeviceRGB) DecodeArray() []float64 { +func (cl *PdfColorspaceDeviceRGB) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } -func (this *PdfColorspaceDeviceRGB) ToPdfObject() PdfObject { +func (cl *PdfColorspaceDeviceRGB) ToPdfObject() PdfObject { return MakeName("DeviceRGB") } -func (this *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -413,7 +413,7 @@ func (this *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, e } // ColorFromPdfObjects gets the color from a series of pdf objects (3 for rgb). -func (this *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -423,10 +423,10 @@ func (this *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (Pd return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) { rgb, ok := color.(*PdfColorDeviceRGB) if !ok { common.Log.Debug("Input color not device RGB") @@ -435,11 +435,11 @@ func (this *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) return rgb, nil } -func (this *PdfColorspaceDeviceRGB) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceDeviceRGB) ImageToRGB(img Image) (Image, error) { return img, nil } -func (this *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { +func (cl *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { grayImage := img samples := img.GetSamples() @@ -481,30 +481,30 @@ func NewPdfColorDeviceCMYK(c, m, y, k float64) *PdfColorDeviceCMYK { return &color } -func (this *PdfColorDeviceCMYK) GetNumComponents() int { +func (cl *PdfColorDeviceCMYK) GetNumComponents() int { return 4 } -func (this *PdfColorDeviceCMYK) C() float64 { - return float64(this[0]) +func (cl *PdfColorDeviceCMYK) C() float64 { + return float64(cl[0]) } -func (this *PdfColorDeviceCMYK) M() float64 { - return float64(this[1]) +func (cl *PdfColorDeviceCMYK) M() float64 { + return float64(cl[1]) } -func (this *PdfColorDeviceCMYK) Y() float64 { - return float64(this[2]) +func (cl *PdfColorDeviceCMYK) Y() float64 { + return float64(cl[2]) } -func (this *PdfColorDeviceCMYK) K() float64 { - return float64(this[3]) +func (cl *PdfColorDeviceCMYK) K() float64 { + return float64(cl[3]) } // ToInteger convert to an integer format. -func (this *PdfColorDeviceCMYK) ToInteger(bits int) [4]uint32 { +func (cl *PdfColorDeviceCMYK) ToInteger(bits int) [4]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [4]uint32{uint32(maxVal * this.C()), uint32(maxVal * this.M()), uint32(maxVal * this.Y()), uint32(maxVal * this.K())} + return [4]uint32{uint32(maxVal * cl.C()), uint32(maxVal * cl.M()), uint32(maxVal * cl.Y()), uint32(maxVal * cl.K())} } type PdfColorspaceDeviceCMYK struct{} @@ -513,24 +513,24 @@ func NewPdfColorspaceDeviceCMYK() *PdfColorspaceDeviceCMYK { return &PdfColorspaceDeviceCMYK{} } -func (this *PdfColorspaceDeviceCMYK) String() string { +func (cl *PdfColorspaceDeviceCMYK) String() string { return "DeviceCMYK" } -func (this *PdfColorspaceDeviceCMYK) GetNumComponents() int { +func (cl *PdfColorspaceDeviceCMYK) GetNumComponents() int { return 4 } // DecodeArray returns the range of color component values in DeviceCMYK colorspace. -func (this *PdfColorspaceDeviceCMYK) DecodeArray() []float64 { +func (cl *PdfColorspaceDeviceCMYK) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } -func (this *PdfColorspaceDeviceCMYK) ToPdfObject() PdfObject { +func (cl *PdfColorspaceDeviceCMYK) ToPdfObject() PdfObject { return MakeName("DeviceCMYK") } -func (this *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 4 { return nil, errors.New("Range check") } @@ -564,7 +564,7 @@ func (this *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, } // ColorFromPdfObjects gets the color from a series of pdf objects (4 for cmyk). -func (this *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 4 { return nil, errors.New("Range check") } @@ -574,10 +574,10 @@ func (this *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (P return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error) { cmyk, ok := color.(*PdfColorDeviceCMYK) if !ok { common.Log.Debug("Input color not device cmyk") @@ -601,7 +601,7 @@ func (this *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error } // ImageToRGB converts an image in CMYK colorspace to an RGB image. -func (this *PdfColorspaceDeviceCMYK) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceDeviceCMYK) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -671,18 +671,18 @@ func NewPdfColorCalGray(grayVal float64) *PdfColorCalGray { return &color } -func (this *PdfColorCalGray) GetNumComponents() int { +func (cl *PdfColorCalGray) GetNumComponents() int { return 1 } -func (this *PdfColorCalGray) Val() float64 { - return float64(*this) +func (cl *PdfColorCalGray) Val() float64 { + return float64(*cl) } // ToInteger convert to an integer format. -func (this *PdfColorCalGray) ToInteger(bits int) uint32 { +func (cl *PdfColorCalGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return uint32(maxVal * this.Val()) + return uint32(maxVal * cl.Val()) } // PdfColorspaceCalGray represents CalGray color space. @@ -704,16 +704,16 @@ func NewPdfColorspaceCalGray() *PdfColorspaceCalGray { return cs } -func (this *PdfColorspaceCalGray) String() string { +func (cl *PdfColorspaceCalGray) String() string { return "CalGray" } -func (this *PdfColorspaceCalGray) GetNumComponents() int { +func (cl *PdfColorspaceCalGray) GetNumComponents() int { return 1 } // DecodeArray returns the range of color component values in CalGray colorspace. -func (this *PdfColorspaceCalGray) DecodeArray() []float64 { +func (cl *PdfColorspaceCalGray) DecodeArray() []float64 { return []float64{0.0, 1.0} } @@ -803,35 +803,35 @@ func newPdfColorspaceCalGrayFromPdfObject(obj PdfObject) (*PdfColorspaceCalGray, } // ToPdfObject return the CalGray colorspace as a PDF object (name dictionary). -func (this *PdfColorspaceCalGray) ToPdfObject() PdfObject { +func (cl *PdfColorspaceCalGray) ToPdfObject() PdfObject { // CalGray color space dictionary.. cspace := &PdfObjectArray{} cspace.Append(MakeName("CalGray")) dict := MakeDict() - if this.WhitePoint != nil { - dict.Set("WhitePoint", MakeArray(MakeFloat(this.WhitePoint[0]), MakeFloat(this.WhitePoint[1]), MakeFloat(this.WhitePoint[2]))) + if cl.WhitePoint != nil { + dict.Set("WhitePoint", MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2]))) } else { common.Log.Error("CalGray: Missing WhitePoint (Required)") } - if this.BlackPoint != nil { - dict.Set("BlackPoint", MakeArray(MakeFloat(this.BlackPoint[0]), MakeFloat(this.BlackPoint[1]), MakeFloat(this.BlackPoint[2]))) + if cl.BlackPoint != nil { + dict.Set("BlackPoint", MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2]))) } - dict.Set("Gamma", MakeFloat(this.Gamma)) + dict.Set("Gamma", MakeFloat(cl.Gamma)) cspace.Append(dict) - if this.container != nil { - this.container.PdfObject = cspace - return this.container + if cl.container != nil { + cl.container.PdfObject = cspace + return cl.container } return cspace } -func (this *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } @@ -845,7 +845,7 @@ func (this *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, err return color, nil } -func (this *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -855,10 +855,10 @@ func (this *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfC return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { calgray, ok := color.(*PdfColorCalGray) if !ok { common.Log.Debug("Input color not cal gray") @@ -868,9 +868,9 @@ func (this *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { ANorm := calgray.Val() // A -> X,Y,Z - X := this.WhitePoint[0] * math.Pow(ANorm, this.Gamma) - Y := this.WhitePoint[1] * math.Pow(ANorm, this.Gamma) - Z := this.WhitePoint[2] * math.Pow(ANorm, this.Gamma) + X := cl.WhitePoint[0] * math.Pow(ANorm, cl.Gamma) + Y := cl.WhitePoint[1] * math.Pow(ANorm, cl.Gamma) + Z := cl.WhitePoint[2] * math.Pow(ANorm, cl.Gamma) // X,Y,Z -> rgb // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -887,7 +887,7 @@ func (this *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { } // ImageToRGB converts image in CalGray color space to RGB (A, B, C -> X, Y, Z). -func (this *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -900,9 +900,9 @@ func (this *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { ANorm := float64(samples[i]) / maxVal // A -> X,Y,Z - X := this.WhitePoint[0] * math.Pow(ANorm, this.Gamma) - Y := this.WhitePoint[1] * math.Pow(ANorm, this.Gamma) - Z := this.WhitePoint[2] * math.Pow(ANorm, this.Gamma) + X := cl.WhitePoint[0] * math.Pow(ANorm, cl.Gamma) + Y := cl.WhitePoint[1] * math.Pow(ANorm, cl.Gamma) + Z := cl.WhitePoint[2] * math.Pow(ANorm, cl.Gamma) // X,Y,Z -> rgb // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -940,26 +940,26 @@ func NewPdfColorCalRGB(a, b, c float64) *PdfColorCalRGB { return &color } -func (this *PdfColorCalRGB) GetNumComponents() int { +func (cl *PdfColorCalRGB) GetNumComponents() int { return 3 } -func (this *PdfColorCalRGB) A() float64 { - return float64(this[0]) +func (cl *PdfColorCalRGB) A() float64 { + return float64(cl[0]) } -func (this *PdfColorCalRGB) B() float64 { - return float64(this[1]) +func (cl *PdfColorCalRGB) B() float64 { + return float64(cl[1]) } -func (this *PdfColorCalRGB) C() float64 { - return float64(this[2]) +func (cl *PdfColorCalRGB) C() float64 { + return float64(cl[2]) } // ToInteger convert to an integer format. -func (this *PdfColorCalRGB) ToInteger(bits int) [3]uint32 { +func (cl *PdfColorCalRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * this.A()), uint32(maxVal * this.B()), uint32(maxVal * this.C())} + return [3]uint32{uint32(maxVal * cl.A()), uint32(maxVal * cl.B()), uint32(maxVal * cl.C())} } // PdfColorspaceCalRGB stores A, B, C components @@ -985,16 +985,16 @@ func NewPdfColorspaceCalRGB() *PdfColorspaceCalRGB { return cs } -func (this *PdfColorspaceCalRGB) String() string { +func (cl *PdfColorspaceCalRGB) String() string { return "CalRGB" } -func (this *PdfColorspaceCalRGB) GetNumComponents() int { +func (cl *PdfColorspaceCalRGB) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in CalRGB colorspace. -func (this *PdfColorspaceCalRGB) DecodeArray() []float64 { +func (cl *PdfColorspaceCalRGB) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } @@ -1107,45 +1107,45 @@ func newPdfColorspaceCalRGBFromPdfObject(obj PdfObject) (*PdfColorspaceCalRGB, e } // ToPdfObject returns colorspace in a PDF object format [name dictionary] -func (this *PdfColorspaceCalRGB) ToPdfObject() PdfObject { +func (cl *PdfColorspaceCalRGB) ToPdfObject() PdfObject { // CalRGB color space dictionary.. cspace := &PdfObjectArray{} cspace.Append(MakeName("CalRGB")) dict := MakeDict() - if this.WhitePoint != nil { - wp := MakeArray(MakeFloat(this.WhitePoint[0]), MakeFloat(this.WhitePoint[1]), MakeFloat(this.WhitePoint[2])) + if cl.WhitePoint != nil { + wp := MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2])) dict.Set("WhitePoint", wp) } else { common.Log.Error("CalRGB: Missing WhitePoint (Required)") } - if this.BlackPoint != nil { - bp := MakeArray(MakeFloat(this.BlackPoint[0]), MakeFloat(this.BlackPoint[1]), MakeFloat(this.BlackPoint[2])) + if cl.BlackPoint != nil { + bp := MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2])) dict.Set("BlackPoint", bp) } - if this.Gamma != nil { - g := MakeArray(MakeFloat(this.Gamma[0]), MakeFloat(this.Gamma[1]), MakeFloat(this.Gamma[2])) + if cl.Gamma != nil { + g := MakeArray(MakeFloat(cl.Gamma[0]), MakeFloat(cl.Gamma[1]), MakeFloat(cl.Gamma[2])) dict.Set("Gamma", g) } - if this.Matrix != nil { - matrix := MakeArray(MakeFloat(this.Matrix[0]), MakeFloat(this.Matrix[1]), MakeFloat(this.Matrix[2]), - MakeFloat(this.Matrix[3]), MakeFloat(this.Matrix[4]), MakeFloat(this.Matrix[5]), - MakeFloat(this.Matrix[6]), MakeFloat(this.Matrix[7]), MakeFloat(this.Matrix[8])) + if cl.Matrix != nil { + matrix := MakeArray(MakeFloat(cl.Matrix[0]), MakeFloat(cl.Matrix[1]), MakeFloat(cl.Matrix[2]), + MakeFloat(cl.Matrix[3]), MakeFloat(cl.Matrix[4]), MakeFloat(cl.Matrix[5]), + MakeFloat(cl.Matrix[6]), MakeFloat(cl.Matrix[7]), MakeFloat(cl.Matrix[8])) dict.Set("Matrix", matrix) } cspace.Append(dict) - if this.container != nil { - this.container.PdfObject = cspace - return this.container + if cl.container != nil { + cl.container.PdfObject = cspace + return cl.container } return cspace } -func (this *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -1172,7 +1172,7 @@ func (this *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, erro return color, nil } -func (this *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -1182,10 +1182,10 @@ func (this *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfCo return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { calrgb, ok := color.(*PdfColorCalRGB) if !ok { common.Log.Debug("Input color not cal rgb") @@ -1200,9 +1200,9 @@ func (this *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { // A, B, C -> X,Y,Z // Gamma [GR GC GB] // Matrix [XA YA ZA XB YB ZB XC YC ZC] - X := this.Matrix[0]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[3]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[6]*math.Pow(cVal, this.Gamma[2]) - Y := this.Matrix[1]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[4]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[7]*math.Pow(cVal, this.Gamma[2]) - Z := this.Matrix[2]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[5]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[8]*math.Pow(cVal, this.Gamma[2]) + X := cl.Matrix[0]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[3]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[6]*math.Pow(cVal, cl.Gamma[2]) + Y := cl.Matrix[1]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[4]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[7]*math.Pow(cVal, cl.Gamma[2]) + Z := cl.Matrix[2]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[5]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[8]*math.Pow(cVal, cl.Gamma[2]) // X, Y, Z -> R, G, B // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -1218,7 +1218,7 @@ func (this *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { return NewPdfColorDeviceRGB(r, g, b), nil } -func (this *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -1234,9 +1234,9 @@ func (this *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { // A, B, C -> X,Y,Z // Gamma [GR GC GB] // Matrix [XA YA ZA XB YB ZB XC YC ZC] - X := this.Matrix[0]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[3]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[6]*math.Pow(cVal, this.Gamma[2]) - Y := this.Matrix[1]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[4]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[7]*math.Pow(cVal, this.Gamma[2]) - Z := this.Matrix[2]*math.Pow(aVal, this.Gamma[0]) + this.Matrix[5]*math.Pow(bVal, this.Gamma[1]) + this.Matrix[8]*math.Pow(cVal, this.Gamma[2]) + X := cl.Matrix[0]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[3]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[6]*math.Pow(cVal, cl.Gamma[2]) + Y := cl.Matrix[1]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[4]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[7]*math.Pow(cVal, cl.Gamma[2]) + Z := cl.Matrix[2]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[5]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[8]*math.Pow(cVal, cl.Gamma[2]) // X, Y, Z -> R, G, B // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -1273,26 +1273,26 @@ func NewPdfColorLab(l, a, b float64) *PdfColorLab { return &color } -func (this *PdfColorLab) GetNumComponents() int { +func (cl *PdfColorLab) GetNumComponents() int { return 3 } -func (this *PdfColorLab) L() float64 { - return float64(this[0]) +func (cl *PdfColorLab) L() float64 { + return float64(cl[0]) } -func (this *PdfColorLab) A() float64 { - return float64(this[1]) +func (cl *PdfColorLab) A() float64 { + return float64(cl[1]) } -func (this *PdfColorLab) B() float64 { - return float64(this[2]) +func (cl *PdfColorLab) B() float64 { + return float64(cl[2]) } // ToInteger convert to an integer format. -func (this *PdfColorLab) ToInteger(bits int) [3]uint32 { +func (cl *PdfColorLab) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * this.L()), uint32(maxVal * this.A()), uint32(maxVal * this.B())} + return [3]uint32{uint32(maxVal * cl.L()), uint32(maxVal * cl.A()), uint32(maxVal * cl.B())} } // PdfColorspaceLab is a L*, a*, b* 3 component colorspace. @@ -1304,22 +1304,22 @@ type PdfColorspaceLab struct { container *PdfIndirectObject } -func (this *PdfColorspaceLab) String() string { +func (cl *PdfColorspaceLab) String() string { return "Lab" } -func (this *PdfColorspaceLab) GetNumComponents() int { +func (cl *PdfColorspaceLab) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in the Lab colorspace. -func (this *PdfColorspaceLab) DecodeArray() []float64 { +func (cl *PdfColorspaceLab) DecodeArray() []float64 { // Range for L decode := []float64{0, 100} // Range for A,B specified by range or default - if this.Range != nil && len(this.Range) == 4 { - decode = append(decode, this.Range...) + if cl.Range != nil && len(cl.Range) == 4 { + decode = append(decode, cl.Range...) } else { decode = append(decode, -100, 100, -100, 100) } @@ -1430,40 +1430,40 @@ func newPdfColorspaceLabFromPdfObject(obj PdfObject) (*PdfColorspaceLab, error) } // ToPdfObject returns colorspace in a PDF object format [name dictionary] -func (this *PdfColorspaceLab) ToPdfObject() PdfObject { +func (cl *PdfColorspaceLab) ToPdfObject() PdfObject { // CalRGB color space dictionary.. csObj := MakeArray() csObj.Append(MakeName("Lab")) dict := MakeDict() - if this.WhitePoint != nil { - wp := MakeArray(MakeFloat(this.WhitePoint[0]), MakeFloat(this.WhitePoint[1]), MakeFloat(this.WhitePoint[2])) + if cl.WhitePoint != nil { + wp := MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2])) dict.Set("WhitePoint", wp) } else { common.Log.Error("Lab: Missing WhitePoint (Required)") } - if this.BlackPoint != nil { - bp := MakeArray(MakeFloat(this.BlackPoint[0]), MakeFloat(this.BlackPoint[1]), MakeFloat(this.BlackPoint[2])) + if cl.BlackPoint != nil { + bp := MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2])) dict.Set("BlackPoint", bp) } - if this.Range != nil { - val := MakeArray(MakeFloat(this.Range[0]), MakeFloat(this.Range[1]), MakeFloat(this.Range[2]), MakeFloat(this.Range[3])) + if cl.Range != nil { + val := MakeArray(MakeFloat(cl.Range[0]), MakeFloat(cl.Range[1]), MakeFloat(cl.Range[2]), MakeFloat(cl.Range[3])) dict.Set("Range", val) } csObj.Append(dict) - if this.container != nil { - this.container.PdfObject = csObj - return this.container + if cl.container != nil { + cl.container.PdfObject = csObj + return cl.container } return csObj } -func (this *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -1479,9 +1479,9 @@ func (this *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) a := vals[1] aMin := float64(-100) aMax := float64(100) - if len(this.Range) > 1 { - aMin = this.Range[0] - aMax = this.Range[1] + if len(cl.Range) > 1 { + aMin = cl.Range[0] + aMax = cl.Range[1] } if a < aMin || a > aMax { common.Log.Debug("A out of range (got %v; range %v to %v)", a, aMin, aMax) @@ -1492,9 +1492,9 @@ func (this *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) b := vals[2] bMin := float64(-100) bMax := float64(100) - if len(this.Range) > 3 { - bMin = this.Range[2] - bMax = this.Range[3] + if len(cl.Range) > 3 { + bMin = cl.Range[2] + bMax = cl.Range[3] } if b < bMin || b > bMax { common.Log.Debug("b out of range (got %v; range %v to %v)", b, bMin, bMax) @@ -1505,7 +1505,7 @@ func (this *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) return color, nil } -func (this *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -1515,10 +1515,10 @@ func (this *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { gFunc := func(x float64) float64 { if x >= 6.0/29 { return x * x * x @@ -1544,9 +1544,9 @@ func (this *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { N := (LStar+16)/116 - BStar/200 // L, M, N -> X,Y,Z - X := this.WhitePoint[0] * gFunc(L) - Y := this.WhitePoint[1] * gFunc(M) - Z := this.WhitePoint[2] * gFunc(N) + X := cl.WhitePoint[0] * gFunc(L) + Y := cl.WhitePoint[1] * gFunc(M) + Z := cl.WhitePoint[2] * gFunc(N) // Convert to RGB. // X, Y, Z -> R, G, B @@ -1563,7 +1563,7 @@ func (this *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { return NewPdfColorDeviceRGB(r, g, b), nil } -func (this *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { g := func(x float64) float64 { if x >= 6.0/29 { return x * x * x @@ -1583,7 +1583,7 @@ func (this *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { if len(componentRanges) != 6 { // If image's Decode not appropriate, fall back to default decode array. common.Log.Trace("Image - Lab Decode range != 6... use [0 100 amin amax bmin bmax] default decode array") - componentRanges = this.DecodeArray() + componentRanges = cl.DecodeArray() } samples := img.GetSamples() @@ -1606,9 +1606,9 @@ func (this *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { N := (LStar+16)/116 - BStar/200 // L, M, N -> X,Y,Z - X := this.WhitePoint[0] * g(L) - Y := this.WhitePoint[1] * g(M) - Z := this.WhitePoint[2] * g(N) + X := cl.WhitePoint[0] * g(L) + Y := cl.WhitePoint[1] * g(M) + Z := cl.WhitePoint[2] * g(N) // Convert to RGB. // X, Y, Z -> R, G, B @@ -1688,16 +1688,16 @@ type PdfColorspaceICCBased struct { stream *PdfObjectStream } -func (this *PdfColorspaceICCBased) GetNumComponents() int { - return this.N +func (cl *PdfColorspaceICCBased) GetNumComponents() int { + return cl.N } // DecodeArray returns the range of color component values in the ICCBased colorspace. -func (this *PdfColorspaceICCBased) DecodeArray() []float64 { - return this.Range +func (cl *PdfColorspaceICCBased) DecodeArray() []float64 { + return cl.Range } -func (this *PdfColorspaceICCBased) String() string { +func (cl *PdfColorspaceICCBased) String() string { return "ICCBased" } @@ -1802,61 +1802,61 @@ func newPdfColorspaceICCBasedFromPdfObject(obj PdfObject) (*PdfColorspaceICCBase } // ToPdfObject returns colorspace in a PDF object format [name stream] -func (this *PdfColorspaceICCBased) ToPdfObject() PdfObject { +func (cl *PdfColorspaceICCBased) ToPdfObject() PdfObject { csObj := &PdfObjectArray{} csObj.Append(MakeName("ICCBased")) var stream *PdfObjectStream - if this.stream != nil { - stream = this.stream + if cl.stream != nil { + stream = cl.stream } else { stream = &PdfObjectStream{} } dict := MakeDict() - dict.Set("N", MakeInteger(int64(this.N))) + dict.Set("N", MakeInteger(int64(cl.N))) - if this.Alternate != nil { - dict.Set("Alternate", this.Alternate.ToPdfObject()) + if cl.Alternate != nil { + dict.Set("Alternate", cl.Alternate.ToPdfObject()) } - if this.Metadata != nil { - dict.Set("Metadata", this.Metadata) + if cl.Metadata != nil { + dict.Set("Metadata", cl.Metadata) } - if this.Range != nil { + if cl.Range != nil { var ranges []PdfObject - for _, r := range this.Range { + for _, r := range cl.Range { ranges = append(ranges, MakeFloat(r)) } dict.Set("Range", MakeArray(ranges...)) } // Encode with a default encoder? - dict.Set("Length", MakeInteger(int64(len(this.Data)))) + dict.Set("Length", MakeInteger(int64(len(cl.Data)))) // Need to have a representation of the stream... - stream.Stream = this.Data + stream.Stream = cl.Data stream.PdfObjectDictionary = dict csObj.Append(stream) - if this.container != nil { - this.container.PdfObject = csObj - return this.container + if cl.container != nil { + cl.container.PdfObject = csObj + return cl.container } return csObj } -func (this *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, error) { - if this.Alternate == nil { - if this.N == 1 { +func (cl *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, error) { + if cl.Alternate == nil { + if cl.N == 1 { cs := NewPdfColorspaceDeviceGray() return cs.ColorFromFloats(vals) - } else if this.N == 3 { + } else if cl.N == 3 { cs := NewPdfColorspaceDeviceRGB() return cs.ColorFromFloats(vals) - } else if this.N == 4 { + } else if cl.N == 4 { cs := NewPdfColorspaceDeviceCMYK() return cs.ColorFromFloats(vals) } else { @@ -1864,18 +1864,18 @@ func (this *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, er } } - return this.Alternate.ColorFromFloats(vals) + return cl.Alternate.ColorFromFloats(vals) } -func (this *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { - if this.Alternate == nil { - if this.N == 1 { +func (cl *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { + if cl.Alternate == nil { + if cl.N == 1 { cs := NewPdfColorspaceDeviceGray() return cs.ColorFromPdfObjects(objects) - } else if this.N == 3 { + } else if cl.N == 3 { cs := NewPdfColorspaceDeviceRGB() return cs.ColorFromPdfObjects(objects) - } else if this.N == 4 { + } else if cl.N == 4 { cs := NewPdfColorspaceDeviceCMYK() return cs.ColorFromPdfObjects(objects) } else { @@ -1883,10 +1883,10 @@ func (this *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (Pdf } } - return this.Alternate.ColorFromPdfObjects(objects) + return cl.Alternate.ColorFromPdfObjects(objects) } -func (this *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { /* _, ok := color.(*PdfColorICCBased) if !ok { @@ -1895,17 +1895,17 @@ func (this *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) } */ - if this.Alternate == nil { + if cl.Alternate == nil { common.Log.Debug("ICC Based colorspace missing alternative") - if this.N == 1 { + if cl.N == 1 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceGray (N=1)") grayCS := NewPdfColorspaceDeviceGray() return grayCS.ColorToRGB(color) - } else if this.N == 3 { + } else if cl.N == 3 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceRGB (N=3)") // Already in RGB. return color, nil - } else if this.N == 4 { + } else if cl.N == 4 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceCMYK (N=4)") // CMYK cmykCS := NewPdfColorspaceDeviceCMYK() @@ -1915,22 +1915,22 @@ func (this *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) } } - common.Log.Trace("ICC Based colorspace with alternative: %#v", this) - return this.Alternate.ColorToRGB(color) + common.Log.Trace("ICC Based colorspace with alternative: %#v", cl) + return cl.Alternate.ColorToRGB(color) } -func (this *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { - if this.Alternate == nil { +func (cl *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { + if cl.Alternate == nil { common.Log.Debug("ICC Based colorspace missing alternative") - if this.N == 1 { + if cl.N == 1 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceGray (N=1)") grayCS := NewPdfColorspaceDeviceGray() return grayCS.ImageToRGB(img) - } else if this.N == 3 { + } else if cl.N == 3 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceRGB (N=3)") // Already in RGB. return img, nil - } else if this.N == 4 { + } else if cl.N == 4 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceCMYK (N=4)") // CMYK cmykCS := NewPdfColorspaceDeviceCMYK() @@ -1939,12 +1939,12 @@ func (this *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { return img, errors.New("ICC Based colorspace missing alternative") } } - common.Log.Trace("ICC Based colorspace with alternative: %#v", this) + common.Log.Trace("ICC Based colorspace with alternative: %#v", cl) - output, err := this.Alternate.ImageToRGB(img) + output, err := cl.Alternate.ImageToRGB(img) common.Log.Trace("ICC Input image: %+v", img) common.Log.Trace("ICC Output image: %+v", output) - return output, err //this.Alternate.ImageToRGB(img) + return output, err //cl.Alternate.ImageToRGB(img) } ////////////////////// @@ -1967,16 +1967,16 @@ func NewPdfColorspaceSpecialPattern() *PdfColorspaceSpecialPattern { return &PdfColorspaceSpecialPattern{} } -func (this *PdfColorspaceSpecialPattern) String() string { +func (cl *PdfColorspaceSpecialPattern) String() string { return "Pattern" } -func (this *PdfColorspaceSpecialPattern) GetNumComponents() int { - return this.UnderlyingCS.GetNumComponents() +func (cl *PdfColorspaceSpecialPattern) GetNumComponents() int { + return cl.UnderlyingCS.GetNumComponents() } // DecodeArray returns an empty slice as there are no components associated with pattern colorspace. -func (this *PdfColorspaceSpecialPattern) DecodeArray() []float64 { +func (cl *PdfColorspaceSpecialPattern) DecodeArray() []float64 { return []float64{} } @@ -2030,33 +2030,33 @@ func newPdfColorspaceSpecialPatternFromPdfObject(obj PdfObject) (*PdfColorspaceS return cs, nil } -func (this *PdfColorspaceSpecialPattern) ToPdfObject() PdfObject { - if this.UnderlyingCS == nil { +func (cl *PdfColorspaceSpecialPattern) ToPdfObject() PdfObject { + if cl.UnderlyingCS == nil { return MakeName("Pattern") } csObj := MakeArray(MakeName("Pattern")) - csObj.Append(this.UnderlyingCS.ToPdfObject()) + csObj.Append(cl.UnderlyingCS.ToPdfObject()) - if this.container != nil { - this.container.PdfObject = csObj - return this.container + if cl.container != nil { + cl.container.PdfObject = csObj + return cl.container } return csObj } -func (this *PdfColorspaceSpecialPattern) ColorFromFloats(vals []float64) (PdfColor, error) { - if this.UnderlyingCS == nil { +func (cl *PdfColorspaceSpecialPattern) ColorFromFloats(vals []float64) (PdfColor, error) { + if cl.UnderlyingCS == nil { return nil, errors.New("Underlying CS not specified") } - return this.UnderlyingCS.ColorFromFloats(vals) + return cl.UnderlyingCS.ColorFromFloats(vals) } // ColorFromPdfObjects loads the color from PDF objects. // The first objects (if present) represent the color in underlying colorspace. The last one represents // the name of the pattern. -func (this *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) < 1 { return nil, errors.New("Invalid number of parameters") } @@ -2073,11 +2073,11 @@ func (this *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject // Pattern color if specified. if len(objects) > 1 { colorObjs := objects[0 : len(objects)-1] - if this.UnderlyingCS == nil { + if cl.UnderlyingCS == nil { common.Log.Debug("Pattern color with defined color components but underlying cs missing") return nil, errors.New("Underlying CS not defined") } - color, err := this.UnderlyingCS.ColorFromPdfObjects(colorObjs) + color, err := cl.UnderlyingCS.ColorFromPdfObjects(colorObjs) if err != nil { common.Log.Debug("ERROR: Unable to convert color via underlying cs: %v", err) return nil, err @@ -2091,7 +2091,7 @@ func (this *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject // ColorToRGB only converts color used with uncolored patterns (defined in underlying colorspace). Does not go into the // pattern objects and convert those. If that is desired, needs to be done separately. See for example // grayscale conversion example in unidoc-examples repo. -func (this *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cl *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, error) { patternColor, ok := color.(*PdfColorPattern) if !ok { common.Log.Debug("Color not pattern (got %T)", color) @@ -2103,15 +2103,15 @@ func (this *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, e return color, nil } - if this.UnderlyingCS == nil { + if cl.UnderlyingCS == nil { return nil, errors.New("Underlying CS not defined.") } - return this.UnderlyingCS.ColorToRGB(patternColor.Color) + return cl.UnderlyingCS.ColorToRGB(patternColor.Color) } // ImageToRGB returns an error since an image cannot be defined in a pattern colorspace. -func (this *PdfColorspaceSpecialPattern) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceSpecialPattern) ImageToRGB(img Image) (Image, error) { common.Log.Debug("Error: Image cannot be specified in Pattern colorspace") return img, errors.New("Invalid colorspace for image (pattern)") } @@ -2135,17 +2135,17 @@ func NewPdfColorspaceSpecialIndexed() *PdfColorspaceSpecialIndexed { return cs } -func (this *PdfColorspaceSpecialIndexed) String() string { +func (cl *PdfColorspaceSpecialIndexed) String() string { return "Indexed" } -func (this *PdfColorspaceSpecialIndexed) GetNumComponents() int { +func (cl *PdfColorspaceSpecialIndexed) GetNumComponents() int { return 1 } // DecodeArray returns the component range values for the Indexed colorspace. -func (this *PdfColorspaceSpecialIndexed) DecodeArray() []float64 { - return []float64{0, float64(this.HiVal)} +func (cl *PdfColorspaceSpecialIndexed) DecodeArray() []float64 { + return []float64{0, float64(cl.HiVal)} } func newPdfColorspaceSpecialIndexedFromPdfObject(obj PdfObject) (*PdfColorspaceSpecialIndexed, error) { @@ -2238,24 +2238,24 @@ func newPdfColorspaceSpecialIndexedFromPdfObject(obj PdfObject) (*PdfColorspaceS return cs, nil } -func (this *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } - N := this.Base.GetNumComponents() + N := cl.Base.GetNumComponents() index := int(vals[0]) * N - if index < 0 || (index+N-1) >= len(this.colorLookup) { + if index < 0 || (index+N-1) >= len(cl.colorLookup) { return nil, errors.New("Outside range") } - cvals := this.colorLookup[index : index+N] + cvals := cl.colorLookup[index : index+N] var floats []float64 for _, val := range cvals { floats = append(floats, float64(val)/255.0) } - color, err := this.Base.ColorFromFloats(floats) + color, err := cl.Base.ColorFromFloats(floats) if err != nil { return nil, err } @@ -2263,7 +2263,7 @@ func (this *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfCol return color, nil } -func (this *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -2273,19 +2273,19 @@ func (this *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceSpecialIndexed) ColorToRGB(color PdfColor) (PdfColor, error) { - if this.Base == nil { +func (cl *PdfColorspaceSpecialIndexed) ColorToRGB(color PdfColor) (PdfColor, error) { + if cl.Base == nil { return nil, errors.New("Indexed base colorspace undefined") } - return this.Base.ColorToRGB(color) + return cl.Base.ColorToRGB(color) } // ImageToRGB convert an indexed image to RGB. -func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { //baseImage := img // Make a new representation of the image to be converted with the base colorspace. baseImage := Image{} @@ -2297,7 +2297,7 @@ func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { baseImage.ColorComponents = img.ColorComponents samples := img.GetSamples() - N := this.Base.GetNumComponents() + N := cl.Base.GetNumComponents() var baseSamples []uint32 // Convert the indexed data to base color map data. @@ -2307,13 +2307,13 @@ func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { index := int(samples[i]) * N common.Log.Trace("Indexed Index: %d", index) // Ensure does not go out of bounds. - if index+N-1 >= len(this.colorLookup) { + if index+N-1 >= len(cl.colorLookup) { // Clip to the end value. - index = len(this.colorLookup) - N - 1 + index = len(cl.colorLookup) - N - 1 common.Log.Trace("Clipping to index: %d", index) } - cvals := this.colorLookup[index : index+N] + cvals := cl.colorLookup[index : index+N] common.Log.Trace("C Vals: % d", cvals) for _, val := range cvals { baseSamples = append(baseSamples, uint32(val)) @@ -2326,19 +2326,19 @@ func (this *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { common.Log.Trace("-> Output samples: %d", baseSamples) // Convert to rgb. - return this.Base.ImageToRGB(baseImage) + return cl.Base.ImageToRGB(baseImage) } // ToPdfObject converts colorspace to a PDF object. [/Indexed base hival lookup] -func (this *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { +func (cl *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { csObj := MakeArray(MakeName("Indexed")) - csObj.Append(this.Base.ToPdfObject()) - csObj.Append(MakeInteger(int64(this.HiVal))) - csObj.Append(this.Lookup) + csObj.Append(cl.Base.ToPdfObject()) + csObj.Append(MakeInteger(int64(cl.HiVal))) + csObj.Append(cl.Lookup) - if this.container != nil { - this.container.PdfObject = csObj - return this.container + if cl.container != nil { + cl.container.PdfObject = csObj + return cl.container } return csObj @@ -2365,16 +2365,16 @@ func NewPdfColorspaceSpecialSeparation() *PdfColorspaceSpecialSeparation { return cs } -func (this *PdfColorspaceSpecialSeparation) String() string { +func (cl *PdfColorspaceSpecialSeparation) String() string { return "Separation" } -func (this *PdfColorspaceSpecialSeparation) GetNumComponents() int { +func (cl *PdfColorspaceSpecialSeparation) GetNumComponents() int { return 1 } // DecodeArray returns the component range values for the Separation colorspace. -func (this *PdfColorspaceSpecialSeparation) DecodeArray() []float64 { +func (cl *PdfColorspaceSpecialSeparation) DecodeArray() []float64 { return []float64{0, 1.0} } @@ -2436,39 +2436,39 @@ func newPdfColorspaceSpecialSeparationFromPdfObject(obj PdfObject) (*PdfColorspa return cs, nil } -func (this *PdfColorspaceSpecialSeparation) ToPdfObject() PdfObject { +func (cl *PdfColorspaceSpecialSeparation) ToPdfObject() PdfObject { csArray := MakeArray(MakeName("Separation")) - csArray.Append(this.ColorantName) - csArray.Append(this.AlternateSpace.ToPdfObject()) - csArray.Append(this.TintTransform.ToPdfObject()) + csArray.Append(cl.ColorantName) + csArray.Append(cl.AlternateSpace.ToPdfObject()) + csArray.Append(cl.TintTransform.ToPdfObject()) // If in a container, replace the contents and return back. // Helps not getting too many duplicates of the same objects. - if this.container != nil { - this.container.PdfObject = csArray - return this.container + if cl.container != nil { + cl.container.PdfObject = csArray + return cl.container } return csArray } -func (this *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cl *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } tint := vals[0] input := []float64{tint} - output, err := this.TintTransform.Evaluate(input) + output, err := cl.TintTransform.Evaluate(input) if err != nil { common.Log.Debug("Error, failed to evaluate: %v", err) - common.Log.Trace("Tint transform: %+v", this.TintTransform) + common.Log.Trace("Tint transform: %+v", cl.TintTransform) return nil, err } - common.Log.Trace("Processing ColorFromFloats(%+v) on AlternateSpace: %#v", output, this.AlternateSpace) - color, err := this.AlternateSpace.ColorFromFloats(output) + common.Log.Trace("Processing ColorFromFloats(%+v) on AlternateSpace: %#v", output, cl.AlternateSpace) + color, err := cl.AlternateSpace.ColorFromFloats(output) if err != nil { common.Log.Debug("Error, failed to evaluate in alternate space: %v", err) return nil, err @@ -2477,7 +2477,7 @@ func (this *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (Pdf return color, nil } -func (this *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cl *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -2487,21 +2487,21 @@ func (this *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObj return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } // ColorToRGB converts a color in Separation colorspace to RGB colorspace. -func (this *PdfColorspaceSpecialSeparation) ColorToRGB(color PdfColor) (PdfColor, error) { - if this.AlternateSpace == nil { +func (cl *PdfColorspaceSpecialSeparation) ColorToRGB(color PdfColor) (PdfColor, error) { + if cl.AlternateSpace == nil { return nil, errors.New("Alternate colorspace undefined") } - return this.AlternateSpace.ColorToRGB(color) + return cl.AlternateSpace.ColorToRGB(color) } // ImageToRGB converts an image with samples in Separation CS to an image with samples specified in // DeviceRGB CS. -func (this *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { altImage := img samples := img.GetSamples() @@ -2509,9 +2509,9 @@ func (this *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) common.Log.Trace("Separation color space -> ToRGB conversion") common.Log.Trace("samples in: %d", len(samples)) - common.Log.Trace("TintTransform: %+v", this.TintTransform) + common.Log.Trace("TintTransform: %+v", cl.TintTransform) - altDecode := this.AlternateSpace.DecodeArray() + altDecode := cl.AlternateSpace.DecodeArray() var altSamples []uint32 // Convert tints to color data in the alternate colorspace. @@ -2520,8 +2520,8 @@ func (this *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) tint := float64(samples[i]) / maxVal // Convert the tint value to the alternate space value. - outputs, err := this.TintTransform.Evaluate([]float64{tint}) - //common.Log.Trace("%v Converting tint value: %f -> [% f]", this.AlternateSpace, tint, outputs) + outputs, err := cl.TintTransform.Evaluate([]float64{tint}) + //common.Log.Trace("%v Converting tint value: %f -> [% f]", cl.AlternateSpace, tint, outputs) if err != nil { return img, err @@ -2539,13 +2539,13 @@ func (this *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) } common.Log.Trace("Samples out: %d", len(altSamples)) altImage.SetSamples(altSamples) - altImage.ColorComponents = this.AlternateSpace.GetNumComponents() + altImage.ColorComponents = cl.AlternateSpace.GetNumComponents() // Set the image's decode parameters for interpretation in the alternative CS. altImage.decode = altDecode // Convert to RGB via the alternate colorspace. - return this.AlternateSpace.ImageToRGB(altImage) + return cl.AlternateSpace.ImageToRGB(altImage) } // PdfColorspaceDeviceN represents a DeviceN color space. DeviceN color spaces are similar to Separation color @@ -2570,20 +2570,20 @@ func NewPdfColorspaceDeviceN() *PdfColorspaceDeviceN { } // String returns the name of the colorspace (DeviceN). -func (this *PdfColorspaceDeviceN) String() string { +func (cl *PdfColorspaceDeviceN) String() string { return "DeviceN" } // GetNumComponents returns the number of input color components, i.e. that are input to the tint transform. -func (this *PdfColorspaceDeviceN) GetNumComponents() int { - return this.ColorantNames.Len() +func (cl *PdfColorspaceDeviceN) GetNumComponents() int { + return cl.ColorantNames.Len() } // DecodeArray returns the component range values for the DeviceN colorspace. // [0 1.0 0 1.0 ...] for each color component. -func (this *PdfColorspaceDeviceN) DecodeArray() []float64 { +func (cl *PdfColorspaceDeviceN) DecodeArray() []float64 { var decode []float64 - for i := 0; i < this.GetNumComponents(); i++ { + for i := 0; i < cl.GetNumComponents(); i++ { decode = append(decode, 0.0, 1.0) } return decode @@ -2661,35 +2661,35 @@ func newPdfColorspaceDeviceNFromPdfObject(obj PdfObject) (*PdfColorspaceDeviceN, // ToPdfObject returns a *PdfIndirectObject containing a *PdfObjectArray representation of the DeviceN colorspace. // Format: [/DeviceN names alternateSpace tintTransform] // or: [/DeviceN names alternateSpace tintTransform attributes] -func (this *PdfColorspaceDeviceN) ToPdfObject() PdfObject { +func (cl *PdfColorspaceDeviceN) ToPdfObject() PdfObject { csArray := MakeArray(MakeName("DeviceN")) - csArray.Append(this.ColorantNames) - csArray.Append(this.AlternateSpace.ToPdfObject()) - csArray.Append(this.TintTransform.ToPdfObject()) - if this.Attributes != nil { - csArray.Append(this.Attributes.ToPdfObject()) + csArray.Append(cl.ColorantNames) + csArray.Append(cl.AlternateSpace.ToPdfObject()) + csArray.Append(cl.TintTransform.ToPdfObject()) + if cl.Attributes != nil { + csArray.Append(cl.Attributes.ToPdfObject()) } - if this.container != nil { - this.container.PdfObject = csArray - return this.container + if cl.container != nil { + cl.container.PdfObject = csArray + return cl.container } return csArray } // ColorFromFloats returns a new PdfColor based on input color components. -func (this *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, error) { - if len(vals) != this.GetNumComponents() { +func (cl *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, error) { + if len(vals) != cl.GetNumComponents() { return nil, errors.New("Range check") } - output, err := this.TintTransform.Evaluate(vals) + output, err := cl.TintTransform.Evaluate(vals) if err != nil { return nil, err } - color, err := this.AlternateSpace.ColorFromFloats(output) + color, err := cl.AlternateSpace.ColorFromFloats(output) if err != nil { return nil, err } @@ -2698,8 +2698,8 @@ func (this *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, err // ColorFromPdfObjects returns a new PdfColor based on input color components. The input PdfObjects should // be numeric. -func (this *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { - if len(objects) != this.GetNumComponents() { +func (cl *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { + if len(objects) != cl.GetNumComponents() { return nil, errors.New("Range check") } @@ -2708,17 +2708,17 @@ func (this *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfC return nil, err } - return this.ColorFromFloats(floats) + return cl.ColorFromFloats(floats) } -func (this *PdfColorspaceDeviceN) ColorToRGB(color PdfColor) (PdfColor, error) { - if this.AlternateSpace == nil { +func (cl *PdfColorspaceDeviceN) ColorToRGB(color PdfColor) (PdfColor, error) { + if cl.AlternateSpace == nil { return nil, errors.New("DeviceN alternate space undefined") } - return this.AlternateSpace.ColorToRGB(color) + return cl.AlternateSpace.ColorToRGB(color) } -func (this *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { +func (cl *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { altImage := img samples := img.GetSamples() @@ -2726,20 +2726,20 @@ func (this *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { // Convert tints to color data in the alternate colorspace. var altSamples []uint32 - for i := 0; i < len(samples); i += this.GetNumComponents() { + for i := 0; i < len(samples); i += cl.GetNumComponents() { // The input to the tint transformation is the tint // for each color component. // // A single tint component is in the range 0.0 - 1.0 var inputs []float64 - for j := 0; j < this.GetNumComponents(); j++ { + for j := 0; j < cl.GetNumComponents(); j++ { tint := float64(samples[i+j]) / maxVal inputs = append(inputs, tint) } // Transform the tints to the alternate colorspace. // (scaled units). - outputs, err := this.TintTransform.Evaluate(inputs) + outputs, err := cl.TintTransform.Evaluate(inputs) if err != nil { return img, err } @@ -2755,7 +2755,7 @@ func (this *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { altImage.SetSamples(altSamples) // Convert to RGB via the alternate colorspace. - return this.AlternateSpace.ImageToRGB(altImage) + return cl.AlternateSpace.ImageToRGB(altImage) } // PdfColorspaceDeviceNAttributes contains additional information about the components of colour space that @@ -2820,19 +2820,19 @@ func newPdfColorspaceDeviceNAttributesFromPdfObject(obj PdfObject) (*PdfColorspa // ToPdfObject returns a PdfObject representation of PdfColorspaceDeviceNAttributes as a PdfObjectDictionary directly // or indirectly within an indirect object container. -func (this *PdfColorspaceDeviceNAttributes) ToPdfObject() PdfObject { +func (cl *PdfColorspaceDeviceNAttributes) ToPdfObject() PdfObject { dict := MakeDict() - if this.Subtype != nil { - dict.Set("Subtype", this.Subtype) + if cl.Subtype != nil { + dict.Set("Subtype", cl.Subtype) } - dict.SetIfNotNil("Colorants", this.Colorants) - dict.SetIfNotNil("Process", this.Process) - dict.SetIfNotNil("MixingHints", this.MixingHints) + dict.SetIfNotNil("Colorants", cl.Colorants) + dict.SetIfNotNil("Process", cl.Process) + dict.SetIfNotNil("MixingHints", cl.MixingHints) - if this.container != nil { - this.container.PdfObject = dict - return this.container + if cl.container != nil { + cl.container.PdfObject = dict + return cl.container } return dict diff --git a/pdf/model/flatten.go b/pdf/model/flatten.go index 3d0be700..11d76ebb 100644 --- a/pdf/model/flatten.go +++ b/pdf/model/flatten.go @@ -35,12 +35,12 @@ type FieldAppearanceGenerator interface { // When `allannots` is true, all annotations will be flattened. Keep false if want to keep non-form related // annotations intact. // When `appgen` is not nil, it will be used to generate appearance streams for the field annotations. -func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenerator) error { +func (r *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenerator) error { // Load all target widget annotations to be flattened into a map. // The bool value indicates whether the annotation has value content. ftargets := map[*PdfAnnotation]bool{} { - acroForm := pdf.AcroForm + acroForm := r.AcroForm if acroForm == nil { return nil } @@ -68,7 +68,7 @@ func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenera // If all annotations are to be flattened, add to targets. if allannots { - for _, page := range pdf.PageList { + for _, page := range r.PageList { for _, annot := range page.Annotations { ftargets[annot] = true } @@ -76,7 +76,7 @@ func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenera } // Go through all pages and flatten specified annotations. - for _, page := range pdf.PageList { + for _, page := range r.PageList { var annots []*PdfAnnotation // Wrap the content streams. @@ -168,7 +168,7 @@ func (pdf *PdfReader) FlattenFields(allannots bool, appgen FieldAppearanceGenera } } - pdf.AcroForm = nil + r.AcroForm = nil return nil } diff --git a/pdf/model/font.go b/pdf/model/font.go index b92a156c..c33a43e1 100644 --- a/pdf/model/font.go +++ b/pdf/model/font.go @@ -666,36 +666,36 @@ type PdfFontDescriptor struct { } // GetDescent returns the Descent of the font `descriptor`. -func (descriptor *PdfFontDescriptor) GetDescent() (float64, error) { - return core.GetNumberAsFloat(descriptor.Descent) +func (desc *PdfFontDescriptor) GetDescent() (float64, error) { + return core.GetNumberAsFloat(desc.Descent) } // GetAscent returns the Ascent of the font `descriptor`. -func (descriptor *PdfFontDescriptor) GetAscent() (float64, error) { - return core.GetNumberAsFloat(descriptor.Ascent) +func (desc *PdfFontDescriptor) GetAscent() (float64, error) { + return core.GetNumberAsFloat(desc.Ascent) } // GetCapHeight returns the CapHeight of the font `descriptor`. -func (descriptor *PdfFontDescriptor) GetCapHeight() (float64, error) { - return core.GetNumberAsFloat(descriptor.CapHeight) +func (desc *PdfFontDescriptor) GetCapHeight() (float64, error) { + return core.GetNumberAsFloat(desc.CapHeight) } // String returns a string describing the font descriptor. -func (descriptor *PdfFontDescriptor) String() string { +func (desc *PdfFontDescriptor) String() string { var parts []string - if descriptor.FontName != nil { - parts = append(parts, descriptor.FontName.String()) + if desc.FontName != nil { + parts = append(parts, desc.FontName.String()) } - if descriptor.FontFamily != nil { - parts = append(parts, descriptor.FontFamily.String()) + if desc.FontFamily != nil { + parts = append(parts, desc.FontFamily.String()) } - if descriptor.fontFile != nil { - parts = append(parts, descriptor.fontFile.String()) + if desc.fontFile != nil { + parts = append(parts, desc.fontFile.String()) } - if descriptor.fontFile2 != nil { - parts = append(parts, descriptor.fontFile2.String()) + if desc.fontFile2 != nil { + parts = append(parts, desc.fontFile2.String()) } - parts = append(parts, fmt.Sprintf("FontFile3=%t", descriptor.FontFile3 != nil)) + parts = append(parts, fmt.Sprintf("FontFile3=%t", desc.FontFile3 != nil)) return fmt.Sprintf("FONT_DESCRIPTOR{%s}", strings.Join(parts, ", ")) } @@ -779,114 +779,114 @@ func newPdfFontDescriptorFromPdfObject(obj core.PdfObject) (*PdfFontDescriptor, } // ToPdfObject returns the PdfFontDescriptor as a PDF dictionary inside an indirect object. -func (this *PdfFontDescriptor) ToPdfObject() core.PdfObject { +func (desc *PdfFontDescriptor) ToPdfObject() core.PdfObject { d := core.MakeDict() - if this.container == nil { - this.container = &core.PdfIndirectObject{} + if desc.container == nil { + desc.container = &core.PdfIndirectObject{} } - this.container.PdfObject = d + desc.container.PdfObject = d d.Set("Type", core.MakeName("FontDescriptor")) - if this.FontName != nil { - d.Set("FontName", this.FontName) + if desc.FontName != nil { + d.Set("FontName", desc.FontName) } - if this.FontFamily != nil { - d.Set("FontFamily", this.FontFamily) + if desc.FontFamily != nil { + d.Set("FontFamily", desc.FontFamily) } - if this.FontStretch != nil { - d.Set("FontStretch", this.FontStretch) + if desc.FontStretch != nil { + d.Set("FontStretch", desc.FontStretch) } - if this.FontWeight != nil { - d.Set("FontWeight", this.FontWeight) + if desc.FontWeight != nil { + d.Set("FontWeight", desc.FontWeight) } - if this.Flags != nil { - d.Set("Flags", this.Flags) + if desc.Flags != nil { + d.Set("Flags", desc.Flags) } - if this.FontBBox != nil { - d.Set("FontBBox", this.FontBBox) + if desc.FontBBox != nil { + d.Set("FontBBox", desc.FontBBox) } - if this.ItalicAngle != nil { - d.Set("ItalicAngle", this.ItalicAngle) + if desc.ItalicAngle != nil { + d.Set("ItalicAngle", desc.ItalicAngle) } - if this.Ascent != nil { - d.Set("Ascent", this.Ascent) + if desc.Ascent != nil { + d.Set("Ascent", desc.Ascent) } - if this.Descent != nil { - d.Set("Descent", this.Descent) + if desc.Descent != nil { + d.Set("Descent", desc.Descent) } - if this.Leading != nil { - d.Set("Leading", this.Leading) + if desc.Leading != nil { + d.Set("Leading", desc.Leading) } - if this.CapHeight != nil { - d.Set("CapHeight", this.CapHeight) + if desc.CapHeight != nil { + d.Set("CapHeight", desc.CapHeight) } - if this.XHeight != nil { - d.Set("XHeight", this.XHeight) + if desc.XHeight != nil { + d.Set("XHeight", desc.XHeight) } - if this.StemV != nil { - d.Set("StemV", this.StemV) + if desc.StemV != nil { + d.Set("StemV", desc.StemV) } - if this.StemH != nil { - d.Set("StemH", this.StemH) + if desc.StemH != nil { + d.Set("StemH", desc.StemH) } - if this.AvgWidth != nil { - d.Set("AvgWidth", this.AvgWidth) + if desc.AvgWidth != nil { + d.Set("AvgWidth", desc.AvgWidth) } - if this.MaxWidth != nil { - d.Set("MaxWidth", this.MaxWidth) + if desc.MaxWidth != nil { + d.Set("MaxWidth", desc.MaxWidth) } - if this.MissingWidth != nil { - d.Set("MissingWidth", this.MissingWidth) + if desc.MissingWidth != nil { + d.Set("MissingWidth", desc.MissingWidth) } - if this.FontFile != nil { - d.Set("FontFile", this.FontFile) + if desc.FontFile != nil { + d.Set("FontFile", desc.FontFile) } - if this.FontFile2 != nil { - d.Set("FontFile2", this.FontFile2) + if desc.FontFile2 != nil { + d.Set("FontFile2", desc.FontFile2) } - if this.FontFile3 != nil { - d.Set("FontFile3", this.FontFile3) + if desc.FontFile3 != nil { + d.Set("FontFile3", desc.FontFile3) } - if this.CharSet != nil { - d.Set("CharSet", this.CharSet) + if desc.CharSet != nil { + d.Set("CharSet", desc.CharSet) } - if this.Style != nil { - d.Set("FontName", this.FontName) + if desc.Style != nil { + d.Set("FontName", desc.FontName) } - if this.Lang != nil { - d.Set("Lang", this.Lang) + if desc.Lang != nil { + d.Set("Lang", desc.Lang) } - if this.FD != nil { - d.Set("FD", this.FD) + if desc.FD != nil { + d.Set("FD", desc.FD) } - if this.CIDSet != nil { - d.Set("CIDSet", this.CIDSet) + if desc.CIDSet != nil { + d.Set("CIDSet", desc.CIDSet) } - return this.container + return desc.container } diff --git a/pdf/model/fonts/ttfparser.go b/pdf/model/fonts/ttfparser.go index de1eb574..7a7b9bb4 100644 --- a/pdf/model/fonts/ttfparser.go +++ b/pdf/model/fonts/ttfparser.go @@ -45,17 +45,17 @@ import ( ) // MakeEncoder returns an encoder built from the tables in `rec`. -func (rec *TtfType) MakeEncoder() (*textencoding.SimpleEncoder, error) { +func (ttf *TtfType) MakeEncoder() (*textencoding.SimpleEncoder, error) { encoding := make(map[textencoding.CharCode]GlyphName) for code := textencoding.CharCode(0); code <= 256; code++ { r := rune(code) // TODO(dennwc): make sure this conversion is valid - gid, ok := rec.Chars[r] + gid, ok := ttf.Chars[r] if !ok { continue } var glyph GlyphName - if int(gid) >= 0 && int(gid) < len(rec.GlyphNames) { - glyph = rec.GlyphNames[gid] + if int(gid) >= 0 && int(gid) < len(ttf.GlyphNames) { + glyph = ttf.GlyphNames[gid] } else { // TODO(dennwc): shouldn't this be uniXXX? glyph = GlyphName(rune(gid)) @@ -63,8 +63,8 @@ func (rec *TtfType) MakeEncoder() (*textencoding.SimpleEncoder, error) { encoding[code] = glyph } if len(encoding) == 0 { - common.Log.Debug("WARNING: Zero length TrueType enconding. rec=%s Chars=[% 02x]", - rec, rec.Chars) + common.Log.Debug("WARNING: Zero length TrueType enconding. ttf=%s Chars=[% 02x]", + ttf, ttf.Chars) } return textencoding.NewCustomSimpleTextEncoder(encoding, nil) } diff --git a/pdf/model/functions.go b/pdf/model/functions.go index 2d39b65d..1c617b30 100644 --- a/pdf/model/functions.go +++ b/pdf/model/functions.go @@ -226,9 +226,9 @@ func newPdfFunctionType0FromStream(stream *PdfObjectStream) (*PdfFunctionType0, return fun, nil } -func (this *PdfFunctionType0) ToPdfObject() PdfObject { - if this.container == nil { - this.container = &PdfObjectStream{} +func (f *PdfFunctionType0) ToPdfObject() PdfObject { + if f.container == nil { + f.container = &PdfObjectStream{} } dict := MakeDict() @@ -236,66 +236,66 @@ func (this *PdfFunctionType0) ToPdfObject() PdfObject { // Domain (required). domainArray := &PdfObjectArray{} - for _, val := range this.Domain { + for _, val := range f.Domain { domainArray.Append(MakeFloat(val)) } dict.Set("Domain", domainArray) // Range (required). rangeArray := &PdfObjectArray{} - for _, val := range this.Range { + for _, val := range f.Range { rangeArray.Append(MakeFloat(val)) } dict.Set("Range", rangeArray) // Size (required). sizeArray := &PdfObjectArray{} - for _, val := range this.Size { + for _, val := range f.Size { sizeArray.Append(MakeInteger(int64(val))) } dict.Set("Size", sizeArray) - dict.Set("BitsPerSample", MakeInteger(int64(this.BitsPerSample))) + dict.Set("BitsPerSample", MakeInteger(int64(f.BitsPerSample))) - if this.Order != 1 { - dict.Set("Order", MakeInteger(int64(this.Order))) + if f.Order != 1 { + dict.Set("Order", MakeInteger(int64(f.Order))) } // TODO: Encode. // Either here, or automatically later on when writing out. - dict.Set("Length", MakeInteger(int64(len(this.rawData)))) - this.container.Stream = this.rawData + dict.Set("Length", MakeInteger(int64(len(f.rawData)))) + f.container.Stream = f.rawData - this.container.PdfObjectDictionary = dict - return this.container + f.container.PdfObjectDictionary = dict + return f.container } -func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { - if len(x) != this.NumInputs { +func (f *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { + if len(x) != f.NumInputs { common.Log.Error("Number of inputs not matching what is needed") return nil, errors.New("Range check error") } - if this.data == nil { + if f.data == nil { // Process the samples if not already done. - err := this.processSamples() + err := f.processSamples() if err != nil { return nil, err } } // Fall back to default Encode/Decode params if not set. - encode := this.Encode + encode := f.Encode if encode == nil { encode = []float64{} - for i := 0; i < len(this.Size); i++ { + for i := 0; i < len(f.Size); i++ { encode = append(encode, 0) - encode = append(encode, float64(this.Size[i]-1)) + encode = append(encode, float64(f.Size[i]-1)) } } - decode := this.Decode + decode := f.Decode if decode == nil { - decode = this.Range + decode = f.Range } var indices []int @@ -303,10 +303,10 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { for i := 0; i < len(x); i++ { xi := x[i] - xip := math.Min(math.Max(xi, this.Domain[2*i]), this.Domain[2*i+1]) + xip := math.Min(math.Max(xi, f.Domain[2*i]), f.Domain[2*i+1]) - ei := interpolate(xip, this.Domain[2*i], this.Domain[2*i+1], encode[2*i], encode[2*i+1]) - eip := math.Min(math.Max(ei, 0), float64(this.Size[i])) + ei := interpolate(xip, f.Domain[2*i], f.Domain[2*i+1], encode[2*i], encode[2*i+1]) + eip := math.Min(math.Max(ei, 0), float64(f.Size[i])) // eip represents coordinate into the data table. // At this point it is real values. @@ -318,8 +318,8 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { index := int(math.Floor(eip + 0.5)) if index < 0 { index = 0 - } else if index > this.Size[i] { - index = this.Size[i] - 1 + } else if index > f.Size[i] { + index = f.Size[i] - 1 } indices = append(indices, index) @@ -327,21 +327,21 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { // Calculate the index m := indices[0] - for i := 1; i < this.NumInputs; i++ { + for i := 1; i < f.NumInputs; i++ { add := indices[i] for j := 0; j < i; j++ { - add *= this.Size[j] + add *= f.Size[j] } m += add } - m *= this.NumOutputs + m *= f.NumOutputs // Output values. var outputs []float64 - for j := 0; j < this.NumOutputs; j++ { - rj := this.data[m+j] - rjp := interpolate(float64(rj), 0, math.Pow(2, float64(this.BitsPerSample)), decode[2*j], decode[2*j+1]) - yj := math.Min(math.Max(rjp, this.Range[2*j]), this.Range[2*j+1]) + for j := 0; j < f.NumOutputs; j++ { + rj := f.data[m+j] + rjp := interpolate(float64(rj), 0, math.Pow(2, float64(f.BitsPerSample)), decode[2*j], decode[2*j+1]) + yj := math.Min(math.Max(rjp, f.Range[2*j]), f.Range[2*j+1]) outputs = append(outputs, yj) } @@ -351,9 +351,9 @@ func (this *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { // Convert raw data to data table. The maximum supported BitsPerSample is 32, so we store the resulting data // in a uint32 array. This is somewhat wasteful in the case of a small BitsPerSample, but these tables are // presumably not huge at any rate. -func (this *PdfFunctionType0) processSamples() error { - data := sampling.ResampleBytes(this.rawData, this.BitsPerSample) - this.data = data +func (f *PdfFunctionType0) processSamples() error { + data := sampling.ResampleBytes(f.rawData, f.BitsPerSample) + f.data = data return nil } @@ -462,59 +462,59 @@ func newPdfFunctionType2FromPdfObject(obj PdfObject) (*PdfFunctionType2, error) return fun, nil } -func (this *PdfFunctionType2) ToPdfObject() PdfObject { +func (f *PdfFunctionType2) ToPdfObject() PdfObject { dict := MakeDict() dict.Set("FunctionType", MakeInteger(2)) // Domain (required). domainArray := &PdfObjectArray{} - for _, val := range this.Domain { + for _, val := range f.Domain { domainArray.Append(MakeFloat(val)) } dict.Set("Domain", domainArray) // Range (required). - if this.Range != nil { + if f.Range != nil { rangeArray := &PdfObjectArray{} - for _, val := range this.Range { + for _, val := range f.Range { rangeArray.Append(MakeFloat(val)) } dict.Set("Range", rangeArray) } // C0. - if this.C0 != nil { + if f.C0 != nil { c0Array := &PdfObjectArray{} - for _, val := range this.C0 { + for _, val := range f.C0 { c0Array.Append(MakeFloat(val)) } dict.Set("C0", c0Array) } // C1. - if this.C1 != nil { + if f.C1 != nil { c1Array := &PdfObjectArray{} - for _, val := range this.C1 { + for _, val := range f.C1 { c1Array.Append(MakeFloat(val)) } dict.Set("C1", c1Array) } // exponent - dict.Set("N", MakeFloat(this.N)) + dict.Set("N", MakeFloat(f.N)) // Wrap in a container if we have one already specified. - if this.container != nil { - this.container.PdfObject = dict - return this.container + if f.container != nil { + f.container.PdfObject = dict + return f.container } else { return dict } } -func (this *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) { +func (f *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) { if len(x) != 1 { common.Log.Error("Only one input allowed") return nil, errors.New("Range check") @@ -522,17 +522,17 @@ func (this *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) { // Prepare. c0 := []float64{0.0} - if this.C0 != nil { - c0 = this.C0 + if f.C0 != nil { + c0 = f.C0 } c1 := []float64{1.0} - if this.C1 != nil { - c1 = this.C1 + if f.C1 != nil { + c1 = f.C1 } var y []float64 for i := 0; i < len(c0); i++ { - yi := c0[i] + math.Pow(x[0], this.N)*(c1[i]-c0[i]) + yi := c0[i] + math.Pow(x[0], f.N)*(c1[i]-c0[i]) y = append(y, yi) } @@ -552,7 +552,7 @@ type PdfFunctionType3 struct { container *PdfIndirectObject } -func (this *PdfFunctionType3) Evaluate(x []float64) ([]float64, error) { +func (f *PdfFunctionType3) Evaluate(x []float64) ([]float64, error) { if len(x) != 1 { common.Log.Error("Only one input allowed") return nil, errors.New("Range check") @@ -661,58 +661,58 @@ func newPdfFunctionType3FromPdfObject(obj PdfObject) (*PdfFunctionType3, error) return fun, nil } -func (this *PdfFunctionType3) ToPdfObject() PdfObject { +func (f *PdfFunctionType3) ToPdfObject() PdfObject { dict := MakeDict() dict.Set("FunctionType", MakeInteger(3)) // Domain (required). domainArray := &PdfObjectArray{} - for _, val := range this.Domain { + for _, val := range f.Domain { domainArray.Append(MakeFloat(val)) } dict.Set("Domain", domainArray) // Range (required). - if this.Range != nil { + if f.Range != nil { rangeArray := &PdfObjectArray{} - for _, val := range this.Range { + for _, val := range f.Range { rangeArray.Append(MakeFloat(val)) } dict.Set("Range", rangeArray) } // Functions - if this.Functions != nil { + if f.Functions != nil { fArray := &PdfObjectArray{} - for _, fun := range this.Functions { + for _, fun := range f.Functions { fArray.Append(fun.ToPdfObject()) } dict.Set("Functions", fArray) } // Bounds. - if this.Bounds != nil { + if f.Bounds != nil { bArray := &PdfObjectArray{} - for _, val := range this.Bounds { + for _, val := range f.Bounds { bArray.Append(MakeFloat(val)) } dict.Set("Bounds", bArray) } // Encode. - if this.Encode != nil { + if f.Encode != nil { eArray := &PdfObjectArray{} - for _, val := range this.Encode { + for _, val := range f.Encode { eArray.Append(MakeFloat(val)) } dict.Set("Encode", eArray) } // Wrap in a container if we have one already specified. - if this.container != nil { - this.container.PdfObject = dict - return this.container + if f.container != nil { + f.container.PdfObject = dict + return f.container } else { return dict } @@ -731,9 +731,9 @@ type PdfFunctionType4 struct { } // Evaluate runs the function. Input is [x1 x2 x3]. -func (this *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) { - if this.executor == nil { - this.executor = ps.NewPSExecutor(this.Program) +func (f *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) { + if f.executor == nil { + f.executor = ps.NewPSExecutor(f.Program) } var inputs []ps.PSObject @@ -741,7 +741,7 @@ func (this *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) { inputs = append(inputs, ps.MakeReal(val)) } - outputs, err := this.executor.Execute(inputs) + outputs, err := f.executor.Execute(inputs) if err != nil { return nil, err } @@ -810,11 +810,11 @@ func newPdfFunctionType4FromStream(stream *PdfObjectStream) (*PdfFunctionType4, return fun, nil } -func (this *PdfFunctionType4) ToPdfObject() PdfObject { - container := this.container +func (f *PdfFunctionType4) ToPdfObject() PdfObject { + container := f.container if container == nil { - this.container = &PdfObjectStream{} - container = this.container + f.container = &PdfObjectStream{} + container = f.container } dict := MakeDict() @@ -822,28 +822,28 @@ func (this *PdfFunctionType4) ToPdfObject() PdfObject { // Domain (required). domainArray := &PdfObjectArray{} - for _, val := range this.Domain { + for _, val := range f.Domain { domainArray.Append(MakeFloat(val)) } dict.Set("Domain", domainArray) // Range (required). rangeArray := &PdfObjectArray{} - for _, val := range this.Range { + for _, val := range f.Range { rangeArray.Append(MakeFloat(val)) } dict.Set("Range", rangeArray) - if this.decodedData == nil && this.Program != nil { + if f.decodedData == nil && f.Program != nil { // Update data. This is used for created functions (not parsed ones). - this.decodedData = []byte(this.Program.String()) + f.decodedData = []byte(f.Program.String()) } // TODO: Encode. // Either here, or automatically later on when writing out. - dict.Set("Length", MakeInteger(int64(len(this.decodedData)))) + dict.Set("Length", MakeInteger(int64(len(f.decodedData)))) - container.Stream = this.decodedData + container.Stream = f.decodedData container.PdfObjectDictionary = dict return container diff --git a/pdf/model/outlines.go b/pdf/model/outlines.go index 95ac108c..4cd69779 100644 --- a/pdf/model/outlines.go +++ b/pdf/model/outlines.go @@ -125,7 +125,7 @@ func newPdfOutlineFromIndirectObject(container *PdfIndirectObject) (*PdfOutline, } // Does not traverse the tree. -func (this *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirectObject) (*PdfOutlineItem, error) { +func (r *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirectObject) (*PdfOutlineItem, error) { dict, isDict := container.PdfObject.(*PdfObjectDictionary) if !isDict { return nil, fmt.Errorf("Outline object not a dictionary") @@ -140,7 +140,7 @@ func (this *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirec if obj == nil { return nil, fmt.Errorf("Missing Title from Outline Item (required)") } - obj, err := this.traceToObject(obj) + obj, err := r.traceToObject(obj) if err != nil { return nil, err } @@ -162,21 +162,21 @@ func (this *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirec // Other keys. if obj := dict.Get("Dest"); obj != nil { - item.Dest, err = this.traceToObject(obj) + item.Dest, err = r.traceToObject(obj) if err != nil { return nil, err } - err := this.traverseObjectData(item.Dest) + err := r.traverseObjectData(item.Dest) if err != nil { return nil, err } } if obj := dict.Get("A"); obj != nil { - item.A, err = this.traceToObject(obj) + item.A, err = r.traceToObject(obj) if err != nil { return nil, err } - err := this.traverseObjectData(item.A) + err := r.traverseObjectData(item.A) if err != nil { return nil, err } @@ -186,20 +186,20 @@ func (this *PdfReader) newPdfOutlineItemFromIndirectObject(container *PdfIndirec // Currently not supporting structure elements. item.SE = nil /* - item.SE, err = this.traceToObject(obj) + item.SE, err = r.traceToObject(obj) if err != nil { return nil, err } */ } if obj := dict.Get("C"); obj != nil { - item.C, err = this.traceToObject(obj) + item.C, err = r.traceToObject(obj) if err != nil { return nil, err } } if obj := dict.Get("F"); obj != nil { - item.F, err = this.traceToObject(obj) + item.F, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -221,53 +221,53 @@ func (n *PdfOutlineTreeNode) getOuter() PdfModel { return nil } -func (this *PdfOutlineTreeNode) GetContainingPdfObject() PdfObject { - return this.getOuter().GetContainingPdfObject() +func (n *PdfOutlineTreeNode) GetContainingPdfObject() PdfObject { + return n.getOuter().GetContainingPdfObject() } -func (this *PdfOutlineTreeNode) ToPdfObject() PdfObject { - return this.getOuter().ToPdfObject() +func (n *PdfOutlineTreeNode) ToPdfObject() PdfObject { + return n.getOuter().ToPdfObject() } -func (this *PdfOutline) GetContainingPdfObject() PdfObject { - return this.primitive +func (o *PdfOutline) GetContainingPdfObject() PdfObject { + return o.primitive } // ToPdfObject recursively builds the Outline tree PDF object. -func (this *PdfOutline) ToPdfObject() PdfObject { - container := this.primitive +func (o *PdfOutline) ToPdfObject() PdfObject { + container := o.primitive dict := container.PdfObject.(*PdfObjectDictionary) dict.Set("Type", MakeName("Outlines")) - if this.First != nil { - dict.Set("First", this.First.ToPdfObject()) + if o.First != nil { + dict.Set("First", o.First.ToPdfObject()) } - if this.Last != nil { - dict.Set("Last", this.Last.getOuter().GetContainingPdfObject()) - //PdfObjectConverterCache[this.Last.getOuter()] + if o.Last != nil { + dict.Set("Last", o.Last.getOuter().GetContainingPdfObject()) + //PdfObjectConverterCache[o.Last.getOuter()] } - if this.Parent != nil { - dict.Set("Parent", this.Parent.getOuter().GetContainingPdfObject()) + if o.Parent != nil { + dict.Set("Parent", o.Parent.getOuter().GetContainingPdfObject()) } return container } -func (this *PdfOutlineItem) GetContainingPdfObject() PdfObject { - return this.primitive +func (o *PdfOutlineItem) GetContainingPdfObject() PdfObject { + return o.primitive } // ToPdfObject recursively builds the Outline tree PDF object. -func (this *PdfOutlineItem) ToPdfObject() PdfObject { - container := this.primitive +func (o *PdfOutlineItem) ToPdfObject() PdfObject { + container := o.primitive dict := container.PdfObject.(*PdfObjectDictionary) - dict.Set("Title", this.Title) - if this.A != nil { - dict.Set("A", this.A) + dict.Set("Title", o.Title) + if o.A != nil { + dict.Set("A", o.A) } if obj := dict.Get("SE"); obj != nil { // TODO: Currently not supporting structure element hierarchy. @@ -276,39 +276,39 @@ func (this *PdfOutlineItem) ToPdfObject() PdfObject { // delete(*dict, "SE") } /* - if this.SE != nil { - (*dict)["SE"] = this.SE + if o.SE != nil { + (*dict)["SE"] = o.SE } */ - if this.C != nil { - dict.Set("C", this.C) + if o.C != nil { + dict.Set("C", o.C) } - if this.Dest != nil { - dict.Set("Dest", this.Dest) + if o.Dest != nil { + dict.Set("Dest", o.Dest) } - if this.F != nil { - dict.Set("F", this.F) + if o.F != nil { + dict.Set("F", o.F) } - if this.Count != nil { - dict.Set("Count", MakeInteger(*this.Count)) + if o.Count != nil { + dict.Set("Count", MakeInteger(*o.Count)) } - if this.Next != nil { - dict.Set("Next", this.Next.ToPdfObject()) + if o.Next != nil { + dict.Set("Next", o.Next.ToPdfObject()) } - if this.First != nil { - dict.Set("First", this.First.ToPdfObject()) + if o.First != nil { + dict.Set("First", o.First.ToPdfObject()) } - if this.Prev != nil { - dict.Set("Prev", this.Prev.getOuter().GetContainingPdfObject()) - //PdfObjectConverterCache[this.Prev.getOuter()] + if o.Prev != nil { + dict.Set("Prev", o.Prev.getOuter().GetContainingPdfObject()) + //PdfObjectConverterCache[o.Prev.getOuter()] } - if this.Last != nil { - dict.Set("Last", this.Last.getOuter().GetContainingPdfObject()) - // PdfObjectConverterCache[this.Last.getOuter()] + if o.Last != nil { + dict.Set("Last", o.Last.getOuter().GetContainingPdfObject()) + // PdfObjectConverterCache[o.Last.getOuter()] } - if this.Parent != nil { - dict.Set("Parent", this.Parent.getOuter().GetContainingPdfObject()) - //PdfObjectConverterCache[this.Parent.getOuter()] + if o.Parent != nil { + dict.Set("Parent", o.Parent.getOuter().GetContainingPdfObject()) + //PdfObjectConverterCache[o.Parent.getOuter()] } return container diff --git a/pdf/model/page.go b/pdf/model/page.go index bbcee163..8878811a 100644 --- a/pdf/model/page.go +++ b/pdf/model/page.go @@ -71,14 +71,14 @@ func NewPdfPage() *PdfPage { return &page } -func (this *PdfPage) setContainer(container *PdfIndirectObject) { - container.PdfObject = this.pageDict - this.primitive = container +func (p *PdfPage) setContainer(container *PdfIndirectObject) { + container.PdfObject = p.pageDict + p.primitive = container } -func (this *PdfPage) Duplicate() *PdfPage { +func (p *PdfPage) Duplicate() *PdfPage { var dup PdfPage - dup = *this + dup = *p dup.pageDict = MakeDict() dup.primitive = MakeIndirectObject(dup.pageDict) @@ -88,7 +88,7 @@ func (this *PdfPage) Duplicate() *PdfPage { // Build a PdfPage based on the underlying dictionary. // Used in loading existing PDF files. // Note that a new container is created (indirect object). -func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, error) { +func (r *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, error) { page := NewPdfPage() page.pageDict = p // TODO @@ -108,7 +108,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e if obj := d.Get("LastModified"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -125,7 +125,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e if obj := d.Get("Resources"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -154,7 +154,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e if obj := d.Get("MediaBox"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -169,7 +169,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } if obj := d.Get("CropBox"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -184,7 +184,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } if obj := d.Get("BleedBox"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -199,7 +199,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } if obj := d.Get("TrimBox"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -214,7 +214,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } if obj := d.Get("ArtBox"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -235,7 +235,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } if obj := d.Get("Rotate"); obj != nil { var err error - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -302,7 +302,7 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e } var err error - page.Annotations, err = reader.LoadAnnotations(&d) + page.Annotations, err = r.LoadAnnotations(&d) if err != nil { return nil, err } @@ -310,14 +310,14 @@ func (reader *PdfReader) newPdfPageFromDict(p *PdfObjectDictionary) (*PdfPage, e return page, nil } -func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotation, error) { +func (r *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotation, error) { annotsObj := d.Get("Annots") if annotsObj == nil { return nil, nil } var err error - annotsObj, err = reader.traceToObject(annotsObj) + annotsObj, err = r.traceToObject(annotsObj) if err != nil { return nil, err } @@ -328,7 +328,7 @@ func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotati var annotations []*PdfAnnotation for _, obj := range annotsArr.Elements() { - obj, err = reader.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -352,7 +352,7 @@ func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotati } } - annot, err := reader.newPdfAnnotationFromIndirectObject(indirectObj) + annot, err := r.newPdfAnnotationFromIndirectObject(indirectObj) if err != nil { return nil, err } @@ -364,12 +364,12 @@ func (reader *PdfReader) LoadAnnotations(d *PdfObjectDictionary) ([]*PdfAnnotati // GetMediaBox gets the inheritable media box value, either from the page // or a higher up page/pages struct. -func (this *PdfPage) GetMediaBox() (*PdfRectangle, error) { - if this.MediaBox != nil { - return this.MediaBox, nil +func (p *PdfPage) GetMediaBox() (*PdfRectangle, error) { + if p.MediaBox != nil { + return p.MediaBox, nil } - node := this.Parent + node := p.Parent for node != nil { dictObj, ok := node.(*PdfIndirectObject) if !ok { @@ -402,12 +402,12 @@ func (this *PdfPage) GetMediaBox() (*PdfRectangle, error) { } // Get the inheritable resources, either from the page or or a higher up page/pages struct. -func (this *PdfPage) getResources() (*PdfPageResources, error) { - if this.Resources != nil { - return this.Resources, nil +func (p *PdfPage) getResources() (*PdfPageResources, error) { + if p.Resources != nil { + return p.Resources, nil } - node := this.Parent + node := p.Parent for node != nil { dictObj, ok := node.(*PdfIndirectObject) if !ok { @@ -442,61 +442,61 @@ func (this *PdfPage) getResources() (*PdfPageResources, error) { } // GetPageDict convert the Page to a PDF object dictionary. -func (this *PdfPage) GetPageDict() *PdfObjectDictionary { - p := this.pageDict - p.Clear() - p.Set("Type", MakeName("Page")) - p.Set("Parent", this.Parent) +func (p *PdfPage) GetPageDict() *PdfObjectDictionary { + d := p.pageDict + d.Clear() + d.Set("Type", MakeName("Page")) + d.Set("Parent", p.Parent) - if this.LastModified != nil { - p.Set("LastModified", this.LastModified.ToPdfObject()) + if p.LastModified != nil { + d.Set("LastModified", p.LastModified.ToPdfObject()) } - if this.Resources != nil { - p.Set("Resources", this.Resources.ToPdfObject()) + if p.Resources != nil { + d.Set("Resources", p.Resources.ToPdfObject()) } - if this.CropBox != nil { - p.Set("CropBox", this.CropBox.ToPdfObject()) + if p.CropBox != nil { + d.Set("CropBox", p.CropBox.ToPdfObject()) } - if this.MediaBox != nil { - p.Set("MediaBox", this.MediaBox.ToPdfObject()) + if p.MediaBox != nil { + d.Set("MediaBox", p.MediaBox.ToPdfObject()) } - if this.BleedBox != nil { - p.Set("BleedBox", this.BleedBox.ToPdfObject()) + if p.BleedBox != nil { + d.Set("BleedBox", p.BleedBox.ToPdfObject()) } - if this.TrimBox != nil { - p.Set("TrimBox", this.TrimBox.ToPdfObject()) + if p.TrimBox != nil { + d.Set("TrimBox", p.TrimBox.ToPdfObject()) } - if this.ArtBox != nil { - p.Set("ArtBox", this.ArtBox.ToPdfObject()) + if p.ArtBox != nil { + d.Set("ArtBox", p.ArtBox.ToPdfObject()) } - p.SetIfNotNil("BoxColorInfo", this.BoxColorInfo) - p.SetIfNotNil("Contents", this.Contents) + d.SetIfNotNil("BoxColorInfo", p.BoxColorInfo) + d.SetIfNotNil("Contents", p.Contents) - if this.Rotate != nil { - p.Set("Rotate", MakeInteger(*this.Rotate)) + if p.Rotate != nil { + d.Set("Rotate", MakeInteger(*p.Rotate)) } - p.SetIfNotNil("Group", this.Group) - p.SetIfNotNil("Thumb", this.Thumb) - p.SetIfNotNil("B", this.B) - p.SetIfNotNil("Dur", this.Dur) - p.SetIfNotNil("Trans", this.Trans) - p.SetIfNotNil("AA", this.AA) - p.SetIfNotNil("Metadata", this.Metadata) - p.SetIfNotNil("PieceInfo", this.PieceInfo) - p.SetIfNotNil("StructParents", this.StructParents) - p.SetIfNotNil("ID", this.ID) - p.SetIfNotNil("PZ", this.PZ) - p.SetIfNotNil("SeparationInfo", this.SeparationInfo) - p.SetIfNotNil("Tabs", this.Tabs) - p.SetIfNotNil("TemplateInstantiated", this.TemplateInstantiated) - p.SetIfNotNil("PresSteps", this.PresSteps) - p.SetIfNotNil("UserUnit", this.UserUnit) - p.SetIfNotNil("VP", this.VP) + d.SetIfNotNil("Group", p.Group) + d.SetIfNotNil("Thumb", p.Thumb) + d.SetIfNotNil("B", p.B) + d.SetIfNotNil("Dur", p.Dur) + d.SetIfNotNil("Trans", p.Trans) + d.SetIfNotNil("AA", p.AA) + d.SetIfNotNil("Metadata", p.Metadata) + d.SetIfNotNil("PieceInfo", p.PieceInfo) + d.SetIfNotNil("StructParents", p.StructParents) + d.SetIfNotNil("ID", p.ID) + d.SetIfNotNil("PZ", p.PZ) + d.SetIfNotNil("SeparationInfo", p.SeparationInfo) + d.SetIfNotNil("Tabs", p.Tabs) + d.SetIfNotNil("TemplateInstantiated", p.TemplateInstantiated) + d.SetIfNotNil("PresSteps", p.PresSteps) + d.SetIfNotNil("UserUnit", p.UserUnit) + d.SetIfNotNil("VP", p.VP) - if this.Annotations != nil { + if p.Annotations != nil { arr := MakeArray() - for _, annot := range this.Annotations { + for _, annot := range p.Annotations { if subannot := annot.GetContext(); subannot != nil { arr.Append(subannot.ToPdfObject()) } else { @@ -504,38 +504,38 @@ func (this *PdfPage) GetPageDict() *PdfObjectDictionary { arr.Append(annot.ToPdfObject()) } } - p.Set("Annots", arr) + d.Set("Annots", arr) } - return p + return d } // GetPageAsIndirectObject returns the page as a dictionary within an PdfIndirectObject. -func (this *PdfPage) GetPageAsIndirectObject() *PdfIndirectObject { - return this.primitive +func (p *PdfPage) GetPageAsIndirectObject() *PdfIndirectObject { + return p.primitive } // GetContainingPdfObject returns the page as a dictionary within an PdfIndirectObject. -func (this *PdfPage) GetContainingPdfObject() PdfObject { - return this.primitive +func (p *PdfPage) GetContainingPdfObject() PdfObject { + return p.primitive } // ToPdfObject converts the PdfPage to a dictionary within an indirect object container. -func (this *PdfPage) ToPdfObject() PdfObject { - container := this.primitive - this.GetPageDict() // update. +func (p *PdfPage) ToPdfObject() PdfObject { + container := p.primitive + p.GetPageDict() // update. return container } // AddImageResource adds an image to the XObject resources. -func (this *PdfPage) AddImageResource(name PdfObjectName, ximg *XObjectImage) error { +func (p *PdfPage) AddImageResource(name PdfObjectName, ximg *XObjectImage) error { var xresDict *PdfObjectDictionary - if this.Resources.XObject == nil { + if p.Resources.XObject == nil { xresDict = MakeDict() - this.Resources.XObject = xresDict + p.Resources.XObject = xresDict } else { var ok bool - xresDict, ok = (this.Resources.XObject).(*PdfObjectDictionary) + xresDict, ok = (p.Resources.XObject).(*PdfObjectDictionary) if !ok { return errors.New("Invalid xres dict type") } @@ -548,8 +548,8 @@ func (this *PdfPage) AddImageResource(name PdfObjectName, ximg *XObjectImage) er } // HasXObjectByName checks if has XObject resource by name. -func (this *PdfPage) HasXObjectByName(name PdfObjectName) bool { - xresDict, has := this.Resources.XObject.(*PdfObjectDictionary) +func (p *PdfPage) HasXObjectByName(name PdfObjectName) bool { + xresDict, has := p.Resources.XObject.(*PdfObjectDictionary) if !has { return false } @@ -562,8 +562,8 @@ func (this *PdfPage) HasXObjectByName(name PdfObjectName) bool { } // GetXObjectByName get XObject by name. -func (this *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { - xresDict, has := this.Resources.XObject.(*PdfObjectDictionary) +func (p *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { + xresDict, has := p.Resources.XObject.(*PdfObjectDictionary) if !has { return nil, false } @@ -576,8 +576,8 @@ func (this *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { } // HasFontByName checks if has font resource by name. -func (this *PdfPage) HasFontByName(name PdfObjectName) bool { - fontDict, has := this.Resources.Font.(*PdfObjectDictionary) +func (p *PdfPage) HasFontByName(name PdfObjectName) bool { + fontDict, has := p.Resources.Font.(*PdfObjectDictionary) if !has { return false } @@ -590,18 +590,18 @@ func (this *PdfPage) HasFontByName(name PdfObjectName) bool { } // HasExtGState checks if ExtGState name is available. -func (this *PdfPage) HasExtGState(name PdfObjectName) bool { - if this.Resources == nil { +func (p *PdfPage) HasExtGState(name PdfObjectName) bool { + if p.Resources == nil { return false } - if this.Resources.ExtGState == nil { + if p.Resources.ExtGState == nil { return false } - egsDict, ok := TraceToDirectObject(this.Resources.ExtGState).(*PdfObjectDictionary) + egsDict, ok := TraceToDirectObject(p.Resources.ExtGState).(*PdfObjectDictionary) if !ok { - common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", TraceToDirectObject(this.Resources.ExtGState)) + common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", TraceToDirectObject(p.Resources.ExtGState)) return false } @@ -613,19 +613,19 @@ func (this *PdfPage) HasExtGState(name PdfObjectName) bool { } // AddExtGState adds a graphics state to the XObject resources. -func (this *PdfPage) AddExtGState(name PdfObjectName, egs *PdfObjectDictionary) error { - if this.Resources == nil { - //this.Resources = &PdfPageResources{} - this.Resources = NewPdfPageResources() +func (p *PdfPage) AddExtGState(name PdfObjectName, egs *PdfObjectDictionary) error { + if p.Resources == nil { + //p.Resources = &PdfPageResources{} + p.Resources = NewPdfPageResources() } - if this.Resources.ExtGState == nil { - this.Resources.ExtGState = MakeDict() + if p.Resources.ExtGState == nil { + p.Resources.ExtGState = MakeDict() } - egsDict, ok := TraceToDirectObject(this.Resources.ExtGState).(*PdfObjectDictionary) + egsDict, ok := TraceToDirectObject(p.Resources.ExtGState).(*PdfObjectDictionary) if !ok { - common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", TraceToDirectObject(this.Resources.ExtGState)) + common.Log.Debug("Expected ExtGState dictionary is not a dictionary: %v", TraceToDirectObject(p.Resources.ExtGState)) return errors.New("Type check error") } @@ -634,18 +634,18 @@ func (this *PdfPage) AddExtGState(name PdfObjectName, egs *PdfObjectDictionary) } // AddFont adds a font dictionary to the Font resources. -func (this *PdfPage) AddFont(name PdfObjectName, font PdfObject) error { - if this.Resources == nil { - this.Resources = NewPdfPageResources() +func (p *PdfPage) AddFont(name PdfObjectName, font PdfObject) error { + if p.Resources == nil { + p.Resources = NewPdfPageResources() } - if this.Resources.Font == nil { - this.Resources.Font = MakeDict() + if p.Resources.Font == nil { + p.Resources.Font = MakeDict() } - fontDict, ok := TraceToDirectObject(this.Resources.Font).(*PdfObjectDictionary) + fontDict, ok := TraceToDirectObject(p.Resources.Font).(*PdfObjectDictionary) if !ok { - common.Log.Debug("Expected font dictionary is not a dictionary: %v", TraceToDirectObject(this.Resources.Font)) + common.Log.Debug("Expected font dictionary is not a dictionary: %v", TraceToDirectObject(p.Resources.Font)) return errors.New("Type check error") } @@ -662,9 +662,9 @@ type WatermarkImageOptions struct { } // AddWatermarkImage add a watermark to the page. -func (this *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOptions) error { +func (p *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOptions) error { // Page dimensions. - bbox, err := this.GetMediaBox() + bbox, err := p.GetMediaBox() if err != nil { return err } @@ -684,26 +684,26 @@ func (this *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOpt yOffset = (pHeight - wHeight) / 2 } - if this.Resources == nil { - this.Resources = NewPdfPageResources() + if p.Resources == nil { + p.Resources = NewPdfPageResources() } // Find available image name for this page. i := 0 imgName := PdfObjectName(fmt.Sprintf("Imw%d", i)) - for this.Resources.HasXObjectByName(imgName) { + for p.Resources.HasXObjectByName(imgName) { i++ imgName = PdfObjectName(fmt.Sprintf("Imw%d", i)) } - err = this.AddImageResource(imgName, ximg) + err = p.AddImageResource(imgName, ximg) if err != nil { return err } i = 0 gsName := PdfObjectName(fmt.Sprintf("GS%d", i)) - for this.HasExtGState(gsName) { + for p.HasExtGState(gsName) { i++ gsName = PdfObjectName(fmt.Sprintf("GS%d", i)) } @@ -711,7 +711,7 @@ func (this *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOpt gs0.Set("BM", MakeName("Normal")) gs0.Set("CA", MakeFloat(opt.Alpha)) gs0.Set("ca", MakeFloat(opt.Alpha)) - err = this.AddExtGState(gsName, gs0) + err = p.AddExtGState(gsName, gs0) if err != nil { return err } @@ -721,29 +721,29 @@ func (this *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOpt "%.0f 0 0 %.0f %.4f %.4f cm\n"+ "/%s Do\n"+ "Q", gsName, wWidth, wHeight, xOffset, yOffset, imgName) - this.AddContentStreamByString(contentStr) + p.AddContentStreamByString(contentStr) return nil } // AddContentStreamByString adds content stream by string. Puts the content string into a stream // object and points the content stream towards it. -func (this *PdfPage) AddContentStreamByString(contentStr string) error { +func (p *PdfPage) AddContentStreamByString(contentStr string) error { stream, err := MakeStream([]byte(contentStr), NewFlateEncoder()) if err != nil { return err } - if this.Contents == nil { + if p.Contents == nil { // If not set, place it directly. - this.Contents = stream - } else if contArray, isArray := TraceToDirectObject(this.Contents).(*PdfObjectArray); isArray { + p.Contents = stream + } else if contArray, isArray := TraceToDirectObject(p.Contents).(*PdfObjectArray); isArray { // If an array of content streams, append it. contArray.Append(stream) } else { // Only 1 element in place. Wrap inside a new array and add the new one. - contArray := MakeArray(this.Contents, stream) - this.Contents = contArray + contArray := MakeArray(p.Contents, stream) + p.Contents = contArray } return nil @@ -751,14 +751,14 @@ func (this *PdfPage) AddContentStreamByString(contentStr string) error { // AppendContentStream adds content stream by string. Appends to the last // contentstream instance if many. -func (this *PdfPage) AppendContentStream(contentStr string) error { - cstreams, err := this.GetContentStreams() +func (p *PdfPage) AppendContentStream(contentStr string) error { + cstreams, err := p.GetContentStreams() if err != nil { return err } if len(cstreams) == 0 { cstreams = []string{contentStr} - return this.SetContentStreams(cstreams, NewFlateEncoder()) + return p.SetContentStreams(cstreams, NewFlateEncoder()) } var buf bytes.Buffer @@ -767,16 +767,16 @@ func (this *PdfPage) AppendContentStream(contentStr string) error { buf.WriteString(contentStr) cstreams[len(cstreams)-1] = buf.String() - return this.SetContentStreams(cstreams, NewFlateEncoder()) + return p.SetContentStreams(cstreams, NewFlateEncoder()) } // SetContentStreams sets the content streams based on a string array. Will make 1 object stream // for each string and reference from the page Contents. Each stream will be // encoded using the encoding specified by the StreamEncoder, if empty, will // use identity encoding (raw data). -func (this *PdfPage) SetContentStreams(cStreams []string, encoder StreamEncoder) error { +func (p *PdfPage) SetContentStreams(cStreams []string, encoder StreamEncoder) error { if len(cStreams) == 0 { - this.Contents = nil + p.Contents = nil return nil } @@ -808,13 +808,13 @@ func (this *PdfPage) SetContentStreams(cStreams []string, encoder StreamEncoder) // Set the page contents. // Point directly to the object stream if only one, or embed in an array. if len(streamObjs) == 1 { - this.Contents = streamObjs[0] + p.Contents = streamObjs[0] } else { contArray := MakeArray() for _, streamObj := range streamObjs { contArray.Append(streamObj) } - this.Contents = contArray + p.Contents = contArray } return nil @@ -837,12 +837,12 @@ func getContentStreamAsString(cstreamObj PdfObject) (string, error) { } // GetContentStreams returns the content stream as an array of strings. -func (this *PdfPage) GetContentStreams() ([]string, error) { - if this.Contents == nil { +func (p *PdfPage) GetContentStreams() ([]string, error) { + if p.Contents == nil { return nil, nil } - contents := TraceToDirectObject(this.Contents) + contents := TraceToDirectObject(p.Contents) if contArray, isArray := contents.(*PdfObjectArray); isArray { // If an array of content streams, append it. var cstreams []string @@ -866,8 +866,8 @@ func (this *PdfPage) GetContentStreams() ([]string, error) { } // GetAllContentStreams gets all the content streams for a page as one string. -func (this *PdfPage) GetAllContentStreams() (string, error) { - cstreams, err := this.GetContentStreams() +func (p *PdfPage) GetAllContentStreams() (string, error) { + cstreams, err := p.GetContentStreams() if err != nil { return "", err } @@ -892,11 +892,11 @@ func NewPdfPageResourcesColorspaces() *PdfPageResourcesColorspaces { } // Set sets the colorspace corresponding to key. Add to Names if not set. -func (this *PdfPageResourcesColorspaces) Set(key PdfObjectName, val PdfColorspace) { - if _, has := this.Colorspaces[string(key)]; !has { - this.Names = append(this.Names, string(key)) +func (r *PdfPageResourcesColorspaces) Set(key PdfObjectName, val PdfColorspace) { + if _, has := r.Colorspaces[string(key)]; !has { + r.Names = append(r.Names, string(key)) } - this.Colorspaces[string(key)] = val + r.Colorspaces[string(key)] = val } func newPdfPageResourcesColorspacesFromPdfObject(obj PdfObject) (*PdfPageResourcesColorspaces, error) { @@ -928,15 +928,15 @@ func newPdfPageResourcesColorspacesFromPdfObject(obj PdfObject) (*PdfPageResourc return colorspaces, nil } -func (this *PdfPageResourcesColorspaces) ToPdfObject() PdfObject { +func (r *PdfPageResourcesColorspaces) ToPdfObject() PdfObject { dict := MakeDict() - for _, csName := range this.Names { - dict.Set(PdfObjectName(csName), this.Colorspaces[csName].ToPdfObject()) + for _, csName := range r.Names { + dict.Set(PdfObjectName(csName), r.Colorspaces[csName].ToPdfObject()) } - if this.container != nil { - this.container.PdfObject = dict - return this.container + if r.container != nil { + r.container.PdfObject = dict + return r.container } return dict diff --git a/pdf/model/pattern.go b/pdf/model/pattern.go index a9847569..f4a1d6c1 100644 --- a/pdf/model/pattern.go +++ b/pdf/model/pattern.go @@ -26,36 +26,36 @@ type PdfPattern struct { container PdfObject } -func (this *PdfPattern) GetContainingPdfObject() PdfObject { - return this.container +func (p *PdfPattern) GetContainingPdfObject() PdfObject { + return p.container } // GetContext returns a reference to the subpattern entry: either PdfTilingPattern or PdfShadingPattern. -func (this *PdfPattern) GetContext() PdfModel { - return this.context +func (p *PdfPattern) GetContext() PdfModel { + return p.context } // SetContext sets the sub pattern (context). Either PdfTilingPattern or PdfShadingPattern. -func (this *PdfPattern) SetContext(ctx PdfModel) { - this.context = ctx +func (p *PdfPattern) SetContext(ctx PdfModel) { + p.context = ctx } -func (this *PdfPattern) IsTiling() bool { - return this.PatternType == 1 +func (p *PdfPattern) IsTiling() bool { + return p.PatternType == 1 } -func (this *PdfPattern) IsShading() bool { - return this.PatternType == 2 +func (p *PdfPattern) IsShading() bool { + return p.PatternType == 2 } // GetAsTilingPattern returns a tiling pattern. Check with IsTiling() prior to using this. -func (this *PdfPattern) GetAsTilingPattern() *PdfTilingPattern { - return this.context.(*PdfTilingPattern) +func (p *PdfPattern) GetAsTilingPattern() *PdfTilingPattern { + return p.context.(*PdfTilingPattern) } // GetAsShadingPattern returns a shading pattern. Check with IsShading() prior to using this. -func (this *PdfPattern) GetAsShadingPattern() *PdfShadingPattern { - return this.context.(*PdfShadingPattern) +func (p *PdfPattern) GetAsShadingPattern() *PdfShadingPattern { + return p.context.(*PdfShadingPattern) } // PdfTilingPattern is a Tiling pattern that consists of repetitions of a pattern cell with defined intervals. @@ -73,8 +73,8 @@ type PdfTilingPattern struct { Matrix *PdfObjectArray // Pattern matrix (6 numbers). } -func (this *PdfTilingPattern) IsColored() bool { - if this.PaintType != nil && *this.PaintType == 1 { +func (p *PdfTilingPattern) IsColored() bool { + if p.PaintType != nil && *p.PaintType == 1 { return true } else { return false @@ -82,17 +82,17 @@ func (this *PdfTilingPattern) IsColored() bool { } // GetContentStream returns the pattern cell's content stream -func (this *PdfTilingPattern) GetContentStream() ([]byte, error) { - decoded, _, err := this.GetContentStreamWithEncoder() +func (p *PdfTilingPattern) GetContentStream() ([]byte, error) { + decoded, _, err := p.GetContentStreamWithEncoder() return decoded, err } // GetContentStreamWithEncoder returns the pattern cell's content stream and its encoder // TODO (v3): Change GetContentStreamWithEncoder to GetContentStream -func (this *PdfTilingPattern) GetContentStreamWithEncoder() ([]byte, StreamEncoder, error) { - streamObj, ok := this.container.(*PdfObjectStream) +func (p *PdfTilingPattern) GetContentStreamWithEncoder() ([]byte, StreamEncoder, error) { + streamObj, ok := p.container.(*PdfObjectStream) if !ok { - common.Log.Debug("Tiling pattern container not a stream (got %T)", this.container) + common.Log.Debug("Tiling pattern container not a stream (got %T)", p.container) return nil, nil, ErrTypeError } @@ -112,10 +112,10 @@ func (this *PdfTilingPattern) GetContentStreamWithEncoder() ([]byte, StreamEncod } // SetContentStream sets the pattern cell's content stream. -func (this *PdfTilingPattern) SetContentStream(content []byte, encoder StreamEncoder) error { - streamObj, ok := this.container.(*PdfObjectStream) +func (p *PdfTilingPattern) SetContentStream(content []byte, encoder StreamEncoder) error { + streamObj, ok := p.container.(*PdfObjectStream) if !ok { - common.Log.Debug("Tiling pattern container not a stream (got %T)", this.container) + common.Log.Debug("Tiling pattern container not a stream (got %T)", p.container) return ErrTypeError } @@ -355,71 +355,71 @@ func newPdfShadingPatternFromDictionary(dict *PdfObjectDictionary) (*PdfShadingP /* Conversions to pdf objects. */ -func (this *PdfPattern) getDict() *PdfObjectDictionary { - if indObj, is := this.container.(*PdfIndirectObject); is { +func (p *PdfPattern) getDict() *PdfObjectDictionary { + if indObj, is := p.container.(*PdfIndirectObject); is { dict, ok := indObj.PdfObject.(*PdfObjectDictionary) if !ok { return nil } return dict - } else if streamObj, is := this.container.(*PdfObjectStream); is { + } else if streamObj, is := p.container.(*PdfObjectStream); is { return streamObj.PdfObjectDictionary } else { - common.Log.Debug("Trying to access pattern dictionary of invalid object type (%T)", this.container) + common.Log.Debug("Trying to access pattern dictionary of invalid object type (%T)", p.container) return nil } } -func (this *PdfPattern) ToPdfObject() PdfObject { - d := this.getDict() +func (p *PdfPattern) ToPdfObject() PdfObject { + d := p.getDict() d.Set("Type", MakeName("Pattern")) - d.Set("PatternType", MakeInteger(this.PatternType)) + d.Set("PatternType", MakeInteger(p.PatternType)) - return this.container + return p.container } -func (this *PdfTilingPattern) ToPdfObject() PdfObject { - this.PdfPattern.ToPdfObject() +func (p *PdfTilingPattern) ToPdfObject() PdfObject { + p.PdfPattern.ToPdfObject() - d := this.getDict() - if this.PaintType != nil { - d.Set("PaintType", this.PaintType) + d := p.getDict() + if p.PaintType != nil { + d.Set("PaintType", p.PaintType) } - if this.TilingType != nil { - d.Set("TilingType", this.TilingType) + if p.TilingType != nil { + d.Set("TilingType", p.TilingType) } - if this.BBox != nil { - d.Set("BBox", this.BBox.ToPdfObject()) + if p.BBox != nil { + d.Set("BBox", p.BBox.ToPdfObject()) } - if this.XStep != nil { - d.Set("XStep", this.XStep) + if p.XStep != nil { + d.Set("XStep", p.XStep) } - if this.YStep != nil { - d.Set("YStep", this.YStep) + if p.YStep != nil { + d.Set("YStep", p.YStep) } - if this.Resources != nil { - d.Set("Resources", this.Resources.ToPdfObject()) + if p.Resources != nil { + d.Set("Resources", p.Resources.ToPdfObject()) } - if this.Matrix != nil { - d.Set("Matrix", this.Matrix) + if p.Matrix != nil { + d.Set("Matrix", p.Matrix) } - return this.container + return p.container } -func (this *PdfShadingPattern) ToPdfObject() PdfObject { - this.PdfPattern.ToPdfObject() - d := this.getDict() +func (p *PdfShadingPattern) ToPdfObject() PdfObject { + p.PdfPattern.ToPdfObject() + d := p.getDict() - if this.Shading != nil { - d.Set("Shading", this.Shading.ToPdfObject()) + if p.Shading != nil { + d.Set("Shading", p.Shading.ToPdfObject()) } - if this.Matrix != nil { - d.Set("Matrix", this.Matrix) + if p.Matrix != nil { + d.Set("Matrix", p.Matrix) } - if this.ExtGState != nil { - d.Set("ExtGState", this.ExtGState) + if p.ExtGState != nil { + d.Set("ExtGState", p.ExtGState) } - return this.container + return p.container } diff --git a/pdf/model/reader.go b/pdf/model/reader.go index ba87bfe4..b40f0d64 100755 --- a/pdf/model/reader.go +++ b/pdf/model/reader.go @@ -68,26 +68,26 @@ func NewPdfReader(rs io.ReadSeeker) (*PdfReader, error) { } // PdfVersion returns version of the PDF file. -func (this *PdfReader) PdfVersion() Version { - return this.parser.PdfVersion() +func (r *PdfReader) PdfVersion() Version { + return r.parser.PdfVersion() } // IsEncrypted returns true if the PDF file is encrypted. -func (this *PdfReader) IsEncrypted() (bool, error) { - return this.parser.IsEncrypted() +func (r *PdfReader) IsEncrypted() (bool, error) { + return r.parser.IsEncrypted() } // GetEncryptionMethod returns a descriptive information string about the encryption method used. -func (this *PdfReader) GetEncryptionMethod() string { - crypter := this.parser.GetCrypter() +func (r *PdfReader) GetEncryptionMethod() string { + crypter := r.parser.GetCrypter() return crypter.String() } // Decrypt decrypts the PDF file with a specified password. Also tries to // decrypt with an empty password. Returns true if successful, // false otherwise. -func (this *PdfReader) Decrypt(password []byte) (bool, error) { - success, err := this.parser.Decrypt(password) +func (r *PdfReader) Decrypt(password []byte) (bool, error) { + success, err := r.parser.Decrypt(password) if err != nil { return false, err } @@ -95,7 +95,7 @@ func (this *PdfReader) Decrypt(password []byte) (bool, error) { return false, nil } - err = this.loadStructure() + err = r.loadStructure() if err != nil { common.Log.Debug("ERROR: Fail to load structure (%s)", err) return false, err @@ -111,17 +111,17 @@ func (this *PdfReader) Decrypt(password []byte) (bool, error) { // The bool flag indicates that the user can access and view the file. // The AccessPermissions shows what access the user has for editing etc. // An error is returned if there was a problem performing the authentication. -func (this *PdfReader) CheckAccessRights(password []byte) (bool, security.Permissions, error) { - return this.parser.CheckAccessRights(password) +func (r *PdfReader) CheckAccessRights(password []byte) (bool, security.Permissions, error) { + return r.parser.CheckAccessRights(password) } // Loads the structure of the pdf file: pages, outlines, etc. -func (this *PdfReader) loadStructure() error { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) loadStructure() error { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return fmt.Errorf("File need to be decrypted first") } - trailerDict := this.parser.GetTrailer() + trailerDict := r.parser.GetTrailer() if trailerDict == nil { return fmt.Errorf("Missing trailer") } @@ -131,7 +131,7 @@ func (this *PdfReader) loadStructure() error { if !ok { return fmt.Errorf("Invalid Root (trailer: %s)", trailerDict) } - oc, err := this.parser.LookupByReference(*root) + oc, err := r.parser.LookupByReference(*root) if err != nil { common.Log.Debug("ERROR: Failed to read root element catalog: %s", err) return err @@ -153,7 +153,7 @@ func (this *PdfReader) loadStructure() error { if !ok { return errors.New("Pages in catalog should be a reference") } - op, err := this.parser.LookupByReference(*pagesRef) + op, err := r.parser.LookupByReference(*pagesRef) if err != nil { common.Log.Debug("ERROR: Failed to read pages") return err @@ -175,31 +175,31 @@ func (this *PdfReader) loadStructure() error { return errors.New("Pages count invalid") } - this.root = root - this.catalog = catalog - this.pages = pages - this.pageCount = int(*pageCount) - this.pageList = []*PdfIndirectObject{} + r.root = root + r.catalog = catalog + r.pages = pages + r.pageCount = int(*pageCount) + r.pageList = []*PdfIndirectObject{} traversedPageNodes := map[PdfObject]bool{} - err = this.buildPageList(ppages, nil, traversedPageNodes) + err = r.buildPageList(ppages, nil, traversedPageNodes) if err != nil { return err } common.Log.Trace("---") common.Log.Trace("TOC") common.Log.Trace("Pages") - common.Log.Trace("%d: %s", len(this.pageList), this.pageList) + common.Log.Trace("%d: %s", len(r.pageList), r.pageList) // Outlines. - this.outlineTree, err = this.loadOutlines() + r.outlineTree, err = r.loadOutlines() if err != nil { common.Log.Debug("ERROR: Failed to build outline tree (%s)", err) return err } // Load interactive forms and fields. - this.AcroForm, err = this.loadForms() + r.AcroForm, err = r.loadForms() if err != nil { return err } @@ -213,7 +213,7 @@ func (this *PdfReader) loadStructure() error { // 1 0 obj << /Next 2 0 R >> // 2 0 obj << /Next 1 0 R >> // -func (this *PdfReader) traceToObjectWrapper(obj PdfObject, refList map[*PdfObjectReference]bool) (PdfObject, error) { +func (r *PdfReader) traceToObjectWrapper(obj PdfObject, refList map[*PdfObjectReference]bool) (PdfObject, error) { // Keep a list of references to avoid circular references. ref, isRef := obj.(*PdfObjectReference) @@ -223,29 +223,29 @@ func (this *PdfReader) traceToObjectWrapper(obj PdfObject, refList map[*PdfObjec return nil, errors.New("Circular reference") } refList[ref] = true - obj, err := this.parser.LookupByReference(*ref) + obj, err := r.parser.LookupByReference(*ref) if err != nil { return nil, err } - return this.traceToObjectWrapper(obj, refList) + return r.traceToObjectWrapper(obj, refList) } // Not a reference, an object. Can be indirect or any direct pdf object (other than reference). return obj, nil } -func (this *PdfReader) traceToObject(obj PdfObject) (PdfObject, error) { +func (r *PdfReader) traceToObject(obj PdfObject) (PdfObject, error) { refList := map[*PdfObjectReference]bool{} - return this.traceToObjectWrapper(obj, refList) + return r.traceToObjectWrapper(obj, refList) } -func (this *PdfReader) loadOutlines() (*PdfOutlineTreeNode, error) { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) loadOutlines() (*PdfOutlineTreeNode, error) { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return nil, fmt.Errorf("File need to be decrypted first") } // Has outlines? Otherwise return an empty outlines structure. - catalog := this.catalog + catalog := r.catalog outlinesObj := catalog.Get("Outlines") if outlinesObj == nil { return nil, nil @@ -253,7 +253,7 @@ func (this *PdfReader) loadOutlines() (*PdfOutlineTreeNode, error) { common.Log.Trace("-Has outlines") // Trace references to the object. - outlineRootObj, err := this.traceToObject(outlinesObj) + outlineRootObj, err := r.traceToObject(outlinesObj) if err != nil { common.Log.Debug("ERROR: Failed to read outlines") return nil, err @@ -277,7 +277,7 @@ func (this *PdfReader) loadOutlines() (*PdfOutlineTreeNode, error) { common.Log.Trace("Outline root dict: %v", dict) - outlineTree, _, err := this.buildOutlineTree(outlineRoot, nil, nil) + outlineTree, _, err := r.buildOutlineTree(outlineRoot, nil, nil) if err != nil { return nil, err } @@ -292,7 +292,7 @@ func (this *PdfReader) loadOutlines() (*PdfOutlineTreeNode, error) { // Parent, Prev are the parent or previous node in the hierarchy. // The function returns the corresponding tree node and the last node which is used // for setting the Last pointer of the tree node structures. -func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNode, prev *PdfOutlineTreeNode) (*PdfOutlineTreeNode, *PdfOutlineTreeNode, error) { +func (r *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNode, prev *PdfOutlineTreeNode) (*PdfOutlineTreeNode, *PdfOutlineTreeNode, error) { container, isInd := obj.(*PdfIndirectObject) if !isInd { return nil, nil, fmt.Errorf("Outline container not an indirect object %T", obj) @@ -305,7 +305,7 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod if obj := dict.Get("Title"); obj != nil { // Outline item has a title. (required) - outlineItem, err := this.newPdfOutlineItemFromIndirectObject(container) + outlineItem, err := r.newPdfOutlineItemFromIndirectObject(container) if err != nil { return nil, nil, err } @@ -313,12 +313,12 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod outlineItem.Prev = prev if firstObj := dict.Get("First"); firstObj != nil { - firstObj, err = this.traceToObject(firstObj) + firstObj, err = r.traceToObject(firstObj) if err != nil { return nil, nil, err } if _, isNull := firstObj.(*PdfObjectNull); !isNull { - first, last, err := this.buildOutlineTree(firstObj, &outlineItem.PdfOutlineTreeNode, nil) + first, last, err := r.buildOutlineTree(firstObj, &outlineItem.PdfOutlineTreeNode, nil) if err != nil { return nil, nil, err } @@ -329,12 +329,12 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod // Resolve the reference to next if nextObj := dict.Get("Next"); nextObj != nil { - nextObj, err = this.traceToObject(nextObj) + nextObj, err = r.traceToObject(nextObj) if err != nil { return nil, nil, err } if _, isNull := nextObj.(*PdfObjectNull); !isNull { - next, last, err := this.buildOutlineTree(nextObj, parent, &outlineItem.PdfOutlineTreeNode) + next, last, err := r.buildOutlineTree(nextObj, parent, &outlineItem.PdfOutlineTreeNode) if err != nil { return nil, nil, err } @@ -356,12 +356,12 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod if firstObj := dict.Get("First"); firstObj != nil { // Has children... - firstObj, err = this.traceToObject(firstObj) + firstObj, err = r.traceToObject(firstObj) if err != nil { return nil, nil, err } if _, isNull := firstObj.(*PdfObjectNull); !isNull { - first, last, err := this.buildOutlineTree(firstObj, &outline.PdfOutlineTreeNode, nil) + first, last, err := r.buildOutlineTree(firstObj, &outline.PdfOutlineTreeNode, nil) if err != nil { return nil, nil, err } @@ -372,12 +372,12 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod /* if nextObj, hasNext := (*dict)["Next"]; hasNext { - nextObj, err = this.traceToObject(nextObj) + nextObj, err = r.traceToObject(nextObj) if err != nil { return nil, nil, err } if _, isNull := nextObj.(*PdfObjectNull); !isNull { - next, last, err := this.buildOutlineTree(nextObj, parent, &outline.PdfOutlineTreeNode) + next, last, err := r.buildOutlineTree(nextObj, parent, &outline.PdfOutlineTreeNode) if err != nil { return nil, nil, err } @@ -391,12 +391,12 @@ func (this *PdfReader) buildOutlineTree(obj PdfObject, parent *PdfOutlineTreeNod } // GetOutlineTree returns the outline tree. -func (this *PdfReader) GetOutlineTree() *PdfOutlineTreeNode { - return this.outlineTree +func (r *PdfReader) GetOutlineTree() *PdfOutlineTreeNode { + return r.outlineTree } // GetOutlinesFlattened returns a flattened list of tree nodes and titles. -func (this *PdfReader) GetOutlinesFlattened() ([]*PdfOutlineTreeNode, []string, error) { +func (r *PdfReader) GetOutlinesFlattened() ([]*PdfOutlineTreeNode, []string, error) { var outlineNodeList []*PdfOutlineTreeNode var flattenedTitleList []string @@ -426,25 +426,25 @@ func (this *PdfReader) GetOutlinesFlattened() ([]*PdfOutlineTreeNode, []string, flattenFunc(node.First, outlineList, titleList, depth+1) } } - flattenFunc(this.outlineTree, &outlineNodeList, &flattenedTitleList, 0) + flattenFunc(r.outlineTree, &outlineNodeList, &flattenedTitleList, 0) return outlineNodeList, flattenedTitleList, nil } // loadForms loads the AcroForm. -func (this *PdfReader) loadForms() (*PdfAcroForm, error) { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) loadForms() (*PdfAcroForm, error) { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return nil, fmt.Errorf("File need to be decrypted first") } // Has forms? - catalog := this.catalog + catalog := r.catalog obj := catalog.Get("AcroForm") if obj == nil { // Nothing to load. return nil, nil } var err error - obj, err = this.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -465,14 +465,14 @@ func (this *PdfReader) loadForms() (*PdfAcroForm, error) { // Ensure we have access to everything. common.Log.Trace("Traverse the Acroforms structure") - err = this.traverseObjectData(formsDict) + err = r.traverseObjectData(formsDict) if err != nil { common.Log.Debug("ERROR: Unable to traverse AcroForms (%s)", err) return nil, err } // Create the acro forms object. - acroForm, err := this.newPdfAcroFormFromDict(formsDict) + acroForm, err := r.newPdfAcroFormFromDict(formsDict) if err != nil { return nil, err } @@ -480,7 +480,7 @@ func (this *PdfReader) loadForms() (*PdfAcroForm, error) { return acroForm, nil } -func (this *PdfReader) lookupPageByObject(obj PdfObject) (*PdfPage, error) { +func (r *PdfReader) lookupPageByObject(obj PdfObject) (*PdfPage, error) { // can be indirect, direct, or reference // look up the corresponding page return nil, errors.New("Page not found") @@ -489,7 +489,7 @@ func (this *PdfReader) lookupPageByObject(obj PdfObject) (*PdfPage, error) { // Build the table of contents. // tree, ex: Pages -> Pages -> Pages -> Page // Traverse through the whole thing recursively. -func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirectObject, traversedPageNodes map[PdfObject]bool) error { +func (r *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirectObject, traversedPageNodes map[PdfObject]bool) error { if node == nil { return nil } @@ -511,7 +511,7 @@ func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirec } common.Log.Trace("buildPageList node type: %s (%+v)", *objType, node) if *objType == "Page" { - p, err := this.newPdfPageFromDict(nodeDict) + p, err := r.newPdfPageFromDict(nodeDict) if err != nil { return err } @@ -521,8 +521,8 @@ func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirec // Set the parent (in case missing or incorrect). nodeDict.Set("Parent", parent) } - this.pageList = append(this.pageList, node) - this.PageList = append(this.PageList, p) + r.pageList = append(r.pageList, node) + r.PageList = append(r.PageList, p) return nil } @@ -537,12 +537,12 @@ func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirec } // Resolve the object recursively. - err := this.traverseObjectData(node) + err := r.traverseObjectData(node) if err != nil { return err } - kidsObj, err := this.parser.Resolve(nodeDict.Get("Kids")) + kidsObj, err := r.parser.Resolve(nodeDict.Get("Kids")) if err != nil { common.Log.Debug("ERROR: Failed loading Kids object") return err @@ -568,7 +568,7 @@ func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirec return errors.New("Page not indirect object") } kids.Set(idx, child) - err = this.buildPageList(child, node, traversedPageNodes) + err = r.buildPageList(child, node, traversedPageNodes) if err != nil { return err } @@ -578,24 +578,24 @@ func (this *PdfReader) buildPageList(node *PdfIndirectObject, parent *PdfIndirec } // GetNumPages returns the number of pages in the document. -func (this *PdfReader) GetNumPages() (int, error) { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) GetNumPages() (int, error) { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return 0, fmt.Errorf("File need to be decrypted first") } - return len(this.pageList), nil + return len(r.pageList), nil } // Resolves a reference, returning the object and indicates whether or not // it was cached. -func (this *PdfReader) resolveReference(ref *PdfObjectReference) (PdfObject, bool, error) { - cachedObj, isCached := this.parser.ObjCache[int(ref.ObjectNumber)] +func (r *PdfReader) resolveReference(ref *PdfObjectReference) (PdfObject, bool, error) { + cachedObj, isCached := r.parser.ObjCache[int(ref.ObjectNumber)] if !isCached { common.Log.Trace("Reader Lookup ref: %s", ref) - obj, err := this.parser.LookupByReference(*ref) + obj, err := r.parser.LookupByReference(*ref) if err != nil { return nil, false, err } - this.parser.ObjCache[int(ref.ObjectNumber)] = obj + r.parser.ObjCache[int(ref.ObjectNumber)] = obj return obj, false, nil } return cachedObj, true, nil @@ -607,23 +607,23 @@ func (this *PdfReader) resolveReference(ref *PdfObjectReference) (PdfObject, boo * * GH: Are we fully protected against circular references? (Add tests). */ -func (this *PdfReader) traverseObjectData(o PdfObject) error { +func (r *PdfReader) traverseObjectData(o PdfObject) error { common.Log.Trace("Traverse object data") - if _, isTraversed := this.traversed[o]; isTraversed { + if _, isTraversed := r.traversed[o]; isTraversed { common.Log.Trace("-Already traversed...") return nil } - this.traversed[o] = true + r.traversed[o] = true if io, isIndirectObj := o.(*PdfIndirectObject); isIndirectObj { common.Log.Trace("io: %s", io) common.Log.Trace("- %s", io.PdfObject) - err := this.traverseObjectData(io.PdfObject) + err := r.traverseObjectData(io.PdfObject) return err } if so, isStreamObj := o.(*PdfObjectStream); isStreamObj { - err := this.traverseObjectData(so.PdfObjectDictionary) + err := r.traverseObjectData(so.PdfObjectDictionary) return err } @@ -632,17 +632,17 @@ func (this *PdfReader) traverseObjectData(o PdfObject) error { for _, name := range dict.Keys() { v := dict.Get(name) if ref, isRef := v.(*PdfObjectReference); isRef { - resolvedObj, _, err := this.resolveReference(ref) + resolvedObj, _, err := r.resolveReference(ref) if err != nil { return err } dict.Set(name, resolvedObj) - err = this.traverseObjectData(resolvedObj) + err = r.traverseObjectData(resolvedObj) if err != nil { return err } } else { - err := this.traverseObjectData(v) + err := r.traverseObjectData(v) if err != nil { return err } @@ -655,18 +655,18 @@ func (this *PdfReader) traverseObjectData(o PdfObject) error { common.Log.Trace("- array: %s", arr) for idx, v := range arr.Elements() { if ref, isRef := v.(*PdfObjectReference); isRef { - resolvedObj, _, err := this.resolveReference(ref) + resolvedObj, _, err := r.resolveReference(ref) if err != nil { return err } arr.Set(idx, resolvedObj) - err = this.traverseObjectData(resolvedObj) + err = r.traverseObjectData(resolvedObj) if err != nil { return err } } else { - err := this.traverseObjectData(v) + err := r.traverseObjectData(v) if err != nil { return err } @@ -685,18 +685,18 @@ func (this *PdfReader) traverseObjectData(o PdfObject) error { // GetPageAsIndirectObject returns the indirect object representing a page fro a given page number. // Indirect object with type /Page. -func (this *PdfReader) GetPageAsIndirectObject(pageNumber int) (PdfObject, error) { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) GetPageAsIndirectObject(pageNumber int) (PdfObject, error) { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return nil, fmt.Errorf("File needs to be decrypted first") } - if len(this.pageList) < pageNumber { + if len(r.pageList) < pageNumber { return nil, errors.New("Invalid page number (page count too short)") } - page := this.pageList[pageNumber-1] + page := r.pageList[pageNumber-1] // Look up all references related to page and load everything. // TODO: Use of traverse object data will be limited when lazy-loading is supported. - err := this.traverseObjectData(page) + err := r.traverseObjectData(page) if err != nil { return nil, err } @@ -721,28 +721,28 @@ func (r *PdfReader) PageFromIndirectObject(ind *PdfIndirectObject) (*PdfPage, in } // GetPage returns the PdfPage model for the specified page number. -func (this *PdfReader) GetPage(pageNumber int) (*PdfPage, error) { - if this.parser.GetCrypter() != nil && !this.parser.IsAuthenticated() { +func (r *PdfReader) GetPage(pageNumber int) (*PdfPage, error) { + if r.parser.GetCrypter() != nil && !r.parser.IsAuthenticated() { return nil, fmt.Errorf("File needs to be decrypted first") } - if len(this.pageList) < pageNumber { + if len(r.pageList) < pageNumber { return nil, errors.New("Invalid page number (page count too short)") } idx := pageNumber - 1 if idx < 0 { return nil, fmt.Errorf("Page numbering must start at 1") } - page := this.PageList[idx] + page := r.PageList[idx] return page, nil } // GetOCProperties returns the optional content properties PdfObject. -func (this *PdfReader) GetOCProperties() (PdfObject, error) { - dict := this.catalog +func (r *PdfReader) GetOCProperties() (PdfObject, error) { + dict := r.catalog obj := dict.Get("OCProperties") var err error - obj, err = this.traceToObject(obj) + obj, err = r.traceToObject(obj) if err != nil { return nil, err } @@ -751,7 +751,7 @@ func (this *PdfReader) GetOCProperties() (PdfObject, error) { // Should be pretty safe. Should not be referencing to pages or // any large structures. Local structures and references // to OC Groups. - err = this.traverseObjectData(obj) + err = r.traverseObjectData(obj) if err != nil { return nil, err } @@ -761,8 +761,8 @@ func (this *PdfReader) GetOCProperties() (PdfObject, error) { // Inspect inspects the object types, subtypes and content in the PDF file returning a map of // object type to number of instances of each. -func (this *PdfReader) Inspect() (map[string]int, error) { - return this.parser.Inspect() +func (r *PdfReader) Inspect() (map[string]int, error) { + return r.parser.Inspect() } // GetObjectNums returns the object numbers of the PDF objects in the file @@ -775,14 +775,14 @@ func (r *PdfReader) GetObjectNums() []int { } // GetIndirectObjectByNumber retrieves and returns a specific PdfObject by object number. -func (this *PdfReader) GetIndirectObjectByNumber(number int) (PdfObject, error) { - obj, err := this.parser.LookupByNumber(number) +func (r *PdfReader) GetIndirectObjectByNumber(number int) (PdfObject, error) { + obj, err := r.parser.LookupByNumber(number) return obj, err } // GetTrailer returns the PDF's trailer dictionary. -func (this *PdfReader) GetTrailer() (*PdfObjectDictionary, error) { - trailerDict := this.parser.GetTrailer() +func (r *PdfReader) GetTrailer() (*PdfObjectDictionary, error) { + trailerDict := r.parser.GetTrailer() if trailerDict == nil { return nil, errors.New("Trailer missing") } diff --git a/pdf/model/shading.go b/pdf/model/shading.go index ba71320b..5bbe9f90 100644 --- a/pdf/model/shading.go +++ b/pdf/model/shading.go @@ -33,22 +33,22 @@ type PdfShading struct { container PdfObject // The container. Can be stream, indirect object, or dictionary. } -func (this *PdfShading) GetContainingPdfObject() PdfObject { - return this.container +func (s *PdfShading) GetContainingPdfObject() PdfObject { + return s.container } // GetContext returns a reference to the subshading entry as represented by PdfShadingType1-7. -func (this *PdfShading) GetContext() PdfModel { - return this.context +func (s *PdfShading) GetContext() PdfModel { + return s.context } // SetContext set the sub annotation (context). -func (this *PdfShading) SetContext(ctx PdfModel) { - this.context = ctx +func (s *PdfShading) SetContext(ctx PdfModel) { + s.context = ctx } -func (this *PdfShading) getShadingDict() (*PdfObjectDictionary, error) { - obj := this.container +func (s *PdfShading) getShadingDict() (*PdfObjectDictionary, error) { + obj := s.container if indObj, isInd := obj.(*PdfIndirectObject); isInd { d, ok := indObj.PdfObject.(*PdfObjectDictionary) @@ -833,68 +833,68 @@ func newPdfShadingType7FromDictionary(dict *PdfObjectDictionary) (*PdfShadingTyp return &shading, nil } -func (this *PdfShading) ToPdfObject() PdfObject { - container := this.container +func (s *PdfShading) ToPdfObject() PdfObject { + container := s.container - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.ShadingType != nil { - d.Set("ShadingType", this.ShadingType) + if s.ShadingType != nil { + d.Set("ShadingType", s.ShadingType) } - if this.ColorSpace != nil { - d.Set("ColorSpace", this.ColorSpace.ToPdfObject()) + if s.ColorSpace != nil { + d.Set("ColorSpace", s.ColorSpace.ToPdfObject()) } - if this.Background != nil { - d.Set("Background", this.Background) + if s.Background != nil { + d.Set("Background", s.Background) } - if this.BBox != nil { - d.Set("BBox", this.BBox.ToPdfObject()) + if s.BBox != nil { + d.Set("BBox", s.BBox.ToPdfObject()) } - if this.AntiAlias != nil { - d.Set("AntiAlias", this.AntiAlias) + if s.AntiAlias != nil { + d.Set("AntiAlias", s.AntiAlias) } return container } -func (this *PdfShadingType1) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType1) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.Domain != nil { - d.Set("Domain", this.Domain) + if s.Domain != nil { + d.Set("Domain", s.Domain) } - if this.Matrix != nil { - d.Set("Matrix", this.Matrix) + if s.Matrix != nil { + d.Set("Matrix", s.Matrix) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - return this.container + return s.container } -func (this *PdfShadingType2) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType2) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil @@ -903,203 +903,203 @@ func (this *PdfShadingType2) ToPdfObject() PdfObject { common.Log.Error("Shading dict is nil") return nil } - if this.Coords != nil { - d.Set("Coords", this.Coords) + if s.Coords != nil { + d.Set("Coords", s.Coords) } - if this.Domain != nil { - d.Set("Domain", this.Domain) + if s.Domain != nil { + d.Set("Domain", s.Domain) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - if this.Extend != nil { - d.Set("Extend", this.Extend) + if s.Extend != nil { + d.Set("Extend", s.Extend) } - return this.container + return s.container } -func (this *PdfShadingType3) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType3) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.Coords != nil { - d.Set("Coords", this.Coords) + if s.Coords != nil { + d.Set("Coords", s.Coords) } - if this.Domain != nil { - d.Set("Domain", this.Domain) + if s.Domain != nil { + d.Set("Domain", s.Domain) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - if this.Extend != nil { - d.Set("Extend", this.Extend) + if s.Extend != nil { + d.Set("Extend", s.Extend) } - return this.container + return s.container } -func (this *PdfShadingType4) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType4) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.BitsPerCoordinate != nil { - d.Set("BitsPerCoordinate", this.BitsPerCoordinate) + if s.BitsPerCoordinate != nil { + d.Set("BitsPerCoordinate", s.BitsPerCoordinate) } - if this.BitsPerComponent != nil { - d.Set("BitsPerComponent", this.BitsPerComponent) + if s.BitsPerComponent != nil { + d.Set("BitsPerComponent", s.BitsPerComponent) } - if this.BitsPerFlag != nil { - d.Set("BitsPerFlag", this.BitsPerFlag) + if s.BitsPerFlag != nil { + d.Set("BitsPerFlag", s.BitsPerFlag) } - if this.Decode != nil { - d.Set("Decode", this.Decode) + if s.Decode != nil { + d.Set("Decode", s.Decode) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - return this.container + return s.container } -func (this *PdfShadingType5) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType5) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.BitsPerCoordinate != nil { - d.Set("BitsPerCoordinate", this.BitsPerCoordinate) + if s.BitsPerCoordinate != nil { + d.Set("BitsPerCoordinate", s.BitsPerCoordinate) } - if this.BitsPerComponent != nil { - d.Set("BitsPerComponent", this.BitsPerComponent) + if s.BitsPerComponent != nil { + d.Set("BitsPerComponent", s.BitsPerComponent) } - if this.VerticesPerRow != nil { - d.Set("VerticesPerRow", this.VerticesPerRow) + if s.VerticesPerRow != nil { + d.Set("VerticesPerRow", s.VerticesPerRow) } - if this.Decode != nil { - d.Set("Decode", this.Decode) + if s.Decode != nil { + d.Set("Decode", s.Decode) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - return this.container + return s.container } -func (this *PdfShadingType6) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType6) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.BitsPerCoordinate != nil { - d.Set("BitsPerCoordinate", this.BitsPerCoordinate) + if s.BitsPerCoordinate != nil { + d.Set("BitsPerCoordinate", s.BitsPerCoordinate) } - if this.BitsPerComponent != nil { - d.Set("BitsPerComponent", this.BitsPerComponent) + if s.BitsPerComponent != nil { + d.Set("BitsPerComponent", s.BitsPerComponent) } - if this.BitsPerFlag != nil { - d.Set("BitsPerFlag", this.BitsPerFlag) + if s.BitsPerFlag != nil { + d.Set("BitsPerFlag", s.BitsPerFlag) } - if this.Decode != nil { - d.Set("Decode", this.Decode) + if s.Decode != nil { + d.Set("Decode", s.Decode) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - return this.container + return s.container } -func (this *PdfShadingType7) ToPdfObject() PdfObject { - this.PdfShading.ToPdfObject() +func (s *PdfShadingType7) ToPdfObject() PdfObject { + s.PdfShading.ToPdfObject() - d, err := this.getShadingDict() + d, err := s.getShadingDict() if err != nil { common.Log.Error("Unable to access shading dict") return nil } - if this.BitsPerCoordinate != nil { - d.Set("BitsPerCoordinate", this.BitsPerCoordinate) + if s.BitsPerCoordinate != nil { + d.Set("BitsPerCoordinate", s.BitsPerCoordinate) } - if this.BitsPerComponent != nil { - d.Set("BitsPerComponent", this.BitsPerComponent) + if s.BitsPerComponent != nil { + d.Set("BitsPerComponent", s.BitsPerComponent) } - if this.BitsPerFlag != nil { - d.Set("BitsPerFlag", this.BitsPerFlag) + if s.BitsPerFlag != nil { + d.Set("BitsPerFlag", s.BitsPerFlag) } - if this.Decode != nil { - d.Set("Decode", this.Decode) + if s.Decode != nil { + d.Set("Decode", s.Decode) } - if this.Function != nil { - if len(this.Function) == 1 { - d.Set("Function", this.Function[0].ToPdfObject()) + if s.Function != nil { + if len(s.Function) == 1 { + d.Set("Function", s.Function[0].ToPdfObject()) } else { farr := MakeArray() - for _, f := range this.Function { + for _, f := range s.Function { farr.Append(f.ToPdfObject()) } d.Set("Function", farr) } } - return this.container + return s.container } diff --git a/pdf/model/writer.go b/pdf/model/writer.go index 3c9be2ee..f5a059b8 100644 --- a/pdf/model/writer.go +++ b/pdf/model/writer.go @@ -229,60 +229,60 @@ func copyObject(obj PdfObject, objectToObjectCopyMap map[PdfObject]PdfObject) Pd } // copyObjects makes objects copy and set as working. -func (this *PdfWriter) copyObjects() { +func (w *PdfWriter) copyObjects() { objectToObjectCopyMap := make(map[PdfObject]PdfObject) - objects := make([]PdfObject, len(this.objects)) + objects := make([]PdfObject, len(w.objects)) objectsMap := make(map[PdfObject]bool) - for i, obj := range this.objects { + for i, obj := range w.objects { newObject := copyObject(obj, objectToObjectCopyMap) objects[i] = newObject - if this.objectsMap[obj] { + if w.objectsMap[obj] { objectsMap[newObject] = true } } - this.objects = objects - this.objectsMap = objectsMap - this.infoObj = copyObject(this.infoObj, objectToObjectCopyMap).(*PdfIndirectObject) - this.root = copyObject(this.root, objectToObjectCopyMap).(*PdfIndirectObject) - if this.encryptObj != nil { - this.encryptObj = copyObject(this.encryptObj, objectToObjectCopyMap).(*PdfIndirectObject) + w.objects = objects + w.objectsMap = objectsMap + w.infoObj = copyObject(w.infoObj, objectToObjectCopyMap).(*PdfIndirectObject) + w.root = copyObject(w.root, objectToObjectCopyMap).(*PdfIndirectObject) + if w.encryptObj != nil { + w.encryptObj = copyObject(w.encryptObj, objectToObjectCopyMap).(*PdfIndirectObject) } } // SetVersion sets the PDF version of the output file. -func (this *PdfWriter) SetVersion(majorVersion, minorVersion int) { - this.majorVersion = majorVersion - this.minorVersion = minorVersion +func (w *PdfWriter) SetVersion(majorVersion, minorVersion int) { + w.majorVersion = majorVersion + w.minorVersion = minorVersion } // SetOCProperties sets the optional content properties. -func (this *PdfWriter) SetOCProperties(ocProperties PdfObject) error { - dict := this.catalog +func (w *PdfWriter) SetOCProperties(ocProperties PdfObject) error { + dict := w.catalog if ocProperties != nil { common.Log.Trace("Setting OC Properties...") dict.Set("OCProperties", ocProperties) // Any risk of infinite loops? - this.addObjects(ocProperties) + w.addObjects(ocProperties) } return nil } // SetOptimizer sets the optimizer to optimize PDF before writing. -func (this *PdfWriter) SetOptimizer(optimizer Optimizer) { - this.optimizer = optimizer +func (w *PdfWriter) SetOptimizer(optimizer Optimizer) { + w.optimizer = optimizer } // GetOptimizer returns current PDF optimizer. -func (this *PdfWriter) GetOptimizer() Optimizer { - return this.optimizer +func (w *PdfWriter) GetOptimizer() Optimizer { + return w.optimizer } -func (this *PdfWriter) hasObject(obj PdfObject) bool { +func (w *PdfWriter) hasObject(obj PdfObject) bool { // Check if already added. - for _, o := range this.objects { + for _, o := range w.objects { // GH: May perform better to use a hash map to check if added? if o == obj { return true @@ -294,25 +294,25 @@ func (this *PdfWriter) hasObject(obj PdfObject) bool { // Adds the object to list of objects and returns true if the obj was // not already added. // Returns false if the object was previously added. -func (this *PdfWriter) addObject(obj PdfObject) bool { - hasObj := this.hasObject(obj) +func (w *PdfWriter) addObject(obj PdfObject) bool { + hasObj := w.hasObject(obj) if !hasObj { - this.objects = append(this.objects, obj) + w.objects = append(w.objects, obj) return true } return false } -func (this *PdfWriter) addObjects(obj PdfObject) error { +func (w *PdfWriter) addObjects(obj PdfObject) error { common.Log.Trace("Adding objects!") if io, isIndirectObj := obj.(*PdfIndirectObject); isIndirectObj { common.Log.Trace("Indirect") common.Log.Trace("- %s (%p)", obj, io) common.Log.Trace("- %s", io.PdfObject) - if this.addObject(io) { - err := this.addObjects(io.PdfObject) + if w.addObject(io) { + err := w.addObjects(io.PdfObject) if err != nil { return err } @@ -323,8 +323,8 @@ func (this *PdfWriter) addObjects(obj PdfObject) error { if so, isStreamObj := obj.(*PdfObjectStream); isStreamObj { common.Log.Trace("Stream") common.Log.Trace("- %s %p", obj, obj) - if this.addObject(so) { - err := this.addObjects(so.PdfObjectDictionary) + if w.addObject(so) { + err := w.addObjects(so.PdfObjectDictionary) if err != nil { return err } @@ -339,7 +339,7 @@ func (this *PdfWriter) addObjects(obj PdfObject) error { v := dict.Get(k) common.Log.Trace("Key %s", k) if k != "Parent" { - err := this.addObjects(v) + err := w.addObjects(v) if err != nil { return err } @@ -349,9 +349,9 @@ func (this *PdfWriter) addObjects(obj PdfObject) error { continue } - if hasObj := this.hasObject(v); !hasObj { + if hasObj := w.hasObject(v); !hasObj { common.Log.Debug("Parent obj is missing!! %T %p %v", v, v, v) - this.pendingObjects[v] = dict + w.pendingObjects[v] = dict // Although it is missing at this point, it could be added later... } // How to handle the parent? Make sure it is present? @@ -375,7 +375,7 @@ func (this *PdfWriter) addObjects(obj PdfObject) error { return errors.New("Array is nil") } for _, v := range arr.Elements() { - err := this.addObjects(v) + err := w.addObjects(v) if err != nil { return err } @@ -393,7 +393,7 @@ func (this *PdfWriter) addObjects(obj PdfObject) error { } // AddPage adds a page to the PDF file. The new page should be an indirect object. -func (this *PdfWriter) AddPage(page *PdfPage) error { +func (w *PdfWriter) AddPage(page *PdfPage) error { obj := page.ToPdfObject() common.Log.Trace("==========") common.Log.Trace("Appending to page list %T", obj) @@ -451,11 +451,11 @@ func (this *PdfWriter) AddPage(page *PdfPage) error { // Update the dictionary. // Reuses the input object, updating the fields. - pDict.Set("Parent", this.pages) + pDict.Set("Parent", w.pages) pageObj.PdfObject = pDict // Add to Pages. - pagesDict, ok := this.pages.PdfObject.(*PdfObjectDictionary) + pagesDict, ok := w.pages.PdfObject.(*PdfObjectDictionary) if !ok { return errors.New("Invalid Pages obj (not a dict)") } @@ -471,10 +471,10 @@ func (this *PdfWriter) AddPage(page *PdfPage) error { // Update the count. *pageCount = *pageCount + 1 - this.addObject(pageObj) + w.addObject(pageObj) // Traverse the page and record all object references. - err := this.addObjects(pDict) + err := w.addObjects(pDict) if err != nil { return err } @@ -511,21 +511,21 @@ func procPage(p *PdfPage) { } // AddOutlineTree adds outlines to a PDF file. -func (this *PdfWriter) AddOutlineTree(outlineTree *PdfOutlineTreeNode) { - this.outlineTree = outlineTree +func (w *PdfWriter) AddOutlineTree(outlineTree *PdfOutlineTreeNode) { + w.outlineTree = outlineTree } // Look for a specific key. Returns a list of entries. // What if something appears on many pages? -func (this *PdfWriter) seekByName(obj PdfObject, followKeys []string, key string) ([]PdfObject, error) { +func (w *PdfWriter) seekByName(obj PdfObject, followKeys []string, key string) ([]PdfObject, error) { common.Log.Trace("Seek by name.. %T", obj) var list []PdfObject if io, isIndirectObj := obj.(*PdfIndirectObject); isIndirectObj { - return this.seekByName(io.PdfObject, followKeys, key) + return w.seekByName(io.PdfObject, followKeys, key) } if so, isStreamObj := obj.(*PdfObjectStream); isStreamObj { - return this.seekByName(so.PdfObjectDictionary, followKeys, key) + return w.seekByName(so.PdfObjectDictionary, followKeys, key) } if dict, isDict := obj.(*PdfObjectDictionary); isDict { @@ -538,7 +538,7 @@ func (this *PdfWriter) seekByName(obj PdfObject, followKeys []string, key string for _, followKey := range followKeys { if string(k) == followKey { common.Log.Trace("Follow key %s", followKey) - items, err := this.seekByName(v, followKeys, key) + items, err := w.seekByName(v, followKeys, key) if err != nil { return list, err } @@ -556,39 +556,39 @@ func (this *PdfWriter) seekByName(obj PdfObject, followKeys []string, key string } // SetForms sets the Acroform for a PDF file. -func (this *PdfWriter) SetForms(form *PdfAcroForm) error { - this.acroForm = form +func (w *PdfWriter) SetForms(form *PdfAcroForm) error { + w.acroForm = form return nil } // writeObject writes out an indirect / stream object. -func (this *PdfWriter) writeObject(num int, obj PdfObject) { +func (w *PdfWriter) writeObject(num int, obj PdfObject) { common.Log.Trace("Write obj #%d\n", num) if pobj, isIndirect := obj.(*PdfIndirectObject); isIndirect { - this.crossReferenceMap[num] = crossReference{Type: 1, Offset: this.writePos, Generation: pobj.GenerationNumber} + w.crossReferenceMap[num] = crossReference{Type: 1, Offset: w.writePos, Generation: pobj.GenerationNumber} outStr := fmt.Sprintf("%d 0 obj\n", num) outStr += pobj.PdfObject.DefaultWriteString() outStr += "\nendobj\n" - this.writeString(outStr) + w.writeString(outStr) return } // TODO: Add a default encoder if Filter not specified? // Still need to make sure is encrypted. if pobj, isStream := obj.(*PdfObjectStream); isStream { - this.crossReferenceMap[num] = crossReference{Type: 1, Offset: this.writePos, Generation: pobj.GenerationNumber} + w.crossReferenceMap[num] = crossReference{Type: 1, Offset: w.writePos, Generation: pobj.GenerationNumber} outStr := fmt.Sprintf("%d 0 obj\n", num) outStr += pobj.PdfObjectDictionary.DefaultWriteString() outStr += "\nstream\n" - this.writeString(outStr) - this.writeBytes(pobj.Stream) - this.writeString("\nendstream\nendobj\n") + w.writeString(outStr) + w.writeBytes(pobj.Stream) + w.writeString("\nendstream\nendobj\n") return } if ostreams, isObjStreams := obj.(*PdfObjectStreams); isObjStreams { - this.crossReferenceMap[num] = crossReference{Type: 1, Offset: this.writePos, Generation: ostreams.GenerationNumber} + w.crossReferenceMap[num] = crossReference{Type: 1, Offset: w.writePos, Generation: ostreams.GenerationNumber} outStr := fmt.Sprintf("%d 0 obj\n", num) var offsets []string var objData string @@ -602,7 +602,7 @@ func (this *PdfWriter) writeObject(num int, obj PdfObject) { data := io.PdfObject.DefaultWriteString() + " " objData = objData + data offsets = append(offsets, fmt.Sprintf("%d %d", io.ObjectNumber, offset)) - this.crossReferenceMap[int(io.ObjectNumber)] = crossReference{Type: 2, ObjectNumber: num, Index: index} + w.crossReferenceMap[int(io.ObjectNumber)] = crossReference{Type: 2, ObjectNumber: num, Index: index} offset = offset + int64(len([]byte(data))) } offsetsStr := strings.Join(offsets, " ") + " " @@ -621,19 +621,19 @@ func (this *PdfWriter) writeObject(num int, obj PdfObject) { dict.Set(PdfObjectName("Length"), MakeInteger(length)) outStr += dict.DefaultWriteString() outStr += "\nstream\n" - this.writeString(outStr) - this.writeBytes(data) - this.writeString("\nendstream\nendobj\n") + w.writeString(outStr) + w.writeBytes(data) + w.writeString("\nendstream\nendobj\n") return } - this.writer.WriteString(obj.DefaultWriteString()) + w.writer.WriteString(obj.DefaultWriteString()) } // Update all the object numbers prior to writing. -func (this *PdfWriter) updateObjectNumbers() { +func (w *PdfWriter) updateObjectNumbers() { // Update numbers - for idx, obj := range this.objects { + for idx, obj := range w.objects { switch o := obj.(type) { case *PdfIndirectObject: o.ObjectNumber = int64(idx + 1) @@ -667,7 +667,7 @@ const ( ) // Encrypt encrypts the output file with a specified user/owner password. -func (this *PdfWriter) Encrypt(userPass, ownerPass []byte, options *EncryptOptions) error { +func (w *PdfWriter) Encrypt(userPass, ownerPass []byte, options *EncryptOptions) error { algo := RC4_128bit if options != nil { algo = options.Algorithm @@ -692,44 +692,44 @@ func (this *PdfWriter) Encrypt(userPass, ownerPass []byte, options *EncryptOptio if err != nil { return err } - this.crypter = crypter + w.crypter = crypter if info.Major != 0 { - this.SetVersion(info.Major, info.Minor) + w.SetVersion(info.Major, info.Minor) } - this.encryptDict = info.Encrypt + w.encryptDict = info.Encrypt - this.ids = MakeArray(MakeHexString(info.ID0), MakeHexString(info.ID1)) + w.ids = MakeArray(MakeHexString(info.ID0), MakeHexString(info.ID1)) // Make an object to contain the encryption dictionary. io := MakeIndirectObject(info.Encrypt) - this.encryptObj = io - this.addObject(io) + w.encryptObj = io + w.addObject(io) return nil } // Wrapper function to handle writing out string. -func (this *PdfWriter) writeString(s string) error { - n, err := this.writer.WriteString(s) +func (w *PdfWriter) writeString(s string) error { + n, err := w.writer.WriteString(s) if err != nil { return err } - this.writePos += int64(n) + w.writePos += int64(n) return nil } // Wrapper function to handle writing out bytes. -func (this *PdfWriter) writeBytes(bb []byte) error { - n, err := this.writer.Write(bb) +func (w *PdfWriter) writeBytes(bb []byte) error { + n, err := w.writer.Write(bb) if err != nil { return err } - this.writePos += int64(n) + w.writePos += int64(n) return nil } // Write writes out the PDF. -func (this *PdfWriter) Write(writer io.Writer) error { +func (w *PdfWriter) Write(writer io.Writer) error { common.Log.Trace("Write()") lk := license.GetLicenseKey() @@ -739,32 +739,32 @@ func (this *PdfWriter) Write(writer io.Writer) error { } // Outlines. - if this.outlineTree != nil { - common.Log.Trace("OutlineTree: %+v", this.outlineTree) - outlines := this.outlineTree.ToPdfObject() + if w.outlineTree != nil { + common.Log.Trace("OutlineTree: %+v", w.outlineTree) + outlines := w.outlineTree.ToPdfObject() common.Log.Trace("Outlines: %+v (%T, p:%p)", outlines, outlines, outlines) - this.catalog.Set("Outlines", outlines) - err := this.addObjects(outlines) + w.catalog.Set("Outlines", outlines) + err := w.addObjects(outlines) if err != nil { return err } } // Form fields. - if this.acroForm != nil { + if w.acroForm != nil { common.Log.Trace("Writing acro forms") - indObj := this.acroForm.ToPdfObject() + indObj := w.acroForm.ToPdfObject() common.Log.Trace("AcroForm: %+v", indObj) - this.catalog.Set("AcroForm", indObj) - err := this.addObjects(indObj) + w.catalog.Set("AcroForm", indObj) + err := w.addObjects(indObj) if err != nil { return err } } // Check pending objects prior to write. - for pendingObj, pendingObjDict := range this.pendingObjects { - if !this.hasObject(pendingObj) { + for pendingObj, pendingObjDict := range w.pendingObjects { + if !w.hasObject(pendingObj) { common.Log.Debug("ERROR Pending object %+v %T (%p) never added for writing", pendingObj, pendingObj, pendingObj) for _, key := range pendingObjDict.Keys() { val := pendingObjDict.Get(key) @@ -777,26 +777,25 @@ func (this *PdfWriter) Write(writer io.Writer) error { } } // Set version in the catalog. - this.catalog.Set("Version", MakeName(fmt.Sprintf("%d.%d", this.majorVersion, this.minorVersion))) + w.catalog.Set("Version", MakeName(fmt.Sprintf("%d.%d", w.majorVersion, w.minorVersion))) // Make a copy of objects prior to optimizing as this can alter the objects. - this.copyObjects() + w.copyObjects() - if this.optimizer != nil { + if w.optimizer != nil { var err error - this.objects, err = this.optimizer.Optimize(this.objects) + w.objects, err = w.optimizer.Optimize(w.objects) if err != nil { return err } } - w := bufio.NewWriter(writer) - this.writer = w - this.writePos = 0 - useCrossReferenceStream := this.majorVersion > 1 || (this.majorVersion == 1 && this.minorVersion > 4) + w.writer = bufio.NewWriter(writer) + w.writePos = 0 + useCrossReferenceStream := w.majorVersion > 1 || (w.majorVersion == 1 && w.minorVersion > 4) objectsInObjectStreams := make(map[PdfObject]bool) if !useCrossReferenceStream { - for _, obj := range this.objects { + for _, obj := range w.objects { if objStm, isObjectStreams := obj.(*PdfObjectStreams); isObjectStreams { useCrossReferenceStream = true for _, obj := range objStm.Elements() { @@ -809,20 +808,20 @@ func (this *PdfWriter) Write(writer io.Writer) error { } } - if useCrossReferenceStream && this.majorVersion == 1 && this.minorVersion < 5 { - this.minorVersion = 5 + if useCrossReferenceStream && w.majorVersion == 1 && w.minorVersion < 5 { + w.minorVersion = 5 } - this.writeString(fmt.Sprintf("%%PDF-%d.%d\n", this.majorVersion, this.minorVersion)) - this.writeString("%âãÏÓ\n") + w.writeString(fmt.Sprintf("%%PDF-%d.%d\n", w.majorVersion, w.minorVersion)) + w.writeString("%âãÏÓ\n") - this.updateObjectNumbers() + w.updateObjectNumbers() // Write objects - common.Log.Trace("Writing %d obj", len(this.objects)) - this.crossReferenceMap = make(map[int]crossReference) - this.crossReferenceMap[0] = crossReference{Type: 0, ObjectNumber: 0, Generation: 0xFFFF} - for idx, obj := range this.objects { + common.Log.Trace("Writing %d obj", len(w.objects)) + w.crossReferenceMap = make(map[int]crossReference) + w.crossReferenceMap[0] = crossReference{Type: 0, ObjectNumber: 0, Generation: 0xFFFF} + for idx, obj := range w.objects { if skip := objectsInObjectStreams[obj]; skip { continue } @@ -830,26 +829,26 @@ func (this *PdfWriter) Write(writer io.Writer) error { // Encrypt prior to writing. // Encrypt dictionary should not be encrypted. - if this.crypter != nil && obj != this.encryptObj { - err := this.crypter.Encrypt(obj, int64(idx+1), 0) + if w.crypter != nil && obj != w.encryptObj { + err := w.crypter.Encrypt(obj, int64(idx+1), 0) if err != nil { common.Log.Debug("ERROR: Failed encrypting (%s)", err) return err } } - this.writeObject(idx+1, obj) + w.writeObject(idx+1, obj) } - xrefOffset := this.writePos + xrefOffset := w.writePos if useCrossReferenceStream { - crossObjNumber := len(this.crossReferenceMap) - this.crossReferenceMap[crossObjNumber] = crossReference{Type: 1, ObjectNumber: crossObjNumber, Offset: xrefOffset} + crossObjNumber := len(w.crossReferenceMap) + w.crossReferenceMap[crossObjNumber] = crossReference{Type: 1, ObjectNumber: crossObjNumber, Offset: xrefOffset} crossReferenceData := bytes.NewBuffer(nil) - for idx := 0; idx < len(this.crossReferenceMap); idx++ { - ref := this.crossReferenceMap[idx] + for idx := 0; idx < len(w.crossReferenceMap); idx++ { + ref := w.crossReferenceMap[idx] switch ref.Type { case 0: binary.Write(crossReferenceData, binary.BigEndian, byte(0)) @@ -874,56 +873,56 @@ func (this *PdfWriter) Write(writer io.Writer) error { crossReferenceStream.PdfObjectDictionary.Set("W", MakeArray(MakeInteger(1), MakeInteger(4), MakeInteger(2))) crossReferenceStream.PdfObjectDictionary.Set("Index", MakeArray(MakeInteger(0), MakeInteger(crossReferenceStream.ObjectNumber+1))) crossReferenceStream.PdfObjectDictionary.Set("Size", MakeInteger(crossReferenceStream.ObjectNumber+1)) - crossReferenceStream.PdfObjectDictionary.Set("Info", this.infoObj) - crossReferenceStream.PdfObjectDictionary.Set("Root", this.root) + crossReferenceStream.PdfObjectDictionary.Set("Info", w.infoObj) + crossReferenceStream.PdfObjectDictionary.Set("Root", w.root) // If encrypted! - if this.crypter != nil { - crossReferenceStream.Set("Encrypt", this.encryptObj) - crossReferenceStream.Set("ID", this.ids) - common.Log.Trace("Ids: %s", this.ids) + if w.crypter != nil { + crossReferenceStream.Set("Encrypt", w.encryptObj) + crossReferenceStream.Set("ID", w.ids) + common.Log.Trace("Ids: %s", w.ids) } - this.writeObject(int(crossReferenceStream.ObjectNumber), crossReferenceStream) + w.writeObject(int(crossReferenceStream.ObjectNumber), crossReferenceStream) } else { - this.writeString("xref\r\n") - outStr := fmt.Sprintf("%d %d\r\n", 0, len(this.crossReferenceMap)) - this.writeString(outStr) - for idx := 0; idx < len(this.crossReferenceMap); idx++ { - ref := this.crossReferenceMap[idx] + w.writeString("xref\r\n") + outStr := fmt.Sprintf("%d %d\r\n", 0, len(w.crossReferenceMap)) + w.writeString(outStr) + for idx := 0; idx < len(w.crossReferenceMap); idx++ { + ref := w.crossReferenceMap[idx] switch ref.Type { case 0: outStr = fmt.Sprintf("%.10d %.5d f\r\n", 0, 65535) - this.writeString(outStr) + w.writeString(outStr) case 1: outStr = fmt.Sprintf("%.10d %.5d n\r\n", ref.Offset, 0) - this.writeString(outStr) + w.writeString(outStr) } } // Generate & write trailer trailer := MakeDict() - trailer.Set("Info", this.infoObj) - trailer.Set("Root", this.root) - trailer.Set("Size", MakeInteger(int64(len(this.objects)+1))) + trailer.Set("Info", w.infoObj) + trailer.Set("Root", w.root) + trailer.Set("Size", MakeInteger(int64(len(w.objects)+1))) // If encrypted! - if this.crypter != nil { - trailer.Set("Encrypt", this.encryptObj) - trailer.Set("ID", this.ids) - common.Log.Trace("Ids: %s", this.ids) + if w.crypter != nil { + trailer.Set("Encrypt", w.encryptObj) + trailer.Set("ID", w.ids) + common.Log.Trace("Ids: %s", w.ids) } - this.writeString("trailer\n") - this.writeString(trailer.DefaultWriteString()) - this.writeString("\n") + w.writeString("trailer\n") + w.writeString(trailer.DefaultWriteString()) + w.writeString("\n") } // Make offset reference. outStr := fmt.Sprintf("startxref\n%d\n", xrefOffset) - this.writeString(outStr) - this.writeString("%%EOF\n") + w.writeString(outStr) + w.writeString("%%EOF\n") - this.writer.Flush() + w.writer.Flush() return nil } From 3f7ad738126b254286a65665d9e61ce1f1eaf29e Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Tue, 11 Dec 2018 04:37:00 +0200 Subject: [PATCH 7/7] refactor some receiver and method names; fix typos in comments --- pdf/contentstream/contentstream.go | 4 +- pdf/contentstream/inline-image.go | 48 +- pdf/contentstream/processor.go | 8 +- pdf/core/encoding.go | 2 +- pdf/core/primitives.go | 59 +- pdf/core/primitives_test.go | 6 +- pdf/creator/styled_paragraph.go | 2 - pdf/internal/cmap/cmap_test.go | 4 +- pdf/internal/testutils/testutils.go | 6 +- pdf/model/colorspace.go | 642 +++++++++--------- pdf/model/colorspace_test.go | 2 +- .../combine_duplicate_direct_objects.go | 2 +- .../combine_identical_indirect_objects.go | 2 +- pdf/model/optimize/compress_streams.go | 2 +- pdf/model/outlines.go | 60 +- pdf/model/page.go | 26 +- pdf/model/shading.go | 2 +- pdf/model/structures.go | 2 +- pdf/model/writer.go | 12 +- pdf/model/xobject.go | 8 +- 20 files changed, 449 insertions(+), 450 deletions(-) diff --git a/pdf/contentstream/contentstream.go b/pdf/contentstream/contentstream.go index 8f07f1bd..49c0c724 100644 --- a/pdf/contentstream/contentstream.go +++ b/pdf/contentstream/contentstream.go @@ -89,12 +89,12 @@ func (ops *ContentStreamOperations) Bytes() []byte { if op.Operand == "BI" { // Inline image requires special handling. buf.WriteString(op.Operand + "\n") - buf.WriteString(op.Params[0].DefaultWriteString()) + buf.WriteString(op.Params[0].WriteString()) } else { // Default handler. for _, param := range op.Params { - buf.WriteString(param.DefaultWriteString()) + buf.WriteString(param.WriteString()) buf.WriteString(" ") } diff --git a/pdf/contentstream/inline-image.go b/pdf/contentstream/inline-image.go index a38487c7..39d34a0d 100644 --- a/pdf/contentstream/inline-image.go +++ b/pdf/contentstream/inline-image.go @@ -71,39 +71,39 @@ func NewInlineImageFromImage(img model.Image, encoder core.StreamEncoder) (*Cont func (img *ContentStreamInlineImage) String() string { s := fmt.Sprintf("InlineImage(len=%d)\n", len(img.stream)) if img.BitsPerComponent != nil { - s += "- BPC " + img.BitsPerComponent.DefaultWriteString() + "\n" + s += "- BPC " + img.BitsPerComponent.WriteString() + "\n" } if img.ColorSpace != nil { - s += "- CS " + img.ColorSpace.DefaultWriteString() + "\n" + s += "- CS " + img.ColorSpace.WriteString() + "\n" } if img.Decode != nil { - s += "- D " + img.Decode.DefaultWriteString() + "\n" + s += "- D " + img.Decode.WriteString() + "\n" } if img.DecodeParms != nil { - s += "- DP " + img.DecodeParms.DefaultWriteString() + "\n" + s += "- DP " + img.DecodeParms.WriteString() + "\n" } if img.Filter != nil { - s += "- F " + img.Filter.DefaultWriteString() + "\n" + s += "- F " + img.Filter.WriteString() + "\n" } if img.Height != nil { - s += "- H " + img.Height.DefaultWriteString() + "\n" + s += "- H " + img.Height.WriteString() + "\n" } if img.ImageMask != nil { - s += "- IM " + img.ImageMask.DefaultWriteString() + "\n" + s += "- IM " + img.ImageMask.WriteString() + "\n" } if img.Intent != nil { - s += "- Intent " + img.Intent.DefaultWriteString() + "\n" + s += "- Intent " + img.Intent.WriteString() + "\n" } if img.Interpolate != nil { - s += "- I " + img.Interpolate.DefaultWriteString() + "\n" + s += "- I " + img.Interpolate.WriteString() + "\n" } if img.Width != nil { - s += "- W " + img.Width.DefaultWriteString() + "\n" + s += "- W " + img.Width.WriteString() + "\n" } return s } -func (img *ContentStreamInlineImage) DefaultWriteString() string { +func (img *ContentStreamInlineImage) WriteString() string { var output bytes.Buffer // We do not start with "BI" as that is the operand and is written out separately. @@ -111,34 +111,34 @@ func (img *ContentStreamInlineImage) DefaultWriteString() string { s := "" if img.BitsPerComponent != nil { - s += "/BPC " + img.BitsPerComponent.DefaultWriteString() + "\n" + s += "/BPC " + img.BitsPerComponent.WriteString() + "\n" } if img.ColorSpace != nil { - s += "/CS " + img.ColorSpace.DefaultWriteString() + "\n" + s += "/CS " + img.ColorSpace.WriteString() + "\n" } if img.Decode != nil { - s += "/D " + img.Decode.DefaultWriteString() + "\n" + s += "/D " + img.Decode.WriteString() + "\n" } if img.DecodeParms != nil { - s += "/DP " + img.DecodeParms.DefaultWriteString() + "\n" + s += "/DP " + img.DecodeParms.WriteString() + "\n" } if img.Filter != nil { - s += "/F " + img.Filter.DefaultWriteString() + "\n" + s += "/F " + img.Filter.WriteString() + "\n" } if img.Height != nil { - s += "/H " + img.Height.DefaultWriteString() + "\n" + s += "/H " + img.Height.WriteString() + "\n" } if img.ImageMask != nil { - s += "/IM " + img.ImageMask.DefaultWriteString() + "\n" + s += "/IM " + img.ImageMask.WriteString() + "\n" } if img.Intent != nil { - s += "/Intent " + img.Intent.DefaultWriteString() + "\n" + s += "/Intent " + img.Intent.WriteString() + "\n" } if img.Interpolate != nil { - s += "/I " + img.Interpolate.DefaultWriteString() + "\n" + s += "/I " + img.Interpolate.WriteString() + "\n" } if img.Width != nil { - s += "/W " + img.Width.DefaultWriteString() + "\n" + s += "/W " + img.Width.WriteString() + "\n" } output.WriteString(s) @@ -198,7 +198,7 @@ func (img *ContentStreamInlineImage) GetEncoder() (core.StreamEncoder, error) { return newEncoderFromInlineImage(img) } -// IsMask check if an image is a mask. +// IsMask checks if an image is a mask. // The image mask entry in the image dictionary specifies that the image data shall be used as a stencil // mask for painting in the current color. The mask data is 1bpc, grayscale. func (img *ContentStreamInlineImage) IsMask() (bool, error) { @@ -216,7 +216,7 @@ func (img *ContentStreamInlineImage) IsMask() (bool, error) { } -// ToImage export the inline image to Image which can be transformed or exported easily. +// ToImage exports the inline image to Image which can be transformed or exported easily. // Page resources are needed to look up colorspace information. func (img *ContentStreamInlineImage) ToImage(resources *model.PdfPageResources) (*model.Image, error) { // Decode the imaging data if encoded. @@ -297,7 +297,7 @@ func (img *ContentStreamInlineImage) ToImage(resources *model.PdfPageResources) return image, nil } -// ParseInlineImage parses an inline image from a content stream, both read its properties and binary data. +// ParseInlineImage parses an inline image from a content stream, both reading its properties and binary data. // When called, "BI" has already been read from the stream. This function // finishes reading through "EI" and then returns the ContentStreamInlineImage. func (csp *ContentStreamParser) ParseInlineImage() (*ContentStreamInlineImage, error) { diff --git a/pdf/contentstream/processor.go b/pdf/contentstream/processor.go index cccc4b27..25c3f729 100644 --- a/pdf/contentstream/processor.go +++ b/pdf/contentstream/processor.go @@ -56,12 +56,12 @@ type HandlerEntry struct { type HandlerConditionEnum int -func (h HandlerConditionEnum) All() bool { - return h == HandlerConditionEnumAllOperands +func (e HandlerConditionEnum) All() bool { + return e == HandlerConditionEnumAllOperands } -func (h HandlerConditionEnum) Operand() bool { - return h == HandlerConditionEnumOperand +func (e HandlerConditionEnum) Operand() bool { + return e == HandlerConditionEnumOperand } const ( diff --git a/pdf/core/encoding.go b/pdf/core/encoding.go index 1e5231ca..b159b475 100644 --- a/pdf/core/encoding.go +++ b/pdf/core/encoding.go @@ -1116,7 +1116,7 @@ func (enc *RunLengthEncoder) GetFilterName() string { // Create a new run length decoder from a stream object. func newRunLengthEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObjectDictionary) (*RunLengthEncoder, error) { - // TODO(dennwc): unused paramaters; should verify that they are empty? + // TODO(dennwc): unused paramaters; check if it can have any in PDF spec return NewRunLengthEncoder(), nil } diff --git a/pdf/core/primitives.go b/pdf/core/primitives.go index 80366915..faf0bc99 100644 --- a/pdf/core/primitives.go +++ b/pdf/core/primitives.go @@ -20,8 +20,9 @@ type PdfObject interface { // String outputs a string representation of the primitive (for debugging). String() string - // DefaultWriteString outputs the PDF primitive as written to file as expected by the standard. - DefaultWriteString() string + // WriteString outputs the PDF primitive as written to file as expected by the standard. + // TODO(dennwc): it should return a byte slice, or accept a writer + WriteString() string } // PdfObjectBool represents the primitive PDF boolean object. @@ -242,8 +243,8 @@ func (bool *PdfObjectBool) String() string { return "false" } -// DefaultWriteString outputs the object as it is to be written to file. -func (bool *PdfObjectBool) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (bool *PdfObjectBool) WriteString() string { if *bool { return "true" } @@ -254,8 +255,8 @@ func (int *PdfObjectInteger) String() string { return fmt.Sprintf("%d", *int) } -// DefaultWriteString outputs the object as it is to be written to file. -func (int *PdfObjectInteger) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (int *PdfObjectInteger) WriteString() string { return fmt.Sprintf("%d", *int) } @@ -263,8 +264,8 @@ func (float *PdfObjectFloat) String() string { return fmt.Sprintf("%f", *float) } -// DefaultWriteString outputs the object as it is to be written to file. -func (float *PdfObjectFloat) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (float *PdfObjectFloat) WriteString() string { return fmt.Sprintf("%f", *float) } @@ -298,8 +299,8 @@ func (str *PdfObjectString) Bytes() []byte { return []byte(str.val) } -// DefaultWriteString outputs the object as it is to be written to file. -func (str *PdfObjectString) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (str *PdfObjectString) WriteString() string { var output bytes.Buffer // Handle hex representation. @@ -343,8 +344,8 @@ func (name *PdfObjectName) String() string { return string(*name) } -// DefaultWriteString outputs the object as it is to be written to file. -func (name *PdfObjectName) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (name *PdfObjectName) WriteString() string { var output bytes.Buffer if len(*name) > 127 { @@ -483,11 +484,11 @@ func (array *PdfObjectArray) String() string { return outStr } -// DefaultWriteString outputs the object as it is to be written to file. -func (array *PdfObjectArray) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (array *PdfObjectArray) WriteString() string { outStr := "[" for ind, o := range array.Elements() { - outStr += o.DefaultWriteString() + outStr += o.WriteString() if ind < (array.Len() - 1) { outStr += " " } @@ -594,15 +595,15 @@ func (d *PdfObjectDictionary) String() string { return outStr } -// DefaultWriteString outputs the object as it is to be written to file. -func (d *PdfObjectDictionary) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (d *PdfObjectDictionary) WriteString() string { outStr := "<<" for _, k := range d.keys { v := d.dict[k] common.Log.Trace("Writing k: %s %T %v %v", k, v, k, v) - outStr += k.DefaultWriteString() + outStr += k.WriteString() outStr += " " - outStr += v.DefaultWriteString() + outStr += v.WriteString() } outStr += ">>" return outStr @@ -735,8 +736,8 @@ func (ref *PdfObjectReference) String() string { return fmt.Sprintf("Ref(%d %d)", ref.ObjectNumber, ref.GenerationNumber) } -// DefaultWriteString outputs the object as it is to be written to file. -func (ref *PdfObjectReference) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (ref *PdfObjectReference) WriteString() string { return fmt.Sprintf("%d %d R", ref.ObjectNumber, ref.GenerationNumber) } @@ -747,8 +748,8 @@ func (ind *PdfIndirectObject) String() string { return fmt.Sprintf("IObject:%d", (*ind).ObjectNumber) } -// DefaultWriteString outputs the object as it is to be written to file. -func (ind *PdfIndirectObject) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (ind *PdfIndirectObject) WriteString() string { outStr := fmt.Sprintf("%d 0 R", (*ind).ObjectNumber) return outStr } @@ -758,8 +759,8 @@ func (stream *PdfObjectStream) String() string { return fmt.Sprintf("Object stream %d: %s", stream.ObjectNumber, stream.PdfObjectDictionary) } -// DefaultWriteString outputs the object as it is to be written to file. -func (stream *PdfObjectStream) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (stream *PdfObjectStream) WriteString() string { outStr := fmt.Sprintf("%d 0 R", (*stream).ObjectNumber) return outStr } @@ -769,8 +770,8 @@ func (null *PdfObjectNull) String() string { return "null" } -// DefaultWriteString outputs the object as it is to be written to file. -func (null *PdfObjectNull) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (null *PdfObjectNull) WriteString() string { return "null" } @@ -969,8 +970,8 @@ func (streams *PdfObjectStreams) Len() int { return len(streams.vec) } -// DefaultWriteString outputs the object as it is to be written to file. -func (streams *PdfObjectStreams) DefaultWriteString() string { +// WriteString outputs the object as it is to be written to file. +func (streams *PdfObjectStreams) WriteString() string { outStr := fmt.Sprintf("%d 0 R", (*streams).ObjectNumber) return outStr } diff --git a/pdf/core/primitives_test.go b/pdf/core/primitives_test.go index ee6b8e7b..26c6593e 100644 --- a/pdf/core/primitives_test.go +++ b/pdf/core/primitives_test.go @@ -16,7 +16,7 @@ func TestHexStringWriteBasic(t *testing.T) { for src, expected := range testcases { strObj := MakeHexString(src) - ws := strObj.DefaultWriteString() + ws := strObj.WriteString() if ws != expected { t.Fatalf("%s: '%s' != '%s'\n", src, ws, expected) @@ -39,8 +39,8 @@ func TestHexStringMulti(t *testing.T) { shex := MakeHexString(testcase) // Write out. - writestr := s.DefaultWriteString() - writestrhex := shex.DefaultWriteString() + writestr := s.WriteString() + writestrhex := shex.WriteString() // Parse back. parser1 := makeParserForText(writestr) diff --git a/pdf/creator/styled_paragraph.go b/pdf/creator/styled_paragraph.go index cf2c43d1..e75c85a9 100644 --- a/pdf/creator/styled_paragraph.go +++ b/pdf/creator/styled_paragraph.go @@ -387,8 +387,6 @@ func (p *StyledParagraph) wrapText() error { metrics, found := style.Font.GetGlyphCharMetrics(glyph) if !found { common.Log.Debug("Glyph char metrics not found! %s\n", glyph) - - // FIXME: return error. return errors.New("Glyph char metrics missing") } diff --git a/pdf/internal/cmap/cmap_test.go b/pdf/internal/cmap/cmap_test.go index 6e402e20..5c8da78d 100644 --- a/pdf/internal/cmap/cmap_test.go +++ b/pdf/internal/cmap/cmap_test.go @@ -672,12 +672,12 @@ func checkCmapWriteRead(t *testing.T, codeToUnicode map[CharCode]rune) { return } - var codes0 []CharCode + codes0 := make([]CharCode, 0, len(codeToUnicode)) for code := range codeToUnicode { codes0 = append(codes0, code) } sort.Slice(codes0, func(i, j int) bool { return codes0[i] < codes0[j] }) - var codes []CharCode + codes := make([]CharCode, 0, len(cmap.codeToUnicode)) for code := range cmap.codeToUnicode { codes = append(codes, code) } diff --git a/pdf/internal/testutils/testutils.go b/pdf/internal/testutils/testutils.go index 4d16c760..64cfa10d 100644 --- a/pdf/internal/testutils/testutils.go +++ b/pdf/internal/testutils/testutils.go @@ -86,7 +86,7 @@ func resolveReferences(obj core.PdfObject, objmap map[int64]core.PdfObject) erro func CompareDictionariesDeep(d1, d2 *core.PdfObjectDictionary) bool { if len(d1.Keys()) != len(d2.Keys()) { common.Log.Debug("Dict entries mismatch (%d != %d)", len(d1.Keys()), len(d2.Keys())) - common.Log.Debug("Was '%s' vs '%s'", d1.DefaultWriteString(), d2.DefaultWriteString()) + common.Log.Debug("Was '%s' vs '%s'", d1.WriteString(), d2.WriteString()) return false } @@ -140,8 +140,8 @@ func CompareDictionariesDeep(d1, d2 *core.PdfObjectDictionary) bool { return false } } else { - if v1.DefaultWriteString() != v2.DefaultWriteString() { - common.Log.Debug("Mismatch '%s' != '%s'", v1.DefaultWriteString(), v2.DefaultWriteString()) + if v1.WriteString() != v2.WriteString() { + common.Log.Debug("Mismatch '%s' != '%s'", v1.WriteString(), v2.WriteString()) return false } } diff --git a/pdf/model/colorspace.go b/pdf/model/colorspace.go index 3ba1b4d3..6bac7aad 100644 --- a/pdf/model/colorspace.go +++ b/pdf/model/colorspace.go @@ -211,18 +211,18 @@ func NewPdfColorDeviceGray(grayVal float64) *PdfColorDeviceGray { } // GetNumComponents returns the number of color components (1 for grayscale). -func (cl *PdfColorDeviceGray) GetNumComponents() int { +func (col *PdfColorDeviceGray) GetNumComponents() int { return 1 } -func (cl *PdfColorDeviceGray) Val() float64 { - return float64(*cl) +func (col *PdfColorDeviceGray) Val() float64 { + return float64(*col) } // ToInteger convert to an integer format. -func (cl *PdfColorDeviceGray) ToInteger(bits int) uint32 { +func (col *PdfColorDeviceGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return uint32(maxVal * cl.Val()) + return uint32(maxVal * col.Val()) } type PdfColorspaceDeviceGray struct{} @@ -231,24 +231,24 @@ func NewPdfColorspaceDeviceGray() *PdfColorspaceDeviceGray { return &PdfColorspaceDeviceGray{} } -func (cl *PdfColorspaceDeviceGray) GetNumComponents() int { +func (cs *PdfColorspaceDeviceGray) GetNumComponents() int { return 1 } // DecodeArray returns the range of color component values in DeviceGray colorspace. -func (cl *PdfColorspaceDeviceGray) DecodeArray() []float64 { +func (cs *PdfColorspaceDeviceGray) DecodeArray() []float64 { return []float64{0, 1.0} } -func (cl *PdfColorspaceDeviceGray) ToPdfObject() PdfObject { +func (cs *PdfColorspaceDeviceGray) ToPdfObject() PdfObject { return MakeName("DeviceGray") } -func (cl *PdfColorspaceDeviceGray) String() string { +func (cs *PdfColorspaceDeviceGray) String() string { return "DeviceGray" } -func (cl *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } @@ -269,7 +269,7 @@ func (cl *PdfColorspaceDeviceGray) ColorFromFloats(vals []float64) (PdfColor, er return NewPdfColorDeviceGray(val), nil } -func (cl *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -279,11 +279,11 @@ func (cl *PdfColorspaceDeviceGray) ColorFromPdfObjects(objects []PdfObject) (Pdf return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } // ColorToRGB converts gray -> rgb for a single color component. -func (cl *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) { gray, ok := color.(*PdfColorDeviceGray) if !ok { common.Log.Debug("Input color not device gray %T", color) @@ -294,7 +294,7 @@ func (cl *PdfColorspaceDeviceGray) ColorToRGB(color PdfColor) (PdfColor, error) } // ImageToRGB convert 1-component grayscale data to 3-component RGB. -func (cl *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceDeviceGray) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -327,31 +327,31 @@ func NewPdfColorDeviceRGB(r, g, b float64) *PdfColorDeviceRGB { return &color } -func (cl *PdfColorDeviceRGB) GetNumComponents() int { +func (col *PdfColorDeviceRGB) GetNumComponents() int { return 3 } -func (cl *PdfColorDeviceRGB) R() float64 { - return float64(cl[0]) +func (col *PdfColorDeviceRGB) R() float64 { + return float64(col[0]) } -func (cl *PdfColorDeviceRGB) G() float64 { - return float64(cl[1]) +func (col *PdfColorDeviceRGB) G() float64 { + return float64(col[1]) } -func (cl *PdfColorDeviceRGB) B() float64 { - return float64(cl[2]) +func (col *PdfColorDeviceRGB) B() float64 { + return float64(col[2]) } // ToInteger convert to an integer format. -func (cl *PdfColorDeviceRGB) ToInteger(bits int) [3]uint32 { +func (col *PdfColorDeviceRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * cl.R()), uint32(maxVal * cl.G()), uint32(maxVal * cl.B())} + return [3]uint32{uint32(maxVal * col.R()), uint32(maxVal * col.G()), uint32(maxVal * col.B())} } -func (cl *PdfColorDeviceRGB) ToGray() *PdfColorDeviceGray { +func (col *PdfColorDeviceRGB) ToGray() *PdfColorDeviceGray { // Calculate grayValue [0-1] - grayValue := 0.3*cl.R() + 0.59*cl.G() + 0.11*cl.B() + grayValue := 0.3*col.R() + 0.59*col.G() + 0.11*col.B() // Clip to [0-1] grayValue = math.Min(math.Max(grayValue, 0.0), 1.0) @@ -367,24 +367,24 @@ func NewPdfColorspaceDeviceRGB() *PdfColorspaceDeviceRGB { return &PdfColorspaceDeviceRGB{} } -func (cl *PdfColorspaceDeviceRGB) String() string { +func (cs *PdfColorspaceDeviceRGB) String() string { return "DeviceRGB" } -func (cl *PdfColorspaceDeviceRGB) GetNumComponents() int { +func (cs *PdfColorspaceDeviceRGB) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in DeviceRGB colorspace. -func (cl *PdfColorspaceDeviceRGB) DecodeArray() []float64 { +func (cs *PdfColorspaceDeviceRGB) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } -func (cl *PdfColorspaceDeviceRGB) ToPdfObject() PdfObject { +func (cs *PdfColorspaceDeviceRGB) ToPdfObject() PdfObject { return MakeName("DeviceRGB") } -func (cl *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -413,7 +413,7 @@ func (cl *PdfColorspaceDeviceRGB) ColorFromFloats(vals []float64) (PdfColor, err } // ColorFromPdfObjects gets the color from a series of pdf objects (3 for rgb). -func (cl *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -423,10 +423,10 @@ func (cl *PdfColorspaceDeviceRGB) ColorFromPdfObjects(objects []PdfObject) (PdfC return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) { rgb, ok := color.(*PdfColorDeviceRGB) if !ok { common.Log.Debug("Input color not device RGB") @@ -435,11 +435,11 @@ func (cl *PdfColorspaceDeviceRGB) ColorToRGB(color PdfColor) (PdfColor, error) { return rgb, nil } -func (cl *PdfColorspaceDeviceRGB) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceDeviceRGB) ImageToRGB(img Image) (Image, error) { return img, nil } -func (cl *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { +func (cs *PdfColorspaceDeviceRGB) ImageToGray(img Image) (Image, error) { grayImage := img samples := img.GetSamples() @@ -481,30 +481,30 @@ func NewPdfColorDeviceCMYK(c, m, y, k float64) *PdfColorDeviceCMYK { return &color } -func (cl *PdfColorDeviceCMYK) GetNumComponents() int { +func (col *PdfColorDeviceCMYK) GetNumComponents() int { return 4 } -func (cl *PdfColorDeviceCMYK) C() float64 { - return float64(cl[0]) +func (col *PdfColorDeviceCMYK) C() float64 { + return float64(col[0]) } -func (cl *PdfColorDeviceCMYK) M() float64 { - return float64(cl[1]) +func (col *PdfColorDeviceCMYK) M() float64 { + return float64(col[1]) } -func (cl *PdfColorDeviceCMYK) Y() float64 { - return float64(cl[2]) +func (col *PdfColorDeviceCMYK) Y() float64 { + return float64(col[2]) } -func (cl *PdfColorDeviceCMYK) K() float64 { - return float64(cl[3]) +func (col *PdfColorDeviceCMYK) K() float64 { + return float64(col[3]) } // ToInteger convert to an integer format. -func (cl *PdfColorDeviceCMYK) ToInteger(bits int) [4]uint32 { +func (col *PdfColorDeviceCMYK) ToInteger(bits int) [4]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [4]uint32{uint32(maxVal * cl.C()), uint32(maxVal * cl.M()), uint32(maxVal * cl.Y()), uint32(maxVal * cl.K())} + return [4]uint32{uint32(maxVal * col.C()), uint32(maxVal * col.M()), uint32(maxVal * col.Y()), uint32(maxVal * col.K())} } type PdfColorspaceDeviceCMYK struct{} @@ -513,24 +513,24 @@ func NewPdfColorspaceDeviceCMYK() *PdfColorspaceDeviceCMYK { return &PdfColorspaceDeviceCMYK{} } -func (cl *PdfColorspaceDeviceCMYK) String() string { +func (cs *PdfColorspaceDeviceCMYK) String() string { return "DeviceCMYK" } -func (cl *PdfColorspaceDeviceCMYK) GetNumComponents() int { +func (cs *PdfColorspaceDeviceCMYK) GetNumComponents() int { return 4 } // DecodeArray returns the range of color component values in DeviceCMYK colorspace. -func (cl *PdfColorspaceDeviceCMYK) DecodeArray() []float64 { +func (cs *PdfColorspaceDeviceCMYK) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } -func (cl *PdfColorspaceDeviceCMYK) ToPdfObject() PdfObject { +func (cs *PdfColorspaceDeviceCMYK) ToPdfObject() PdfObject { return MakeName("DeviceCMYK") } -func (cl *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 4 { return nil, errors.New("Range check") } @@ -564,7 +564,7 @@ func (cl *PdfColorspaceDeviceCMYK) ColorFromFloats(vals []float64) (PdfColor, er } // ColorFromPdfObjects gets the color from a series of pdf objects (4 for cmyk). -func (cl *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 4 { return nil, errors.New("Range check") } @@ -574,10 +574,10 @@ func (cl *PdfColorspaceDeviceCMYK) ColorFromPdfObjects(objects []PdfObject) (Pdf return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error) { cmyk, ok := color.(*PdfColorDeviceCMYK) if !ok { common.Log.Debug("Input color not device cmyk") @@ -601,7 +601,7 @@ func (cl *PdfColorspaceDeviceCMYK) ColorToRGB(color PdfColor) (PdfColor, error) } // ImageToRGB converts an image in CMYK colorspace to an RGB image. -func (cl *PdfColorspaceDeviceCMYK) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceDeviceCMYK) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -671,18 +671,18 @@ func NewPdfColorCalGray(grayVal float64) *PdfColorCalGray { return &color } -func (cl *PdfColorCalGray) GetNumComponents() int { +func (col *PdfColorCalGray) GetNumComponents() int { return 1 } -func (cl *PdfColorCalGray) Val() float64 { - return float64(*cl) +func (col *PdfColorCalGray) Val() float64 { + return float64(*col) } // ToInteger convert to an integer format. -func (cl *PdfColorCalGray) ToInteger(bits int) uint32 { +func (col *PdfColorCalGray) ToInteger(bits int) uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return uint32(maxVal * cl.Val()) + return uint32(maxVal * col.Val()) } // PdfColorspaceCalGray represents CalGray color space. @@ -704,16 +704,16 @@ func NewPdfColorspaceCalGray() *PdfColorspaceCalGray { return cs } -func (cl *PdfColorspaceCalGray) String() string { +func (cs *PdfColorspaceCalGray) String() string { return "CalGray" } -func (cl *PdfColorspaceCalGray) GetNumComponents() int { +func (cs *PdfColorspaceCalGray) GetNumComponents() int { return 1 } // DecodeArray returns the range of color component values in CalGray colorspace. -func (cl *PdfColorspaceCalGray) DecodeArray() []float64 { +func (cs *PdfColorspaceCalGray) DecodeArray() []float64 { return []float64{0.0, 1.0} } @@ -803,35 +803,35 @@ func newPdfColorspaceCalGrayFromPdfObject(obj PdfObject) (*PdfColorspaceCalGray, } // ToPdfObject return the CalGray colorspace as a PDF object (name dictionary). -func (cl *PdfColorspaceCalGray) ToPdfObject() PdfObject { +func (cs *PdfColorspaceCalGray) ToPdfObject() PdfObject { // CalGray color space dictionary.. cspace := &PdfObjectArray{} cspace.Append(MakeName("CalGray")) dict := MakeDict() - if cl.WhitePoint != nil { - dict.Set("WhitePoint", MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2]))) + if cs.WhitePoint != nil { + dict.Set("WhitePoint", MakeArray(MakeFloat(cs.WhitePoint[0]), MakeFloat(cs.WhitePoint[1]), MakeFloat(cs.WhitePoint[2]))) } else { common.Log.Error("CalGray: Missing WhitePoint (Required)") } - if cl.BlackPoint != nil { - dict.Set("BlackPoint", MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2]))) + if cs.BlackPoint != nil { + dict.Set("BlackPoint", MakeArray(MakeFloat(cs.BlackPoint[0]), MakeFloat(cs.BlackPoint[1]), MakeFloat(cs.BlackPoint[2]))) } - dict.Set("Gamma", MakeFloat(cl.Gamma)) + dict.Set("Gamma", MakeFloat(cs.Gamma)) cspace.Append(dict) - if cl.container != nil { - cl.container.PdfObject = cspace - return cl.container + if cs.container != nil { + cs.container.PdfObject = cspace + return cs.container } return cspace } -func (cl *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } @@ -845,7 +845,7 @@ func (cl *PdfColorspaceCalGray) ColorFromFloats(vals []float64) (PdfColor, error return color, nil } -func (cl *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -855,10 +855,10 @@ func (cl *PdfColorspaceCalGray) ColorFromPdfObjects(objects []PdfObject) (PdfCol return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { calgray, ok := color.(*PdfColorCalGray) if !ok { common.Log.Debug("Input color not cal gray") @@ -868,9 +868,9 @@ func (cl *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { ANorm := calgray.Val() // A -> X,Y,Z - X := cl.WhitePoint[0] * math.Pow(ANorm, cl.Gamma) - Y := cl.WhitePoint[1] * math.Pow(ANorm, cl.Gamma) - Z := cl.WhitePoint[2] * math.Pow(ANorm, cl.Gamma) + X := cs.WhitePoint[0] * math.Pow(ANorm, cs.Gamma) + Y := cs.WhitePoint[1] * math.Pow(ANorm, cs.Gamma) + Z := cs.WhitePoint[2] * math.Pow(ANorm, cs.Gamma) // X,Y,Z -> rgb // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -887,7 +887,7 @@ func (cl *PdfColorspaceCalGray) ColorToRGB(color PdfColor) (PdfColor, error) { } // ImageToRGB converts image in CalGray color space to RGB (A, B, C -> X, Y, Z). -func (cl *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -900,9 +900,9 @@ func (cl *PdfColorspaceCalGray) ImageToRGB(img Image) (Image, error) { ANorm := float64(samples[i]) / maxVal // A -> X,Y,Z - X := cl.WhitePoint[0] * math.Pow(ANorm, cl.Gamma) - Y := cl.WhitePoint[1] * math.Pow(ANorm, cl.Gamma) - Z := cl.WhitePoint[2] * math.Pow(ANorm, cl.Gamma) + X := cs.WhitePoint[0] * math.Pow(ANorm, cs.Gamma) + Y := cs.WhitePoint[1] * math.Pow(ANorm, cs.Gamma) + Z := cs.WhitePoint[2] * math.Pow(ANorm, cs.Gamma) // X,Y,Z -> rgb // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -940,26 +940,26 @@ func NewPdfColorCalRGB(a, b, c float64) *PdfColorCalRGB { return &color } -func (cl *PdfColorCalRGB) GetNumComponents() int { +func (col *PdfColorCalRGB) GetNumComponents() int { return 3 } -func (cl *PdfColorCalRGB) A() float64 { - return float64(cl[0]) +func (col *PdfColorCalRGB) A() float64 { + return float64(col[0]) } -func (cl *PdfColorCalRGB) B() float64 { - return float64(cl[1]) +func (col *PdfColorCalRGB) B() float64 { + return float64(col[1]) } -func (cl *PdfColorCalRGB) C() float64 { - return float64(cl[2]) +func (col *PdfColorCalRGB) C() float64 { + return float64(col[2]) } // ToInteger convert to an integer format. -func (cl *PdfColorCalRGB) ToInteger(bits int) [3]uint32 { +func (col *PdfColorCalRGB) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * cl.A()), uint32(maxVal * cl.B()), uint32(maxVal * cl.C())} + return [3]uint32{uint32(maxVal * col.A()), uint32(maxVal * col.B()), uint32(maxVal * col.C())} } // PdfColorspaceCalRGB stores A, B, C components @@ -985,16 +985,16 @@ func NewPdfColorspaceCalRGB() *PdfColorspaceCalRGB { return cs } -func (cl *PdfColorspaceCalRGB) String() string { +func (cs *PdfColorspaceCalRGB) String() string { return "CalRGB" } -func (cl *PdfColorspaceCalRGB) GetNumComponents() int { +func (cs *PdfColorspaceCalRGB) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in CalRGB colorspace. -func (cl *PdfColorspaceCalRGB) DecodeArray() []float64 { +func (cs *PdfColorspaceCalRGB) DecodeArray() []float64 { return []float64{0.0, 1.0, 0.0, 1.0, 0.0, 1.0} } @@ -1107,45 +1107,45 @@ func newPdfColorspaceCalRGBFromPdfObject(obj PdfObject) (*PdfColorspaceCalRGB, e } // ToPdfObject returns colorspace in a PDF object format [name dictionary] -func (cl *PdfColorspaceCalRGB) ToPdfObject() PdfObject { +func (cs *PdfColorspaceCalRGB) ToPdfObject() PdfObject { // CalRGB color space dictionary.. cspace := &PdfObjectArray{} cspace.Append(MakeName("CalRGB")) dict := MakeDict() - if cl.WhitePoint != nil { - wp := MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2])) + if cs.WhitePoint != nil { + wp := MakeArray(MakeFloat(cs.WhitePoint[0]), MakeFloat(cs.WhitePoint[1]), MakeFloat(cs.WhitePoint[2])) dict.Set("WhitePoint", wp) } else { common.Log.Error("CalRGB: Missing WhitePoint (Required)") } - if cl.BlackPoint != nil { - bp := MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2])) + if cs.BlackPoint != nil { + bp := MakeArray(MakeFloat(cs.BlackPoint[0]), MakeFloat(cs.BlackPoint[1]), MakeFloat(cs.BlackPoint[2])) dict.Set("BlackPoint", bp) } - if cl.Gamma != nil { - g := MakeArray(MakeFloat(cl.Gamma[0]), MakeFloat(cl.Gamma[1]), MakeFloat(cl.Gamma[2])) + if cs.Gamma != nil { + g := MakeArray(MakeFloat(cs.Gamma[0]), MakeFloat(cs.Gamma[1]), MakeFloat(cs.Gamma[2])) dict.Set("Gamma", g) } - if cl.Matrix != nil { - matrix := MakeArray(MakeFloat(cl.Matrix[0]), MakeFloat(cl.Matrix[1]), MakeFloat(cl.Matrix[2]), - MakeFloat(cl.Matrix[3]), MakeFloat(cl.Matrix[4]), MakeFloat(cl.Matrix[5]), - MakeFloat(cl.Matrix[6]), MakeFloat(cl.Matrix[7]), MakeFloat(cl.Matrix[8])) + if cs.Matrix != nil { + matrix := MakeArray(MakeFloat(cs.Matrix[0]), MakeFloat(cs.Matrix[1]), MakeFloat(cs.Matrix[2]), + MakeFloat(cs.Matrix[3]), MakeFloat(cs.Matrix[4]), MakeFloat(cs.Matrix[5]), + MakeFloat(cs.Matrix[6]), MakeFloat(cs.Matrix[7]), MakeFloat(cs.Matrix[8])) dict.Set("Matrix", matrix) } cspace.Append(dict) - if cl.container != nil { - cl.container.PdfObject = cspace - return cl.container + if cs.container != nil { + cs.container.PdfObject = cspace + return cs.container } return cspace } -func (cl *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -1172,7 +1172,7 @@ func (cl *PdfColorspaceCalRGB) ColorFromFloats(vals []float64) (PdfColor, error) return color, nil } -func (cl *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -1182,10 +1182,10 @@ func (cl *PdfColorspaceCalRGB) ColorFromPdfObjects(objects []PdfObject) (PdfColo return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { calrgb, ok := color.(*PdfColorCalRGB) if !ok { common.Log.Debug("Input color not cal rgb") @@ -1200,9 +1200,9 @@ func (cl *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { // A, B, C -> X,Y,Z // Gamma [GR GC GB] // Matrix [XA YA ZA XB YB ZB XC YC ZC] - X := cl.Matrix[0]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[3]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[6]*math.Pow(cVal, cl.Gamma[2]) - Y := cl.Matrix[1]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[4]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[7]*math.Pow(cVal, cl.Gamma[2]) - Z := cl.Matrix[2]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[5]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[8]*math.Pow(cVal, cl.Gamma[2]) + X := cs.Matrix[0]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[3]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[6]*math.Pow(cVal, cs.Gamma[2]) + Y := cs.Matrix[1]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[4]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[7]*math.Pow(cVal, cs.Gamma[2]) + Z := cs.Matrix[2]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[5]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[8]*math.Pow(cVal, cs.Gamma[2]) // X, Y, Z -> R, G, B // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -1218,7 +1218,7 @@ func (cl *PdfColorspaceCalRGB) ColorToRGB(color PdfColor) (PdfColor, error) { return NewPdfColorDeviceRGB(r, g, b), nil } -func (cl *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { rgbImage := img samples := img.GetSamples() @@ -1234,9 +1234,9 @@ func (cl *PdfColorspaceCalRGB) ImageToRGB(img Image) (Image, error) { // A, B, C -> X,Y,Z // Gamma [GR GC GB] // Matrix [XA YA ZA XB YB ZB XC YC ZC] - X := cl.Matrix[0]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[3]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[6]*math.Pow(cVal, cl.Gamma[2]) - Y := cl.Matrix[1]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[4]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[7]*math.Pow(cVal, cl.Gamma[2]) - Z := cl.Matrix[2]*math.Pow(aVal, cl.Gamma[0]) + cl.Matrix[5]*math.Pow(bVal, cl.Gamma[1]) + cl.Matrix[8]*math.Pow(cVal, cl.Gamma[2]) + X := cs.Matrix[0]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[3]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[6]*math.Pow(cVal, cs.Gamma[2]) + Y := cs.Matrix[1]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[4]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[7]*math.Pow(cVal, cs.Gamma[2]) + Z := cs.Matrix[2]*math.Pow(aVal, cs.Gamma[0]) + cs.Matrix[5]*math.Pow(bVal, cs.Gamma[1]) + cs.Matrix[8]*math.Pow(cVal, cs.Gamma[2]) // X, Y, Z -> R, G, B // http://stackoverflow.com/questions/21576719/how-to-convert-cie-color-space-into-rgb-or-hex-color-code-in-php @@ -1273,26 +1273,26 @@ func NewPdfColorLab(l, a, b float64) *PdfColorLab { return &color } -func (cl *PdfColorLab) GetNumComponents() int { +func (col *PdfColorLab) GetNumComponents() int { return 3 } -func (cl *PdfColorLab) L() float64 { - return float64(cl[0]) +func (col *PdfColorLab) L() float64 { + return float64(col[0]) } -func (cl *PdfColorLab) A() float64 { - return float64(cl[1]) +func (col *PdfColorLab) A() float64 { + return float64(col[1]) } -func (cl *PdfColorLab) B() float64 { - return float64(cl[2]) +func (col *PdfColorLab) B() float64 { + return float64(col[2]) } // ToInteger convert to an integer format. -func (cl *PdfColorLab) ToInteger(bits int) [3]uint32 { +func (col *PdfColorLab) ToInteger(bits int) [3]uint32 { maxVal := math.Pow(2, float64(bits)) - 1 - return [3]uint32{uint32(maxVal * cl.L()), uint32(maxVal * cl.A()), uint32(maxVal * cl.B())} + return [3]uint32{uint32(maxVal * col.L()), uint32(maxVal * col.A()), uint32(maxVal * col.B())} } // PdfColorspaceLab is a L*, a*, b* 3 component colorspace. @@ -1304,22 +1304,22 @@ type PdfColorspaceLab struct { container *PdfIndirectObject } -func (cl *PdfColorspaceLab) String() string { +func (cs *PdfColorspaceLab) String() string { return "Lab" } -func (cl *PdfColorspaceLab) GetNumComponents() int { +func (cs *PdfColorspaceLab) GetNumComponents() int { return 3 } // DecodeArray returns the range of color component values in the Lab colorspace. -func (cl *PdfColorspaceLab) DecodeArray() []float64 { +func (cs *PdfColorspaceLab) DecodeArray() []float64 { // Range for L decode := []float64{0, 100} // Range for A,B specified by range or default - if cl.Range != nil && len(cl.Range) == 4 { - decode = append(decode, cl.Range...) + if cs.Range != nil && len(cs.Range) == 4 { + decode = append(decode, cs.Range...) } else { decode = append(decode, -100, 100, -100, 100) } @@ -1430,40 +1430,40 @@ func newPdfColorspaceLabFromPdfObject(obj PdfObject) (*PdfColorspaceLab, error) } // ToPdfObject returns colorspace in a PDF object format [name dictionary] -func (cl *PdfColorspaceLab) ToPdfObject() PdfObject { +func (cs *PdfColorspaceLab) ToPdfObject() PdfObject { // CalRGB color space dictionary.. csObj := MakeArray() csObj.Append(MakeName("Lab")) dict := MakeDict() - if cl.WhitePoint != nil { - wp := MakeArray(MakeFloat(cl.WhitePoint[0]), MakeFloat(cl.WhitePoint[1]), MakeFloat(cl.WhitePoint[2])) + if cs.WhitePoint != nil { + wp := MakeArray(MakeFloat(cs.WhitePoint[0]), MakeFloat(cs.WhitePoint[1]), MakeFloat(cs.WhitePoint[2])) dict.Set("WhitePoint", wp) } else { common.Log.Error("Lab: Missing WhitePoint (Required)") } - if cl.BlackPoint != nil { - bp := MakeArray(MakeFloat(cl.BlackPoint[0]), MakeFloat(cl.BlackPoint[1]), MakeFloat(cl.BlackPoint[2])) + if cs.BlackPoint != nil { + bp := MakeArray(MakeFloat(cs.BlackPoint[0]), MakeFloat(cs.BlackPoint[1]), MakeFloat(cs.BlackPoint[2])) dict.Set("BlackPoint", bp) } - if cl.Range != nil { - val := MakeArray(MakeFloat(cl.Range[0]), MakeFloat(cl.Range[1]), MakeFloat(cl.Range[2]), MakeFloat(cl.Range[3])) + if cs.Range != nil { + val := MakeArray(MakeFloat(cs.Range[0]), MakeFloat(cs.Range[1]), MakeFloat(cs.Range[2]), MakeFloat(cs.Range[3])) dict.Set("Range", val) } csObj.Append(dict) - if cl.container != nil { - cl.container.PdfObject = csObj - return cl.container + if cs.container != nil { + cs.container.PdfObject = csObj + return cs.container } return csObj } -func (cl *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 3 { return nil, errors.New("Range check") } @@ -1479,9 +1479,9 @@ func (cl *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { a := vals[1] aMin := float64(-100) aMax := float64(100) - if len(cl.Range) > 1 { - aMin = cl.Range[0] - aMax = cl.Range[1] + if len(cs.Range) > 1 { + aMin = cs.Range[0] + aMax = cs.Range[1] } if a < aMin || a > aMax { common.Log.Debug("A out of range (got %v; range %v to %v)", a, aMin, aMax) @@ -1492,9 +1492,9 @@ func (cl *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { b := vals[2] bMin := float64(-100) bMax := float64(100) - if len(cl.Range) > 3 { - bMin = cl.Range[2] - bMax = cl.Range[3] + if len(cs.Range) > 3 { + bMin = cs.Range[2] + bMax = cs.Range[3] } if b < bMin || b > bMax { common.Log.Debug("b out of range (got %v; range %v to %v)", b, bMin, bMax) @@ -1505,7 +1505,7 @@ func (cl *PdfColorspaceLab) ColorFromFloats(vals []float64) (PdfColor, error) { return color, nil } -func (cl *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 3 { return nil, errors.New("Range check") } @@ -1515,10 +1515,10 @@ func (cl *PdfColorspaceLab) ColorFromPdfObjects(objects []PdfObject) (PdfColor, return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { gFunc := func(x float64) float64 { if x >= 6.0/29 { return x * x * x @@ -1544,9 +1544,9 @@ func (cl *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { N := (LStar+16)/116 - BStar/200 // L, M, N -> X,Y,Z - X := cl.WhitePoint[0] * gFunc(L) - Y := cl.WhitePoint[1] * gFunc(M) - Z := cl.WhitePoint[2] * gFunc(N) + X := cs.WhitePoint[0] * gFunc(L) + Y := cs.WhitePoint[1] * gFunc(M) + Z := cs.WhitePoint[2] * gFunc(N) // Convert to RGB. // X, Y, Z -> R, G, B @@ -1563,7 +1563,7 @@ func (cl *PdfColorspaceLab) ColorToRGB(color PdfColor) (PdfColor, error) { return NewPdfColorDeviceRGB(r, g, b), nil } -func (cl *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { g := func(x float64) float64 { if x >= 6.0/29 { return x * x * x @@ -1583,7 +1583,7 @@ func (cl *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { if len(componentRanges) != 6 { // If image's Decode not appropriate, fall back to default decode array. common.Log.Trace("Image - Lab Decode range != 6... use [0 100 amin amax bmin bmax] default decode array") - componentRanges = cl.DecodeArray() + componentRanges = cs.DecodeArray() } samples := img.GetSamples() @@ -1606,9 +1606,9 @@ func (cl *PdfColorspaceLab) ImageToRGB(img Image) (Image, error) { N := (LStar+16)/116 - BStar/200 // L, M, N -> X,Y,Z - X := cl.WhitePoint[0] * g(L) - Y := cl.WhitePoint[1] * g(M) - Z := cl.WhitePoint[2] * g(N) + X := cs.WhitePoint[0] * g(L) + Y := cs.WhitePoint[1] * g(M) + Z := cs.WhitePoint[2] * g(N) // Convert to RGB. // X, Y, Z -> R, G, B @@ -1688,16 +1688,16 @@ type PdfColorspaceICCBased struct { stream *PdfObjectStream } -func (cl *PdfColorspaceICCBased) GetNumComponents() int { - return cl.N +func (cs *PdfColorspaceICCBased) GetNumComponents() int { + return cs.N } // DecodeArray returns the range of color component values in the ICCBased colorspace. -func (cl *PdfColorspaceICCBased) DecodeArray() []float64 { - return cl.Range +func (cs *PdfColorspaceICCBased) DecodeArray() []float64 { + return cs.Range } -func (cl *PdfColorspaceICCBased) String() string { +func (cs *PdfColorspaceICCBased) String() string { return "ICCBased" } @@ -1802,61 +1802,61 @@ func newPdfColorspaceICCBasedFromPdfObject(obj PdfObject) (*PdfColorspaceICCBase } // ToPdfObject returns colorspace in a PDF object format [name stream] -func (cl *PdfColorspaceICCBased) ToPdfObject() PdfObject { +func (cs *PdfColorspaceICCBased) ToPdfObject() PdfObject { csObj := &PdfObjectArray{} csObj.Append(MakeName("ICCBased")) var stream *PdfObjectStream - if cl.stream != nil { - stream = cl.stream + if cs.stream != nil { + stream = cs.stream } else { stream = &PdfObjectStream{} } dict := MakeDict() - dict.Set("N", MakeInteger(int64(cl.N))) + dict.Set("N", MakeInteger(int64(cs.N))) - if cl.Alternate != nil { - dict.Set("Alternate", cl.Alternate.ToPdfObject()) + if cs.Alternate != nil { + dict.Set("Alternate", cs.Alternate.ToPdfObject()) } - if cl.Metadata != nil { - dict.Set("Metadata", cl.Metadata) + if cs.Metadata != nil { + dict.Set("Metadata", cs.Metadata) } - if cl.Range != nil { + if cs.Range != nil { var ranges []PdfObject - for _, r := range cl.Range { + for _, r := range cs.Range { ranges = append(ranges, MakeFloat(r)) } dict.Set("Range", MakeArray(ranges...)) } // Encode with a default encoder? - dict.Set("Length", MakeInteger(int64(len(cl.Data)))) + dict.Set("Length", MakeInteger(int64(len(cs.Data)))) // Need to have a representation of the stream... - stream.Stream = cl.Data + stream.Stream = cs.Data stream.PdfObjectDictionary = dict csObj.Append(stream) - if cl.container != nil { - cl.container.PdfObject = csObj - return cl.container + if cs.container != nil { + cs.container.PdfObject = csObj + return cs.container } return csObj } -func (cl *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, error) { - if cl.Alternate == nil { - if cl.N == 1 { +func (cs *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, error) { + if cs.Alternate == nil { + if cs.N == 1 { cs := NewPdfColorspaceDeviceGray() return cs.ColorFromFloats(vals) - } else if cl.N == 3 { + } else if cs.N == 3 { cs := NewPdfColorspaceDeviceRGB() return cs.ColorFromFloats(vals) - } else if cl.N == 4 { + } else if cs.N == 4 { cs := NewPdfColorspaceDeviceCMYK() return cs.ColorFromFloats(vals) } else { @@ -1864,18 +1864,18 @@ func (cl *PdfColorspaceICCBased) ColorFromFloats(vals []float64) (PdfColor, erro } } - return cl.Alternate.ColorFromFloats(vals) + return cs.Alternate.ColorFromFloats(vals) } -func (cl *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { - if cl.Alternate == nil { - if cl.N == 1 { +func (cs *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { + if cs.Alternate == nil { + if cs.N == 1 { cs := NewPdfColorspaceDeviceGray() return cs.ColorFromPdfObjects(objects) - } else if cl.N == 3 { + } else if cs.N == 3 { cs := NewPdfColorspaceDeviceRGB() return cs.ColorFromPdfObjects(objects) - } else if cl.N == 4 { + } else if cs.N == 4 { cs := NewPdfColorspaceDeviceCMYK() return cs.ColorFromPdfObjects(objects) } else { @@ -1883,10 +1883,10 @@ func (cl *PdfColorspaceICCBased) ColorFromPdfObjects(objects []PdfObject) (PdfCo } } - return cl.Alternate.ColorFromPdfObjects(objects) + return cs.Alternate.ColorFromPdfObjects(objects) } -func (cl *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { /* _, ok := color.(*PdfColorICCBased) if !ok { @@ -1895,17 +1895,17 @@ func (cl *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { } */ - if cl.Alternate == nil { + if cs.Alternate == nil { common.Log.Debug("ICC Based colorspace missing alternative") - if cl.N == 1 { + if cs.N == 1 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceGray (N=1)") grayCS := NewPdfColorspaceDeviceGray() return grayCS.ColorToRGB(color) - } else if cl.N == 3 { + } else if cs.N == 3 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceRGB (N=3)") // Already in RGB. return color, nil - } else if cl.N == 4 { + } else if cs.N == 4 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceCMYK (N=4)") // CMYK cmykCS := NewPdfColorspaceDeviceCMYK() @@ -1915,22 +1915,22 @@ func (cl *PdfColorspaceICCBased) ColorToRGB(color PdfColor) (PdfColor, error) { } } - common.Log.Trace("ICC Based colorspace with alternative: %#v", cl) - return cl.Alternate.ColorToRGB(color) + common.Log.Trace("ICC Based colorspace with alternative: %#v", cs) + return cs.Alternate.ColorToRGB(color) } -func (cl *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { - if cl.Alternate == nil { +func (cs *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { + if cs.Alternate == nil { common.Log.Debug("ICC Based colorspace missing alternative") - if cl.N == 1 { + if cs.N == 1 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceGray (N=1)") grayCS := NewPdfColorspaceDeviceGray() return grayCS.ImageToRGB(img) - } else if cl.N == 3 { + } else if cs.N == 3 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceRGB (N=3)") // Already in RGB. return img, nil - } else if cl.N == 4 { + } else if cs.N == 4 { common.Log.Debug("ICC Based colorspace missing alternative - using DeviceCMYK (N=4)") // CMYK cmykCS := NewPdfColorspaceDeviceCMYK() @@ -1939,12 +1939,12 @@ func (cl *PdfColorspaceICCBased) ImageToRGB(img Image) (Image, error) { return img, errors.New("ICC Based colorspace missing alternative") } } - common.Log.Trace("ICC Based colorspace with alternative: %#v", cl) + common.Log.Trace("ICC Based colorspace with alternative: %#v", cs) - output, err := cl.Alternate.ImageToRGB(img) + output, err := cs.Alternate.ImageToRGB(img) common.Log.Trace("ICC Input image: %+v", img) common.Log.Trace("ICC Output image: %+v", output) - return output, err //cl.Alternate.ImageToRGB(img) + return output, err //cs.Alternate.ImageToRGB(img) } ////////////////////// @@ -1967,16 +1967,16 @@ func NewPdfColorspaceSpecialPattern() *PdfColorspaceSpecialPattern { return &PdfColorspaceSpecialPattern{} } -func (cl *PdfColorspaceSpecialPattern) String() string { +func (cs *PdfColorspaceSpecialPattern) String() string { return "Pattern" } -func (cl *PdfColorspaceSpecialPattern) GetNumComponents() int { - return cl.UnderlyingCS.GetNumComponents() +func (cs *PdfColorspaceSpecialPattern) GetNumComponents() int { + return cs.UnderlyingCS.GetNumComponents() } // DecodeArray returns an empty slice as there are no components associated with pattern colorspace. -func (cl *PdfColorspaceSpecialPattern) DecodeArray() []float64 { +func (cs *PdfColorspaceSpecialPattern) DecodeArray() []float64 { return []float64{} } @@ -2030,33 +2030,33 @@ func newPdfColorspaceSpecialPatternFromPdfObject(obj PdfObject) (*PdfColorspaceS return cs, nil } -func (cl *PdfColorspaceSpecialPattern) ToPdfObject() PdfObject { - if cl.UnderlyingCS == nil { +func (cs *PdfColorspaceSpecialPattern) ToPdfObject() PdfObject { + if cs.UnderlyingCS == nil { return MakeName("Pattern") } csObj := MakeArray(MakeName("Pattern")) - csObj.Append(cl.UnderlyingCS.ToPdfObject()) + csObj.Append(cs.UnderlyingCS.ToPdfObject()) - if cl.container != nil { - cl.container.PdfObject = csObj - return cl.container + if cs.container != nil { + cs.container.PdfObject = csObj + return cs.container } return csObj } -func (cl *PdfColorspaceSpecialPattern) ColorFromFloats(vals []float64) (PdfColor, error) { - if cl.UnderlyingCS == nil { +func (cs *PdfColorspaceSpecialPattern) ColorFromFloats(vals []float64) (PdfColor, error) { + if cs.UnderlyingCS == nil { return nil, errors.New("Underlying CS not specified") } - return cl.UnderlyingCS.ColorFromFloats(vals) + return cs.UnderlyingCS.ColorFromFloats(vals) } // ColorFromPdfObjects loads the color from PDF objects. // The first objects (if present) represent the color in underlying colorspace. The last one represents // the name of the pattern. -func (cl *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) < 1 { return nil, errors.New("Invalid number of parameters") } @@ -2073,11 +2073,11 @@ func (cl *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) // Pattern color if specified. if len(objects) > 1 { colorObjs := objects[0 : len(objects)-1] - if cl.UnderlyingCS == nil { + if cs.UnderlyingCS == nil { common.Log.Debug("Pattern color with defined color components but underlying cs missing") return nil, errors.New("Underlying CS not defined") } - color, err := cl.UnderlyingCS.ColorFromPdfObjects(colorObjs) + color, err := cs.UnderlyingCS.ColorFromPdfObjects(colorObjs) if err != nil { common.Log.Debug("ERROR: Unable to convert color via underlying cs: %v", err) return nil, err @@ -2091,7 +2091,7 @@ func (cl *PdfColorspaceSpecialPattern) ColorFromPdfObjects(objects []PdfObject) // ColorToRGB only converts color used with uncolored patterns (defined in underlying colorspace). Does not go into the // pattern objects and convert those. If that is desired, needs to be done separately. See for example // grayscale conversion example in unidoc-examples repo. -func (cl *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, error) { +func (cs *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, error) { patternColor, ok := color.(*PdfColorPattern) if !ok { common.Log.Debug("Color not pattern (got %T)", color) @@ -2103,15 +2103,15 @@ func (cl *PdfColorspaceSpecialPattern) ColorToRGB(color PdfColor) (PdfColor, err return color, nil } - if cl.UnderlyingCS == nil { + if cs.UnderlyingCS == nil { return nil, errors.New("Underlying CS not defined.") } - return cl.UnderlyingCS.ColorToRGB(patternColor.Color) + return cs.UnderlyingCS.ColorToRGB(patternColor.Color) } // ImageToRGB returns an error since an image cannot be defined in a pattern colorspace. -func (cl *PdfColorspaceSpecialPattern) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceSpecialPattern) ImageToRGB(img Image) (Image, error) { common.Log.Debug("Error: Image cannot be specified in Pattern colorspace") return img, errors.New("Invalid colorspace for image (pattern)") } @@ -2135,17 +2135,17 @@ func NewPdfColorspaceSpecialIndexed() *PdfColorspaceSpecialIndexed { return cs } -func (cl *PdfColorspaceSpecialIndexed) String() string { +func (cs *PdfColorspaceSpecialIndexed) String() string { return "Indexed" } -func (cl *PdfColorspaceSpecialIndexed) GetNumComponents() int { +func (cs *PdfColorspaceSpecialIndexed) GetNumComponents() int { return 1 } // DecodeArray returns the component range values for the Indexed colorspace. -func (cl *PdfColorspaceSpecialIndexed) DecodeArray() []float64 { - return []float64{0, float64(cl.HiVal)} +func (cs *PdfColorspaceSpecialIndexed) DecodeArray() []float64 { + return []float64{0, float64(cs.HiVal)} } func newPdfColorspaceSpecialIndexedFromPdfObject(obj PdfObject) (*PdfColorspaceSpecialIndexed, error) { @@ -2238,24 +2238,24 @@ func newPdfColorspaceSpecialIndexedFromPdfObject(obj PdfObject) (*PdfColorspaceS return cs, nil } -func (cl *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } - N := cl.Base.GetNumComponents() + N := cs.Base.GetNumComponents() index := int(vals[0]) * N - if index < 0 || (index+N-1) >= len(cl.colorLookup) { + if index < 0 || (index+N-1) >= len(cs.colorLookup) { return nil, errors.New("Outside range") } - cvals := cl.colorLookup[index : index+N] + cvals := cs.colorLookup[index : index+N] var floats []float64 for _, val := range cvals { floats = append(floats, float64(val)/255.0) } - color, err := cl.Base.ColorFromFloats(floats) + color, err := cs.Base.ColorFromFloats(floats) if err != nil { return nil, err } @@ -2263,7 +2263,7 @@ func (cl *PdfColorspaceSpecialIndexed) ColorFromFloats(vals []float64) (PdfColor return color, nil } -func (cl *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -2273,19 +2273,19 @@ func (cl *PdfColorspaceSpecialIndexed) ColorFromPdfObjects(objects []PdfObject) return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceSpecialIndexed) ColorToRGB(color PdfColor) (PdfColor, error) { - if cl.Base == nil { +func (cs *PdfColorspaceSpecialIndexed) ColorToRGB(color PdfColor) (PdfColor, error) { + if cs.Base == nil { return nil, errors.New("Indexed base colorspace undefined") } - return cl.Base.ColorToRGB(color) + return cs.Base.ColorToRGB(color) } // ImageToRGB convert an indexed image to RGB. -func (cl *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { //baseImage := img // Make a new representation of the image to be converted with the base colorspace. baseImage := Image{} @@ -2297,7 +2297,7 @@ func (cl *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { baseImage.ColorComponents = img.ColorComponents samples := img.GetSamples() - N := cl.Base.GetNumComponents() + N := cs.Base.GetNumComponents() var baseSamples []uint32 // Convert the indexed data to base color map data. @@ -2307,13 +2307,13 @@ func (cl *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { index := int(samples[i]) * N common.Log.Trace("Indexed Index: %d", index) // Ensure does not go out of bounds. - if index+N-1 >= len(cl.colorLookup) { + if index+N-1 >= len(cs.colorLookup) { // Clip to the end value. - index = len(cl.colorLookup) - N - 1 + index = len(cs.colorLookup) - N - 1 common.Log.Trace("Clipping to index: %d", index) } - cvals := cl.colorLookup[index : index+N] + cvals := cs.colorLookup[index : index+N] common.Log.Trace("C Vals: % d", cvals) for _, val := range cvals { baseSamples = append(baseSamples, uint32(val)) @@ -2326,19 +2326,19 @@ func (cl *PdfColorspaceSpecialIndexed) ImageToRGB(img Image) (Image, error) { common.Log.Trace("-> Output samples: %d", baseSamples) // Convert to rgb. - return cl.Base.ImageToRGB(baseImage) + return cs.Base.ImageToRGB(baseImage) } // ToPdfObject converts colorspace to a PDF object. [/Indexed base hival lookup] -func (cl *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { +func (cs *PdfColorspaceSpecialIndexed) ToPdfObject() PdfObject { csObj := MakeArray(MakeName("Indexed")) - csObj.Append(cl.Base.ToPdfObject()) - csObj.Append(MakeInteger(int64(cl.HiVal))) - csObj.Append(cl.Lookup) + csObj.Append(cs.Base.ToPdfObject()) + csObj.Append(MakeInteger(int64(cs.HiVal))) + csObj.Append(cs.Lookup) - if cl.container != nil { - cl.container.PdfObject = csObj - return cl.container + if cs.container != nil { + cs.container.PdfObject = csObj + return cs.container } return csObj @@ -2365,16 +2365,16 @@ func NewPdfColorspaceSpecialSeparation() *PdfColorspaceSpecialSeparation { return cs } -func (cl *PdfColorspaceSpecialSeparation) String() string { +func (cs *PdfColorspaceSpecialSeparation) String() string { return "Separation" } -func (cl *PdfColorspaceSpecialSeparation) GetNumComponents() int { +func (cs *PdfColorspaceSpecialSeparation) GetNumComponents() int { return 1 } // DecodeArray returns the component range values for the Separation colorspace. -func (cl *PdfColorspaceSpecialSeparation) DecodeArray() []float64 { +func (cs *PdfColorspaceSpecialSeparation) DecodeArray() []float64 { return []float64{0, 1.0} } @@ -2436,39 +2436,39 @@ func newPdfColorspaceSpecialSeparationFromPdfObject(obj PdfObject) (*PdfColorspa return cs, nil } -func (cl *PdfColorspaceSpecialSeparation) ToPdfObject() PdfObject { +func (cs *PdfColorspaceSpecialSeparation) ToPdfObject() PdfObject { csArray := MakeArray(MakeName("Separation")) - csArray.Append(cl.ColorantName) - csArray.Append(cl.AlternateSpace.ToPdfObject()) - csArray.Append(cl.TintTransform.ToPdfObject()) + csArray.Append(cs.ColorantName) + csArray.Append(cs.AlternateSpace.ToPdfObject()) + csArray.Append(cs.TintTransform.ToPdfObject()) // If in a container, replace the contents and return back. // Helps not getting too many duplicates of the same objects. - if cl.container != nil { - cl.container.PdfObject = csArray - return cl.container + if cs.container != nil { + cs.container.PdfObject = csArray + return cs.container } return csArray } -func (cl *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (PdfColor, error) { +func (cs *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (PdfColor, error) { if len(vals) != 1 { return nil, errors.New("Range check") } tint := vals[0] input := []float64{tint} - output, err := cl.TintTransform.Evaluate(input) + output, err := cs.TintTransform.Evaluate(input) if err != nil { common.Log.Debug("Error, failed to evaluate: %v", err) - common.Log.Trace("Tint transform: %+v", cl.TintTransform) + common.Log.Trace("Tint transform: %+v", cs.TintTransform) return nil, err } - common.Log.Trace("Processing ColorFromFloats(%+v) on AlternateSpace: %#v", output, cl.AlternateSpace) - color, err := cl.AlternateSpace.ColorFromFloats(output) + common.Log.Trace("Processing ColorFromFloats(%+v) on AlternateSpace: %#v", output, cs.AlternateSpace) + color, err := cs.AlternateSpace.ColorFromFloats(output) if err != nil { common.Log.Debug("Error, failed to evaluate in alternate space: %v", err) return nil, err @@ -2477,7 +2477,7 @@ func (cl *PdfColorspaceSpecialSeparation) ColorFromFloats(vals []float64) (PdfCo return color, nil } -func (cl *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { +func (cs *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { if len(objects) != 1 { return nil, errors.New("Range check") } @@ -2487,21 +2487,21 @@ func (cl *PdfColorspaceSpecialSeparation) ColorFromPdfObjects(objects []PdfObjec return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } // ColorToRGB converts a color in Separation colorspace to RGB colorspace. -func (cl *PdfColorspaceSpecialSeparation) ColorToRGB(color PdfColor) (PdfColor, error) { - if cl.AlternateSpace == nil { +func (cs *PdfColorspaceSpecialSeparation) ColorToRGB(color PdfColor) (PdfColor, error) { + if cs.AlternateSpace == nil { return nil, errors.New("Alternate colorspace undefined") } - return cl.AlternateSpace.ColorToRGB(color) + return cs.AlternateSpace.ColorToRGB(color) } // ImageToRGB converts an image with samples in Separation CS to an image with samples specified in // DeviceRGB CS. -func (cl *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { altImage := img samples := img.GetSamples() @@ -2509,9 +2509,9 @@ func (cl *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { common.Log.Trace("Separation color space -> ToRGB conversion") common.Log.Trace("samples in: %d", len(samples)) - common.Log.Trace("TintTransform: %+v", cl.TintTransform) + common.Log.Trace("TintTransform: %+v", cs.TintTransform) - altDecode := cl.AlternateSpace.DecodeArray() + altDecode := cs.AlternateSpace.DecodeArray() var altSamples []uint32 // Convert tints to color data in the alternate colorspace. @@ -2520,8 +2520,8 @@ func (cl *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { tint := float64(samples[i]) / maxVal // Convert the tint value to the alternate space value. - outputs, err := cl.TintTransform.Evaluate([]float64{tint}) - //common.Log.Trace("%v Converting tint value: %f -> [% f]", cl.AlternateSpace, tint, outputs) + outputs, err := cs.TintTransform.Evaluate([]float64{tint}) + //common.Log.Trace("%v Converting tint value: %f -> [% f]", cs.AlternateSpace, tint, outputs) if err != nil { return img, err @@ -2539,13 +2539,13 @@ func (cl *PdfColorspaceSpecialSeparation) ImageToRGB(img Image) (Image, error) { } common.Log.Trace("Samples out: %d", len(altSamples)) altImage.SetSamples(altSamples) - altImage.ColorComponents = cl.AlternateSpace.GetNumComponents() + altImage.ColorComponents = cs.AlternateSpace.GetNumComponents() // Set the image's decode parameters for interpretation in the alternative CS. altImage.decode = altDecode // Convert to RGB via the alternate colorspace. - return cl.AlternateSpace.ImageToRGB(altImage) + return cs.AlternateSpace.ImageToRGB(altImage) } // PdfColorspaceDeviceN represents a DeviceN color space. DeviceN color spaces are similar to Separation color @@ -2570,20 +2570,20 @@ func NewPdfColorspaceDeviceN() *PdfColorspaceDeviceN { } // String returns the name of the colorspace (DeviceN). -func (cl *PdfColorspaceDeviceN) String() string { +func (cs *PdfColorspaceDeviceN) String() string { return "DeviceN" } // GetNumComponents returns the number of input color components, i.e. that are input to the tint transform. -func (cl *PdfColorspaceDeviceN) GetNumComponents() int { - return cl.ColorantNames.Len() +func (cs *PdfColorspaceDeviceN) GetNumComponents() int { + return cs.ColorantNames.Len() } // DecodeArray returns the component range values for the DeviceN colorspace. // [0 1.0 0 1.0 ...] for each color component. -func (cl *PdfColorspaceDeviceN) DecodeArray() []float64 { +func (cs *PdfColorspaceDeviceN) DecodeArray() []float64 { var decode []float64 - for i := 0; i < cl.GetNumComponents(); i++ { + for i := 0; i < cs.GetNumComponents(); i++ { decode = append(decode, 0.0, 1.0) } return decode @@ -2661,35 +2661,35 @@ func newPdfColorspaceDeviceNFromPdfObject(obj PdfObject) (*PdfColorspaceDeviceN, // ToPdfObject returns a *PdfIndirectObject containing a *PdfObjectArray representation of the DeviceN colorspace. // Format: [/DeviceN names alternateSpace tintTransform] // or: [/DeviceN names alternateSpace tintTransform attributes] -func (cl *PdfColorspaceDeviceN) ToPdfObject() PdfObject { +func (cs *PdfColorspaceDeviceN) ToPdfObject() PdfObject { csArray := MakeArray(MakeName("DeviceN")) - csArray.Append(cl.ColorantNames) - csArray.Append(cl.AlternateSpace.ToPdfObject()) - csArray.Append(cl.TintTransform.ToPdfObject()) - if cl.Attributes != nil { - csArray.Append(cl.Attributes.ToPdfObject()) + csArray.Append(cs.ColorantNames) + csArray.Append(cs.AlternateSpace.ToPdfObject()) + csArray.Append(cs.TintTransform.ToPdfObject()) + if cs.Attributes != nil { + csArray.Append(cs.Attributes.ToPdfObject()) } - if cl.container != nil { - cl.container.PdfObject = csArray - return cl.container + if cs.container != nil { + cs.container.PdfObject = csArray + return cs.container } return csArray } // ColorFromFloats returns a new PdfColor based on input color components. -func (cl *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, error) { - if len(vals) != cl.GetNumComponents() { +func (cs *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, error) { + if len(vals) != cs.GetNumComponents() { return nil, errors.New("Range check") } - output, err := cl.TintTransform.Evaluate(vals) + output, err := cs.TintTransform.Evaluate(vals) if err != nil { return nil, err } - color, err := cl.AlternateSpace.ColorFromFloats(output) + color, err := cs.AlternateSpace.ColorFromFloats(output) if err != nil { return nil, err } @@ -2698,8 +2698,8 @@ func (cl *PdfColorspaceDeviceN) ColorFromFloats(vals []float64) (PdfColor, error // ColorFromPdfObjects returns a new PdfColor based on input color components. The input PdfObjects should // be numeric. -func (cl *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { - if len(objects) != cl.GetNumComponents() { +func (cs *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfColor, error) { + if len(objects) != cs.GetNumComponents() { return nil, errors.New("Range check") } @@ -2708,17 +2708,17 @@ func (cl *PdfColorspaceDeviceN) ColorFromPdfObjects(objects []PdfObject) (PdfCol return nil, err } - return cl.ColorFromFloats(floats) + return cs.ColorFromFloats(floats) } -func (cl *PdfColorspaceDeviceN) ColorToRGB(color PdfColor) (PdfColor, error) { - if cl.AlternateSpace == nil { +func (cs *PdfColorspaceDeviceN) ColorToRGB(color PdfColor) (PdfColor, error) { + if cs.AlternateSpace == nil { return nil, errors.New("DeviceN alternate space undefined") } - return cl.AlternateSpace.ColorToRGB(color) + return cs.AlternateSpace.ColorToRGB(color) } -func (cl *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { +func (cs *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { altImage := img samples := img.GetSamples() @@ -2726,20 +2726,20 @@ func (cl *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { // Convert tints to color data in the alternate colorspace. var altSamples []uint32 - for i := 0; i < len(samples); i += cl.GetNumComponents() { + for i := 0; i < len(samples); i += cs.GetNumComponents() { // The input to the tint transformation is the tint // for each color component. // // A single tint component is in the range 0.0 - 1.0 var inputs []float64 - for j := 0; j < cl.GetNumComponents(); j++ { + for j := 0; j < cs.GetNumComponents(); j++ { tint := float64(samples[i+j]) / maxVal inputs = append(inputs, tint) } // Transform the tints to the alternate colorspace. // (scaled units). - outputs, err := cl.TintTransform.Evaluate(inputs) + outputs, err := cs.TintTransform.Evaluate(inputs) if err != nil { return img, err } @@ -2755,7 +2755,7 @@ func (cl *PdfColorspaceDeviceN) ImageToRGB(img Image) (Image, error) { altImage.SetSamples(altSamples) // Convert to RGB via the alternate colorspace. - return cl.AlternateSpace.ImageToRGB(altImage) + return cs.AlternateSpace.ImageToRGB(altImage) } // PdfColorspaceDeviceNAttributes contains additional information about the components of colour space that @@ -2820,19 +2820,19 @@ func newPdfColorspaceDeviceNAttributesFromPdfObject(obj PdfObject) (*PdfColorspa // ToPdfObject returns a PdfObject representation of PdfColorspaceDeviceNAttributes as a PdfObjectDictionary directly // or indirectly within an indirect object container. -func (cl *PdfColorspaceDeviceNAttributes) ToPdfObject() PdfObject { +func (cs *PdfColorspaceDeviceNAttributes) ToPdfObject() PdfObject { dict := MakeDict() - if cl.Subtype != nil { - dict.Set("Subtype", cl.Subtype) + if cs.Subtype != nil { + dict.Set("Subtype", cs.Subtype) } - dict.SetIfNotNil("Colorants", cl.Colorants) - dict.SetIfNotNil("Process", cl.Process) - dict.SetIfNotNil("MixingHints", cl.MixingHints) + dict.SetIfNotNil("Colorants", cs.Colorants) + dict.SetIfNotNil("Process", cs.Process) + dict.SetIfNotNil("MixingHints", cs.MixingHints) - if cl.container != nil { - cl.container.PdfObject = dict - return cl.container + if cs.container != nil { + cs.container.PdfObject = dict + return cs.container } return dict diff --git a/pdf/model/colorspace_test.go b/pdf/model/colorspace_test.go index 823bd48a..8e5537d5 100644 --- a/pdf/model/colorspace_test.go +++ b/pdf/model/colorspace_test.go @@ -133,7 +133,7 @@ endstream endobj if !ok { t.Fatalf("error") } - fmt.Printf("%s\n", outDict.DefaultWriteString()) + fmt.Printf("%s\n", outDict.WriteString()) r99, ok := resources.GetColorspaceByName("R99") if !ok { t.Fatalf("error") diff --git a/pdf/model/optimize/combine_duplicate_direct_objects.go b/pdf/model/optimize/combine_duplicate_direct_objects.go index 5486b5c5..da1e084c 100644 --- a/pdf/model/optimize/combine_duplicate_direct_objects.go +++ b/pdf/model/optimize/combine_duplicate_direct_objects.go @@ -27,7 +27,7 @@ func (dup *CombineDuplicateDirectObjects) Optimize(objects []core.PdfObject) (op obj := pDict.Get(key) if dict, isDictObj := obj.(*core.PdfObjectDictionary); isDictObj { hasher := md5.New() - hasher.Write([]byte(dict.DefaultWriteString())) + hasher.Write([]byte(dict.WriteString())) hash := string(hasher.Sum(nil)) dictsByHash[hash] = append(dictsByHash[hash], dict) processDict(dict) diff --git a/pdf/model/optimize/combine_identical_indirect_objects.go b/pdf/model/optimize/combine_identical_indirect_objects.go index 7c4f492e..1d59a743 100644 --- a/pdf/model/optimize/combine_identical_indirect_objects.go +++ b/pdf/model/optimize/combine_identical_indirect_objects.go @@ -34,7 +34,7 @@ func (c *CombineIdenticalIndirectObjects) Optimize(objects []core.PdfObject) (op continue } hasher := md5.New() - hasher.Write([]byte(dict.DefaultWriteString())) + hasher.Write([]byte(dict.WriteString())) hash := string(hasher.Sum(nil)) indWithDictByHash[hash] = append(indWithDictByHash[hash], ind) diff --git a/pdf/model/optimize/compress_streams.go b/pdf/model/optimize/compress_streams.go index ea2be38f..041cbae9 100644 --- a/pdf/model/optimize/compress_streams.go +++ b/pdf/model/optimize/compress_streams.go @@ -34,7 +34,7 @@ func (c *CompressStreams) Optimize(objects []core.PdfObject) (optimizedObjects [ } dict := encoder.MakeStreamDict() // compare compressed and uncompressed sizes - if len(data)+len(dict.DefaultWriteString()) < len(stream.Stream) { + if len(data)+len(dict.WriteString()) < len(stream.Stream) { stream.Stream = data stream.PdfObjectDictionary.Merge(dict) stream.PdfObjectDictionary.Set("Length", core.MakeInteger(int64(len(stream.Stream)))) diff --git a/pdf/model/outlines.go b/pdf/model/outlines.go index 4cd69779..f71a6fa5 100644 --- a/pdf/model/outlines.go +++ b/pdf/model/outlines.go @@ -256,18 +256,18 @@ func (o *PdfOutline) ToPdfObject() PdfObject { return container } -func (o *PdfOutlineItem) GetContainingPdfObject() PdfObject { - return o.primitive +func (oi *PdfOutlineItem) GetContainingPdfObject() PdfObject { + return oi.primitive } // ToPdfObject recursively builds the Outline tree PDF object. -func (o *PdfOutlineItem) ToPdfObject() PdfObject { - container := o.primitive +func (oi *PdfOutlineItem) ToPdfObject() PdfObject { + container := oi.primitive dict := container.PdfObject.(*PdfObjectDictionary) - dict.Set("Title", o.Title) - if o.A != nil { - dict.Set("A", o.A) + dict.Set("Title", oi.Title) + if oi.A != nil { + dict.Set("A", oi.A) } if obj := dict.Get("SE"); obj != nil { // TODO: Currently not supporting structure element hierarchy. @@ -276,39 +276,39 @@ func (o *PdfOutlineItem) ToPdfObject() PdfObject { // delete(*dict, "SE") } /* - if o.SE != nil { - (*dict)["SE"] = o.SE + if oi.SE != nil { + (*dict)["SE"] = oi.SE } */ - if o.C != nil { - dict.Set("C", o.C) + if oi.C != nil { + dict.Set("C", oi.C) } - if o.Dest != nil { - dict.Set("Dest", o.Dest) + if oi.Dest != nil { + dict.Set("Dest", oi.Dest) } - if o.F != nil { - dict.Set("F", o.F) + if oi.F != nil { + dict.Set("F", oi.F) } - if o.Count != nil { - dict.Set("Count", MakeInteger(*o.Count)) + if oi.Count != nil { + dict.Set("Count", MakeInteger(*oi.Count)) } - if o.Next != nil { - dict.Set("Next", o.Next.ToPdfObject()) + if oi.Next != nil { + dict.Set("Next", oi.Next.ToPdfObject()) } - if o.First != nil { - dict.Set("First", o.First.ToPdfObject()) + if oi.First != nil { + dict.Set("First", oi.First.ToPdfObject()) } - if o.Prev != nil { - dict.Set("Prev", o.Prev.getOuter().GetContainingPdfObject()) - //PdfObjectConverterCache[o.Prev.getOuter()] + if oi.Prev != nil { + dict.Set("Prev", oi.Prev.getOuter().GetContainingPdfObject()) + //PdfObjectConverterCache[oi.Prev.getOuter()] } - if o.Last != nil { - dict.Set("Last", o.Last.getOuter().GetContainingPdfObject()) - // PdfObjectConverterCache[o.Last.getOuter()] + if oi.Last != nil { + dict.Set("Last", oi.Last.getOuter().GetContainingPdfObject()) + // PdfObjectConverterCache[oi.Last.getOuter()] } - if o.Parent != nil { - dict.Set("Parent", o.Parent.getOuter().GetContainingPdfObject()) - //PdfObjectConverterCache[o.Parent.getOuter()] + if oi.Parent != nil { + dict.Set("Parent", oi.Parent.getOuter().GetContainingPdfObject()) + //PdfObjectConverterCache[oi.Parent.getOuter()] } return container diff --git a/pdf/model/page.go b/pdf/model/page.go index 8878811a..72c90f74 100644 --- a/pdf/model/page.go +++ b/pdf/model/page.go @@ -441,7 +441,7 @@ func (p *PdfPage) getResources() (*PdfPageResources, error) { return nil, nil } -// GetPageDict convert the Page to a PDF object dictionary. +// GetPageDict converts the Page to a PDF object dictionary. func (p *PdfPage) GetPageDict() *PdfObjectDictionary { d := p.pageDict d.Clear() @@ -561,7 +561,7 @@ func (p *PdfPage) HasXObjectByName(name PdfObjectName) bool { } } -// GetXObjectByName get XObject by name. +// GetXObjectByName gets XObject by name. func (p *PdfPage) GetXObjectByName(name PdfObjectName) (PdfObject, bool) { xresDict, has := p.Resources.XObject.(*PdfObjectDictionary) if !has { @@ -661,7 +661,7 @@ type WatermarkImageOptions struct { PreserveAspectRatio bool } -// AddWatermarkImage add a watermark to the page. +// AddWatermarkImage adds a watermark to the page. func (p *PdfPage) AddWatermarkImage(ximg *XObjectImage, opt WatermarkImageOptions) error { // Page dimensions. bbox, err := p.GetMediaBox() @@ -892,11 +892,11 @@ func NewPdfPageResourcesColorspaces() *PdfPageResourcesColorspaces { } // Set sets the colorspace corresponding to key. Add to Names if not set. -func (r *PdfPageResourcesColorspaces) Set(key PdfObjectName, val PdfColorspace) { - if _, has := r.Colorspaces[string(key)]; !has { - r.Names = append(r.Names, string(key)) +func (rcs *PdfPageResourcesColorspaces) Set(key PdfObjectName, val PdfColorspace) { + if _, has := rcs.Colorspaces[string(key)]; !has { + rcs.Names = append(rcs.Names, string(key)) } - r.Colorspaces[string(key)] = val + rcs.Colorspaces[string(key)] = val } func newPdfPageResourcesColorspacesFromPdfObject(obj PdfObject) (*PdfPageResourcesColorspaces, error) { @@ -928,15 +928,15 @@ func newPdfPageResourcesColorspacesFromPdfObject(obj PdfObject) (*PdfPageResourc return colorspaces, nil } -func (r *PdfPageResourcesColorspaces) ToPdfObject() PdfObject { +func (rcs *PdfPageResourcesColorspaces) ToPdfObject() PdfObject { dict := MakeDict() - for _, csName := range r.Names { - dict.Set(PdfObjectName(csName), r.Colorspaces[csName].ToPdfObject()) + for _, csName := range rcs.Names { + dict.Set(PdfObjectName(csName), rcs.Colorspaces[csName].ToPdfObject()) } - if r.container != nil { - r.container.PdfObject = dict - return r.container + if rcs.container != nil { + rcs.container.PdfObject = dict + return rcs.container } return dict diff --git a/pdf/model/shading.go b/pdf/model/shading.go index 5bbe9f90..d481a347 100644 --- a/pdf/model/shading.go +++ b/pdf/model/shading.go @@ -75,7 +75,7 @@ type PdfShadingType1 struct { Function []PdfFunction } -// PdfShadingType2 is a Axial shading. +// PdfShadingType2 is an Axial shading. type PdfShadingType2 struct { *PdfShading Coords *PdfObjectArray diff --git a/pdf/model/structures.go b/pdf/model/structures.go index 4fdbffe7..c0fd8b2c 100644 --- a/pdf/model/structures.go +++ b/pdf/model/structures.go @@ -58,7 +58,7 @@ func NewPdfRectangle(arr PdfObjectArray) (*PdfRectangle, error) { return &rect, nil } -// ToPdfObject convert rectangle to a PDF object. +// ToPdfObject converts rectangle to a PDF object. func (rect *PdfRectangle) ToPdfObject() PdfObject { arr := MakeArray(MakeFloat(rect.Llx), MakeFloat(rect.Lly), MakeFloat(rect.Urx), MakeFloat(rect.Ury)) return arr diff --git a/pdf/model/writer.go b/pdf/model/writer.go index f5a059b8..0ebdd175 100644 --- a/pdf/model/writer.go +++ b/pdf/model/writer.go @@ -568,7 +568,7 @@ func (w *PdfWriter) writeObject(num int, obj PdfObject) { if pobj, isIndirect := obj.(*PdfIndirectObject); isIndirect { w.crossReferenceMap[num] = crossReference{Type: 1, Offset: w.writePos, Generation: pobj.GenerationNumber} outStr := fmt.Sprintf("%d 0 obj\n", num) - outStr += pobj.PdfObject.DefaultWriteString() + outStr += pobj.PdfObject.WriteString() outStr += "\nendobj\n" w.writeString(outStr) return @@ -579,7 +579,7 @@ func (w *PdfWriter) writeObject(num int, obj PdfObject) { if pobj, isStream := obj.(*PdfObjectStream); isStream { w.crossReferenceMap[num] = crossReference{Type: 1, Offset: w.writePos, Generation: pobj.GenerationNumber} outStr := fmt.Sprintf("%d 0 obj\n", num) - outStr += pobj.PdfObjectDictionary.DefaultWriteString() + outStr += pobj.PdfObjectDictionary.WriteString() outStr += "\nstream\n" w.writeString(outStr) w.writeBytes(pobj.Stream) @@ -599,7 +599,7 @@ func (w *PdfWriter) writeObject(num int, obj PdfObject) { if !isIndirect { common.Log.Error("Object streams N %d contains non indirect pdf object %v", num, obj) } - data := io.PdfObject.DefaultWriteString() + " " + data := io.PdfObject.WriteString() + " " objData = objData + data offsets = append(offsets, fmt.Sprintf("%d %d", io.ObjectNumber, offset)) w.crossReferenceMap[int(io.ObjectNumber)] = crossReference{Type: 2, ObjectNumber: num, Index: index} @@ -619,7 +619,7 @@ func (w *PdfWriter) writeObject(num int, obj PdfObject) { length := int64(len(data)) dict.Set(PdfObjectName("Length"), MakeInteger(length)) - outStr += dict.DefaultWriteString() + outStr += dict.WriteString() outStr += "\nstream\n" w.writeString(outStr) w.writeBytes(data) @@ -627,7 +627,7 @@ func (w *PdfWriter) writeObject(num int, obj PdfObject) { return } - w.writer.WriteString(obj.DefaultWriteString()) + w.writer.WriteString(obj.WriteString()) } // Update all the object numbers prior to writing. @@ -912,7 +912,7 @@ func (w *PdfWriter) Write(writer io.Writer) error { common.Log.Trace("Ids: %s", w.ids) } w.writeString("trailer\n") - w.writeString(trailer.DefaultWriteString()) + w.writeString(trailer.WriteString()) w.writeString("\n") } diff --git a/pdf/model/xobject.go b/pdf/model/xobject.go index 8e96d820..dff2f92f 100644 --- a/pdf/model/xobject.go +++ b/pdf/model/xobject.go @@ -152,7 +152,7 @@ func (xform *XObjectForm) SetContentStream(content []byte, encoder StreamEncoder return nil } -// ToPdfObject return a stream object. +// ToPdfObject returns a stream object. func (xform *XObjectForm) ToPdfObject() PdfObject { stream := xform.primitive @@ -367,7 +367,7 @@ func toGray(matte *PdfObjectArray) (float64, error) { return 0.0, err } -// NewXObjectImageFromStream build the image xobject from a stream object. +// NewXObjectImageFromStream builds the image xobject from a stream object. // An image dictionary is the dictionary portion of a stream object representing an image XObject. func NewXObjectImageFromStream(stream *PdfObjectStream) (*XObjectImage, error) { img := &XObjectImage{} @@ -445,7 +445,7 @@ func NewXObjectImageFromStream(stream *PdfObjectStream) (*XObjectImage, error) { return img, nil } -// SetImage update XObject Image with new image data. +// SetImage updates XObject Image with new image data. func (ximg *XObjectImage) SetImage(img *Image, cs PdfColorspace) error { encoded, err := ximg.Filter.EncodeBytes(img.Data) if err != nil { @@ -543,7 +543,7 @@ func (ximg *XObjectImage) GetContainingPdfObject() PdfObject { return ximg.primitive } -// ToPdfObject return a stream object. +// ToPdfObject returns a stream object. func (ximg *XObjectImage) ToPdfObject() PdfObject { stream := ximg.primitive