go用unioffice轉換word文件為pdf

卓能文發表於2024-07-06
package main

import (
	"log"
	"os"
	"path/filepath"

	"github.com/unidoc/unioffice/document"
	"github.com/unidoc/unioffice/document/convert"
)

func main() {
	// cmd, _ := os.Getwd()
	err := convert.RegisterFontsFromDirectory("C:/Windows/Fonts")
	if err != nil {
		log.Fatalf("Error registering fonts from the folder: %s\n", err)
	}
	allArgs := os.Args[1:]
	for _, arg := range allArgs {
		files, _ := filepath.Glob(arg)
		for _, file := range files {
			ext := filepath.Ext(file)
			newFile := file[:len(file)-len(ext)] + ".pdf"
			log.Print(newFile)
			// err := ConvertToPDF(filepath.Join(cmd, file), filepath.Join(cmd, newFile))
			err := wordToPDF(file, newFile)
			if err != nil {
				log.Printf("error creating Word object: %s", err)
			}
		}
	}
}

func wordToPDF(inputPath string, outputPath string) error {
	doc, err := document.Open(inputPath)
	if err != nil {
		return err
	}
	defer doc.Close()
	c := convert.ConvertToPdf(doc)

	err = c.WriteToFile(outputPath)
	if err != nil {
		return err
	}

	return nil
}

轉換的效果不是太理想。

相關文章