package main import ( "fmt" "os/exec" "time" ) func ConvertToPDF(folderPath string, filesPaths []string, contType ContentType) (resultingPath string, err error) { switch contType { case Images: return ImagesToPDF(folderPath, filesPaths) case Office: return OfficeToPDF(folderPath, filesPaths) case Pdfs: return PdfToPDF(folderPath, filesPaths) default: return "", fmt.Errorf("unhandled ContentType with %d index", contType) } } func ImagesToPDF(folderPath string, filesPaths []string) (resultingPath string, err 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, err 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 PdfToPDF(folderPath string, filesPath []string) (resultingPath string, err error) { resultingPath = createResultingPath(folderPath, "PDFs") err = runCommand("gs", append([]string{ "-sDEVICE=pdfwrite", "-dCompressFonts=true", "-dPDFSETTINGS=/ebook", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile=" + resultingPath, }, filesPath...)...) 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 }