This repository has been archived by the owner on Jan 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (84 loc) · 2.01 KB
/
main.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
package main
import (
"flag"
"fmt"
"image/png"
"log"
"os"
"path/filepath"
"github.com/unidoc/unipdf/v3/extractor"
"github.com/unidoc/unipdf/v3/model"
)
func main() {
home, _ := os.UserHomeDir()
inputPath := flag.String("input", "./input.pdf", "PDF file path")
outputPath := flag.String("output", filepath.Join(home, "Downloads"), "Output zip file path")
flag.Parse()
err := extractPDFImage(*inputPath, *outputPath)
if err != nil {
log.Fatalf("Error: %v\n", err)
}
}
func extractPDFImage(inputPath, outputPath string) error {
pdfReader, f, err := model.NewPdfReaderFromFile(inputPath, nil)
if err != nil {
return err
}
defer f.Close()
numPages, err := pdfReader.GetNumPages()
if err != nil {
return err
}
log.Printf("Loading %d pages\n", numPages)
inputPathHash := fmt.Sprintf("%x", inputPath)
for i := 0; i < numPages; i++ {
err2 := extractPageImage(pdfReader, i, inputPathHash, outputPath)
if err2 != nil {
return err2
}
}
return nil
}
func extractPageImage(pdfReader *model.PdfReader, i int, inputPathHash string, outputPath string) error {
page, err := pdfReader.GetPage(i + 1)
if err != nil {
return err
}
pageReader, err := extractor.New(page)
if err != nil {
return err
}
images, err := pageReader.ExtractPageImages(&extractor.ImageExtractOptions{
IncludeInlineStencilMasks: false,
})
if err != nil {
return err
}
log.Printf("Page %d: %d images\n", i+1, len(images.Images))
for idx, img := range images.Images {
imgName := fmt.Sprintf("%s_%d_%d.png", inputPathHash, i+1, idx+1)
err2 := savePNG(imgName, outputPath, img)
if err2 != nil {
return err2
}
}
return nil
}
func savePNG(imgName, outputPath string, img extractor.ImageMark) error {
imgPath := filepath.Join(outputPath, imgName)
log.Printf("Saving image to %s\n", imgPath)
imgFile, err := os.Create(imgPath)
if err != nil {
return err
}
defer imgFile.Close()
image, err := img.Image.ToGoImage()
if err != nil {
return err
}
err = png.Encode(imgFile, image)
if err != nil {
return err
}
return nil
}