package main import ( "archive/zip" "flag" "fmt" "io" "os" "os/exec" "path/filepath" "github.com/fatih/color" ) var 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) } if len(flag.Args()) == 0 { ColorRed.Fprintln(os.Stderr, "please provide at least one input file path") os.Exit(1) } for _, inputFilePath := range flag.Args() { Convert(inputFilePath) } } func Convert(inputFilePath string) { 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() } outputFilePath := fmt.Sprintf("%s.pdf", filepath.Base(inputFilePath)[:len(inputFilePath)-len(filepath.Ext(inputFilePath))]) args := append([]string{"--output", outputFilePath}, 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) } fmt.Println(outputFilePath) }