Created
September 11, 2023 10:01
-
-
Save devlights/d378a6449108976a8344f1307a125409 to your computer and use it in GitHub Desktop.
Word to PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log/slog" | |
"os" | |
"path/filepath" | |
"strings" | |
"github.com/devlights/gord" | |
"github.com/devlights/gord/constants" | |
) | |
type target struct { | |
p string // file-path | |
a string // file-abs-path | |
c string // converted file-path (pdf) | |
verbose bool | |
} | |
func (me *target) abs() string { | |
if me.a == "" { | |
v, _ := filepath.Abs(me.p) | |
me.a = v | |
} | |
if me.verbose { | |
slog.Info("abs", "path", me.a) | |
} | |
return me.a | |
} | |
func (me *target) convert() string { | |
if me.a == "" { | |
me.abs() | |
} | |
me.c = me.a[:strings.Index(me.a, filepath.Ext(me.a))] + ".pdf" | |
if me.verbose { | |
slog.Info("convert", "abs", me.a, "pdf", me.c) | |
} | |
return me.c | |
} | |
func main() { | |
var ( | |
verbose bool | |
) | |
flag.Usage = func() { | |
fmt.Fprintln(os.Stderr, "usage: word2pdf.exe (-v) word-file-path") | |
flag.PrintDefaults() | |
} | |
flag.BoolVar(&verbose, "v", false, "verbose log output") | |
flag.Parse() | |
if flag.NArg() < 1 { | |
flag.Usage() | |
return | |
} | |
if err := run(&target{p: flag.Arg(0), verbose: verbose}); err != nil { | |
slog.Error(err.Error()) | |
} | |
} | |
func run(p *target) error { | |
if p.verbose { | |
slog.Info("start") | |
defer slog.Info("done") | |
} | |
quitFn := gord.MustInitGord() | |
defer quitFn() | |
g, gordReleaseFn := gord.MustNewGord() | |
defer gordReleaseFn() | |
if err := g.SetVisible(false); err != nil { | |
return err | |
} | |
docs, err := g.Documents() | |
if err != nil { | |
return err | |
} | |
doc, docReleaseFn, err := docs.Open(p.abs()) | |
if err != nil { | |
return err | |
} | |
defer docReleaseFn() | |
if p.verbose { | |
slog.Info("Export start") | |
} | |
if err := doc.ExportAsFixedFormat(p.convert(), constants.WdExportFormatPDF); err != nil { | |
return err | |
} | |
if p.verbose { | |
slog.Info("Export end") | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment