github.com/pdfcpu/pdfcpu@v0.11.1/pkg/pdfcpu/property.go (about) 1 /* 2 Copyright 2020 The pdfcpu Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package pdfcpu 18 19 import ( 20 "fmt" 21 "sort" 22 23 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" 24 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types" 25 ) 26 27 // PropertiesList returns a list of document properties as recorded in the document info dict. 28 func PropertiesList(ctx *model.Context) ([]string, error) { 29 list := make([]string, 0, len(ctx.Properties)) 30 keys := make([]string, len(ctx.Properties)) 31 i := 0 32 for k := range ctx.Properties { 33 keys[i] = k 34 i++ 35 } 36 sort.Strings(keys) 37 for _, k := range keys { 38 v := ctx.Properties[k] 39 list = append(list, fmt.Sprintf("%s = %s", k, v)) 40 } 41 return list, nil 42 } 43 44 // PropertiesAdd adds properties into the document info dict. 45 // Returns true if at least one property was added. 46 func PropertiesAdd(ctx *model.Context, properties map[string]string) error { 47 if err := ensureInfoDictAndFileID(ctx); err != nil { 48 return err 49 } 50 51 d, _ := ctx.DereferenceDict(*ctx.Info) 52 53 for k, v := range properties { 54 s, err := types.EscapedUTF16String(v) 55 if err != nil { 56 return err 57 } 58 d[k] = types.StringLiteral(*s) 59 ctx.Properties[k] = *s 60 } 61 62 return nil 63 } 64 65 // PropertiesRemove deletes specified properties. 66 // Returns true if at least one property was removed. 67 func PropertiesRemove(ctx *model.Context, properties []string) (bool, error) { 68 if ctx.Info == nil { 69 return false, nil 70 } 71 72 d, err := ctx.DereferenceDict(*ctx.Info) 73 if err != nil || d == nil { 74 return false, err 75 } 76 77 if len(properties) == 0 { 78 // Remove all properties. 79 for k := range ctx.Properties { 80 delete(d, types.EncodeName(k)) 81 } 82 ctx.Properties = map[string]string{} 83 return true, nil 84 } 85 86 var removed bool 87 for _, k := range properties { 88 _, ok := d[k] 89 if ok && !removed { 90 delete(d, k) 91 delete(ctx.Properties, k) 92 removed = true 93 } 94 } 95 96 return removed, nil 97 }