1+ package main
2+
3+ import (
4+ "flag"
5+ "fmt"
6+ "os"
7+ "os/exec"
8+ "path/filepath"
9+ "time"
10+ )
11+
12+ const (
13+ // Path to the Mac PDF joiner utility
14+ pdfJoinerPath = "/System/Library/Automator/Combine PDF Pages.action/Contents/MacOS/join"
15+ )
16+
17+ func main () {
18+ // Define command-line flags
19+ outputPath := flag .String ("o" , "" , "Output path for the joined PDF" )
20+ flag .Parse ()
21+
22+ // Get the PDF files to join from the remaining arguments
23+ pdfFiles := flag .Args ()
24+ if len (pdfFiles ) < 2 {
25+ fmt .Println ("Error: At least two PDF files are required for joining" )
26+ fmt .Println ("Usage: pdf-joiner [-o output.pdf] file1.pdf file2.pdf [file3.pdf ...]" )
27+ os .Exit (1 )
28+ }
29+
30+ // Validate that all input files exist and are PDFs
31+ for _ , file := range pdfFiles {
32+ if ! fileExists (file ) {
33+ fmt .Printf ("Error: File '%s' does not exist\n " , file )
34+ os .Exit (1 )
35+ }
36+
37+ if filepath .Ext (file ) != ".pdf" {
38+ fmt .Printf ("Warning: File '%s' may not be a PDF file\n " , file )
39+ }
40+ }
41+
42+ // If no output path is provided, create a default one with the current date
43+ if * outputPath == "" {
44+ currentTime := time .Now ().Format ("2006-01-02-150405" )
45+ * outputPath = fmt .Sprintf ("joined-pdf-%s.pdf" , currentTime )
46+ }
47+
48+ // Ensure the output directory exists
49+ outputDir := filepath .Dir (* outputPath )
50+ if outputDir != "." && outputDir != "" {
51+ if err := os .MkdirAll (outputDir , 0755 ); err != nil {
52+ fmt .Printf ("Error creating output directory: %v\n " , err )
53+ os .Exit (1 )
54+ }
55+ }
56+
57+ // Check if the Mac PDF joiner utility exists
58+ if ! fileExists (pdfJoinerPath ) {
59+ fmt .Printf ("Error: PDF joiner utility not found at '%s'\n " , pdfJoinerPath )
60+ fmt .Println ("This tool only works on macOS systems." )
61+ os .Exit (1 )
62+ }
63+
64+ // Prepare the command to join PDFs
65+ args := []string {"-o" , * outputPath }
66+ args = append (args , pdfFiles ... )
67+
68+ // Execute the command
69+ cmd := exec .Command (pdfJoinerPath , args ... )
70+ output , err := cmd .CombinedOutput ()
71+
72+ if err != nil {
73+ fmt .Printf ("Error joining PDFs: %v\n " , err )
74+ fmt .Printf ("Command output: %s\n " , output )
75+ os .Exit (1 )
76+ }
77+
78+ fmt .Printf ("Successfully joined %d PDF files into '%s'\n " , len (pdfFiles ), * outputPath )
79+ }
80+
81+ // fileExists checks if a file exists and is not a directory
82+ func fileExists (path string ) bool {
83+ info , err := os .Stat (path )
84+ if os .IsNotExist (err ) {
85+ return false
86+ }
87+ return ! info .IsDir ()
88+ }
0 commit comments