96 lines
1.9 KiB
Go
96 lines
1.9 KiB
Go
//go:build !nofitz
|
|
|
|
package services
|
|
|
|
import (
|
|
"fmt"
|
|
"image"
|
|
"image/jpeg"
|
|
"image/png"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/gen2brain/go-fitz"
|
|
)
|
|
|
|
func extractTextWithFitz(inputPath string) (string, error) {
|
|
doc, err := fitz.New(inputPath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("open PDF failed: %v", err)
|
|
}
|
|
defer doc.Close()
|
|
|
|
var texts []string
|
|
for i := 0; i < doc.NumPage(); i++ {
|
|
text, err := doc.Text(i)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if text != "" {
|
|
texts = append(texts, text)
|
|
}
|
|
}
|
|
return strings.Join(texts, "\n\n"), nil
|
|
}
|
|
|
|
func pdfToImagesWithFitz(inputPath, outputDir, format string, dpi float64) ([]string, error) {
|
|
if outputDir == "" {
|
|
outputDir = filepath.Dir(inputPath)
|
|
}
|
|
if dpi <= 0 {
|
|
dpi = 150
|
|
}
|
|
|
|
doc, err := fitz.New(inputPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open PDF failed: %v", err)
|
|
}
|
|
defer doc.Close()
|
|
|
|
baseName := GetBaseName(inputPath)
|
|
var results []string
|
|
|
|
for i := 0; i < doc.NumPage(); i++ {
|
|
img, err := doc.ImageDPI(i, dpi)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
var outPath string
|
|
if format == "jpeg" || format == "jpg" {
|
|
outPath = filepath.Join(outputDir, fmt.Sprintf("%s_page_%d.jpg", baseName, i+1))
|
|
err = saveJPEGFile(img, outPath, 90)
|
|
} else {
|
|
outPath = filepath.Join(outputDir, fmt.Sprintf("%s_page_%d.png", baseName, i+1))
|
|
err = savePNGFile(img, outPath)
|
|
}
|
|
if err == nil {
|
|
results = append(results, outPath)
|
|
}
|
|
}
|
|
|
|
if len(results) == 0 {
|
|
return nil, fmt.Errorf("no images generated")
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
func savePNGFile(img image.Image, path string) error {
|
|
f, err := os.Create(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
return png.Encode(f, img)
|
|
}
|
|
|
|
func saveJPEGFile(img image.Image, path string, quality int) error {
|
|
f, err := os.Create(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
return jpeg.Encode(f, img, &jpeg.Options{Quality: quality})
|
|
}
|