github.com/pdfcpu/pdfcpu@v0.11.1/pkg/api/collect.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 api 18 19 import ( 20 "io" 21 "os" 22 23 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu" 24 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" 25 "github.com/pkg/errors" 26 ) 27 28 // Collect creates a custom PDF page sequence for selected pages of rs and writes the result to w. 29 func Collect(rs io.ReadSeeker, w io.Writer, selectedPages []string, conf *model.Configuration) error { 30 if rs == nil { 31 return errors.New("pdfcpu: Collect: missing rs") 32 } 33 34 if conf == nil { 35 conf = model.NewDefaultConfiguration() 36 } 37 conf.Cmd = model.COLLECT 38 39 ctx, err := ReadValidateAndOptimize(rs, conf) 40 if err != nil { 41 return err 42 } 43 44 pages, err := PagesForPageCollection(ctx.PageCount, selectedPages) 45 if err != nil { 46 return err 47 } 48 49 ctxDest, err := pdfcpu.ExtractPages(ctx, pages, false) 50 if err != nil { 51 return err 52 } 53 54 return Write(ctxDest, w, conf) 55 } 56 57 // CollectFile creates a custom PDF page sequence for inFile and writes the result to outFile. 58 func CollectFile(inFile, outFile string, selectedPages []string, conf *model.Configuration) (err error) { 59 tmpFile := inFile + ".tmp" 60 if outFile != "" && inFile != outFile { 61 tmpFile = outFile 62 logWritingTo(outFile) 63 } else { 64 logWritingTo(inFile) 65 } 66 67 var f1, f2 *os.File 68 69 if f1, err = os.Open(inFile); err != nil { 70 return err 71 } 72 73 if f2, err = os.Create(tmpFile); err != nil { 74 f1.Close() 75 return err 76 } 77 78 defer func() { 79 if err != nil { 80 f2.Close() 81 f1.Close() 82 os.Remove(tmpFile) 83 return 84 } 85 if err = f2.Close(); err != nil { 86 return 87 } 88 if err = f1.Close(); err != nil { 89 return 90 } 91 if outFile == "" || inFile == outFile { 92 err = os.Rename(tmpFile, inFile) 93 } 94 }() 95 96 return Collect(f1, f2, selectedPages, conf) 97 }