cbz2pdf/main.go

95 lines
2.2 KiB
Go
Raw Normal View History

2023-04-07 14:33:39 +02:00
package main
import (
"archive/zip"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"github.com/fatih/color"
)
var ( //flags
FlagOutputFile = flag.String("o", "output.pdf", "output file name")
)
var ( // colors
ColorRed = color.New(color.FgRed)
)
func main() {
flag.Parse()
if _, err := exec.LookPath("img2pdf"); err != nil {
ColorRed.Fprintln(os.Stderr, "img2pdf not installed")
os.Exit(1)
}
inputFilePath := flag.Arg(0)
if inputFilePath == "" {
ColorRed.Fprintln(os.Stderr, "please provide an input file path")
os.Exit(1)
}
inputFile, err := os.Open(inputFilePath)
if err != nil {
ColorRed.Fprintf(os.Stderr, "input file path could not be read: %s\n", err.Error())
os.Exit(1)
}
defer inputFile.Close()
fi, err := inputFile.Stat()
if err != nil {
ColorRed.Fprintf(os.Stderr, "input file path could not be read: %s\n", err.Error())
os.Exit(1)
}
zipr, err := zip.NewReader(inputFile, fi.Size())
if err != nil {
ColorRed.Fprintf(os.Stderr, "input file path could not be read: %s\n", err.Error())
os.Exit(1)
}
tempFiles := make([]string, 0, len(zipr.File))
for _, file := range zipr.File {
ext := filepath.Ext(file.Name)
tempFile, err := os.CreateTemp("", fmt.Sprintf("*%s", ext))
if err != nil {
ColorRed.Fprintf(os.Stderr, "temporary file could not be created: %s\n", err.Error())
os.Exit(1)
}
defer os.Remove(tempFile.Name())
defer tempFile.Close()
tempFiles = append(tempFiles, tempFile.Name())
imgFile, err := file.Open()
if err != nil {
ColorRed.Fprintf(os.Stderr, "compressed file could not be read: %s\n", err.Error())
os.Exit(1)
}
defer imgFile.Close()
if _, err := io.Copy(tempFile, imgFile); err != nil {
ColorRed.Fprintf(os.Stderr, "coud not create image file: %s\n", err.Error())
os.Exit(1)
}
tempFile.Close()
}
args := append([]string{"--output", *FlagOutputFile}, tempFiles...)
img2pdf := exec.Command("img2pdf", args...)
if err := img2pdf.Start(); err != nil {
ColorRed.Fprintf(os.Stderr, "img2pdf could not be started: %s\n", err.Error())
os.Exit(1)
}
if err := img2pdf.Wait(); err != nil {
ColorRed.Fprintf(os.Stderr, "img2pdf returned an error: %s\n", err.Error())
os.Exit(1)
}
}