-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
110 lines (84 loc) · 2.18 KB
/
convert.go
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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package pdfimage
import (
"errors"
"fmt"
"image"
"image/jpeg"
"os"
"path/filepath"
"strings"
"github.com/disintegration/imaging"
"github.com/karmdip-mi/go-fitz"
)
func CheckInputError(input string, output string) error {
if input == "" || output == "" {
return errors.New("Input / Output parameters are needed")
}
filext := strings.ToLower(filepath.Ext(filepath.Base(input)))
if filext != ".pdf" {
return errors.New("Input parameter must be path of a file with PDF extension")
}
fi, err := os.Lstat(output)
if err != nil {
return err
}
if fi.Mode().IsDir() == false {
return errors.New("Output parameter is not a valid directory")
}
if _, err := os.Stat(output); err != nil {
if errors.Is(err, os.ErrNotExist) == true {
if err := os.Mkdir(output, 0666); err != nil {
return errors.New(fmt.Sprintf("Can't create output directory (%s): %s", output, err))
}
} else {
return err
}
}
return nil
}
func GetPdfImageData(input string, opt ConvertRequestOptions) ([]image.Image, error) {
doc, err := fitz.New(input)
if err != nil {
return nil, err
}
var images []image.Image
for n := 0; n < doc.NumPage(); n++ {
imgdata, err := doc.Image(n)
if err != nil {
panic(err)
}
if opt.Size.H != 0 || opt.Size.W != 0 {
imgdata = imaging.Resize(imgdata, opt.Size.W, opt.Size.H, imaging.Linear)
}
if opt.Grayscale == true {
imgdata = imaging.Grayscale(imgdata)
}
images = append(images, imgdata)
}
return images, nil
}
func PdfToImage(input string, output string, opt ConvertRequestOptions) ([]string, error) {
if err := CheckInputError(input, output); err != nil {
return nil, err
}
var filelist []string
pdfimgdata, err := GetPdfImageData(input, opt)
if err != nil {
return nil, err
}
imgprefix := strings.TrimSuffix(strings.ToLower(filepath.Base(input)), ".pdf")
for n, img := range pdfimgdata {
filename := fmt.Sprintf("%s/%s_%03d.jpg", output, imgprefix, n)
file, err := os.Create(filename)
if err != nil {
panic(err)
}
err = jpeg.Encode(file, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
if err != nil {
panic(err)
}
file.Close()
filelist = append(filelist, filename)
}
return filelist, nil
}