any2pdf/convert.go
2022-09-24 17:56:55 +03:00

62 lines
1.5 KiB
Go

package main
import (
"fmt"
"os/exec"
"time"
)
func ConvertToPDF(folderPath string, filesPaths []string, contType ContentType) (resultingPath string, error error) {
switch contType {
case Images:
return ImagesToPDF(folderPath, filesPaths)
case Office:
return OfficeToPDF(folderPath, filesPaths)
default:
return "", fmt.Errorf("Unhandled ContentType with %d index", contType)
}
}
func ImagesToPDF(folderPath string, filesPaths []string) (resultingPath string, error error) {
resultingPath = createResultingPath(folderPath, "Images")
if err := runCommand("convert", append(filesPaths, resultingPath)...); err != nil {
return "", err
}
return resultingPath, nil
}
func OfficeToPDF(folderPath string, filesPaths []string) (resultingPath string, error error) {
resultingPath = createResultingPath(folderPath, "Office document")
err := runCommand(
"soffice", "--headless", "--nologo", "--nofirststartwizard",
"--norestore", "--convert-to", "pdf", "--outdir", folderPath, filesPaths[0],
)
if err != nil {
return "", err
}
err = runCommand("mv", folderPath + "/" + "0.pdf", resultingPath)
if err != nil {
return "", err
}
return resultingPath, nil
}
func createResultingPath(folderPath string, suffix string) string {
return folderPath + "/" + time.Now().Format(time.ANSIC) + " " + suffix + ".pdf"
}
func runCommand(command string, arg ...string) error {
cmd := exec.Command(command, arg...)
if err := cmd.Run(); err != nil {
return err
}
return nil
}