github.com/pdfcpu/pdfcpu@v0.11.1/pkg/api/zoom.go (about) 1 /* 2 Copyright 2024 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/log" 24 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu" 25 "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" 26 "github.com/pkg/errors" 27 ) 28 29 // Zoom applies resizeConf for selected pages of rs and writes result to w. 30 func Zoom(rs io.ReadSeeker, w io.Writer, selectedPages []string, zoom *model.Zoom, conf *model.Configuration) error { 31 if rs == nil { 32 return errors.New("pdfcpu: Zoom: missing rs") 33 } 34 35 if conf == nil { 36 conf = model.NewDefaultConfiguration() 37 } 38 conf.Cmd = model.ZOOM 39 40 ctx, err := ReadValidateAndOptimize(rs, conf) 41 if err != nil { 42 return err 43 } 44 45 pages, err := PagesForPageSelection(ctx.PageCount, selectedPages, true, true) 46 if err != nil { 47 return err 48 } 49 50 if err = pdfcpu.Zoom(ctx, pages, zoom); err != nil { 51 return err 52 } 53 54 return Write(ctx, w, conf) 55 } 56 57 // ZoomFile applies zoomConf for selected pages of inFile and writes result to outFile. 58 func ZoomFile(inFile, outFile string, selectedPages []string, zoom *model.Zoom, conf *model.Configuration) (err error) { 59 if log.CLIEnabled() { 60 log.CLI.Printf("zooming %s\n", inFile) 61 } 62 63 tmpFile := inFile + ".tmp" 64 if outFile != "" && inFile != outFile { 65 tmpFile = outFile 66 logWritingTo(outFile) 67 } else { 68 logWritingTo(inFile) 69 } 70 71 var ( 72 f1, f2 *os.File 73 ) 74 75 if f1, err = os.Open(inFile); err != nil { 76 return err 77 } 78 79 if f2, err = os.Create(tmpFile); err != nil { 80 f1.Close() 81 return err 82 } 83 84 defer func() { 85 if err != nil { 86 f2.Close() 87 f1.Close() 88 os.Remove(tmpFile) 89 return 90 } 91 if err = f2.Close(); err != nil { 92 return 93 } 94 if err = f1.Close(); err != nil { 95 return 96 } 97 if outFile == "" || inFile == outFile { 98 err = os.Rename(tmpFile, inFile) 99 } 100 }() 101 102 if conf == nil { 103 conf = model.NewDefaultConfiguration() 104 } 105 conf.Cmd = model.ZOOM 106 107 return Zoom(f1, f2, selectedPages, zoom, conf) 108 }