85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"time"
|
|
)
|
|
|
|
func ConvertToPDF(folderPath string, filesPaths []string, contType ContentType, name string) (resultingPath string, err error) {
|
|
switch contType {
|
|
case Images:
|
|
return ImagesToPDF(folderPath, filesPaths, name)
|
|
case Office:
|
|
return OfficeToPDF(folderPath, filesPaths, name)
|
|
case Pdfs:
|
|
return PdfToPDF(folderPath, filesPaths, name)
|
|
default:
|
|
return "", fmt.Errorf("unhandled ContentType with %d index", contType)
|
|
}
|
|
}
|
|
|
|
func ImagesToPDF(folderPath string, filesPaths []string, name string) (resultingPath string, err error) {
|
|
resultingPath = createResultingPath(folderPath, "Images", name)
|
|
|
|
if err := runCommand("convert", append(filesPaths, resultingPath)...); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return resultingPath, nil
|
|
}
|
|
|
|
func OfficeToPDF(folderPath string, filesPaths []string, name string) (resultingPath string, err error) {
|
|
resultingPath = createResultingPath(folderPath, "Office document", name)
|
|
|
|
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, name string) (resultingPath string, err error) {
|
|
resultingPath = createResultingPath(folderPath, "PDFs", name)
|
|
|
|
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, name string) string {
|
|
filename := time.Now().Format(time.ANSIC) + " " + suffix + ".pdf"
|
|
|
|
if len(name) > 0 {
|
|
filename = name + ".pdf"
|
|
}
|
|
|
|
return folderPath + "/" + filename
|
|
}
|
|
|
|
func runCommand(command string, arg ...string) error {
|
|
cmd := exec.Command(command, arg...)
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|