github.com/pdfcpu/pdfcpu@v0.11.1/pkg/api/rotate.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 // Rotate rotates selected pages of rs clockwise by rotation degrees and writes the result to w. 29 func Rotate(rs io.ReadSeeker, w io.Writer, rotation int, selectedPages []string, conf *model.Configuration) error { 30 if rs == nil { 31 return errors.New("pdfcpu: Rotate: missing rs") 32 } 33 34 if conf == nil { 35 conf = model.NewDefaultConfiguration() 36 } 37 conf.Cmd = model.ROTATE 38 39 ctx, err := ReadValidateAndOptimize(rs, conf) 40 if err != nil { 41 return err 42 } 43 44 pages, err := PagesForPageSelection(ctx.PageCount, selectedPages, true, true) 45 if err != nil { 46 return err 47 } 48 49 if err = pdfcpu.RotatePages(ctx, pages, rotation); err != nil { 50 return err 51 } 52 53 return Write(ctx, w, conf) 54 } 55 56 // RotateFile rotates selected pages of inFile clockwise by rotation degrees and writes the result to outFile. 57 func RotateFile(inFile, outFile string, rotation int, selectedPages []string, conf *model.Configuration) (err error) { 58 var f1, f2 *os.File 59 60 if f1, err = os.Open(inFile); err != nil { 61 return err 62 } 63 64 tmpFile := inFile + ".tmp" 65 if outFile != "" && inFile != outFile { 66 tmpFile = outFile 67 logWritingTo(outFile) 68 } else { 69 logWritingTo(inFile) 70 } 71 if f2, err = os.Create(tmpFile); err != nil { 72 f1.Close() 73 return err 74 } 75 76 defer func() { 77 if err != nil { 78 f2.Close() 79 f1.Close() 80 os.Remove(tmpFile) 81 return 82 } 83 if err = f2.Close(); err != nil { 84 return 85 } 86 if err = f1.Close(); err != nil { 87 return 88 } 89 if outFile == "" || inFile == outFile { 90 err = os.Rename(tmpFile, inFile) 91 } 92 }() 93 94 return Rotate(f1, f2, rotation, selectedPages, conf) 95 }