2017-05-06 16:16:27 +08:00
|
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"os/exec"
|
|
|
|
|
"bufio"
|
|
|
|
|
"io"
|
|
|
|
|
"io/ioutil"
|
2017-05-09 10:04:56 +08:00
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
|
|
"github.com/axgle/mahonia"
|
2017-05-06 16:16:27 +08:00
|
|
|
|
"github.com/astaxie/beego"
|
|
|
|
|
)
|
2017-05-09 10:04:56 +08:00
|
|
|
|
|
|
|
|
|
// 使用 wkhtmltopdf 是实现 html 转 pdf.
|
2017-05-06 16:16:27 +08:00
|
|
|
|
// 中文说明:http://www.jianshu.com/p/4d65857ffe5e#
|
2017-05-09 10:04:56 +08:00
|
|
|
|
func ConverterHtmlToPdf(uri []string,path string) (error) {
|
2017-05-06 16:16:27 +08:00
|
|
|
|
|
|
|
|
|
exe := beego.AppConfig.String("wkhtmltopdf")
|
|
|
|
|
|
|
|
|
|
if exe == "" {
|
2017-05-09 10:04:56 +08:00
|
|
|
|
return errors.New("wkhtmltopdf not exist.")
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
params := []string{"/C",exe,"--margin-bottom","25"}
|
|
|
|
|
|
|
|
|
|
params = append(params,uri...)
|
|
|
|
|
params = append(params,path)
|
|
|
|
|
|
2017-05-11 16:14:29 +08:00
|
|
|
|
beego.Info(params)
|
2017-05-11 16:12:56 +08:00
|
|
|
|
|
2017-05-06 16:16:27 +08:00
|
|
|
|
cmd := exec.Command("cmd",params...)
|
|
|
|
|
|
|
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
2017-05-09 10:04:56 +08:00
|
|
|
|
return errors.New("StdoutPipe: " + err.Error())
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
stderr, err := cmd.StderrPipe()
|
|
|
|
|
if err != nil {
|
2017-05-09 10:04:56 +08:00
|
|
|
|
|
|
|
|
|
return errors.New("StderrPipe: " + err.Error())
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := cmd.Start(); err != nil {
|
2017-05-09 10:04:56 +08:00
|
|
|
|
|
|
|
|
|
return errors.New("Start: "+ err.Error())
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
reader := bufio.NewReader(stdout)
|
|
|
|
|
enc := mahonia.NewDecoder("gbk")
|
|
|
|
|
|
|
|
|
|
//实时循环读取输出流中的一行内容
|
|
|
|
|
for {
|
|
|
|
|
line ,err2 := reader.ReadString('\n')
|
|
|
|
|
|
|
|
|
|
if err2 != nil || io.EOF == err2 {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-09 10:04:56 +08:00
|
|
|
|
beego.Info(enc.ConvertString(line))
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bytesErr, err := ioutil.ReadAll(stderr)
|
|
|
|
|
|
|
|
|
|
if err == nil {
|
2017-05-09 10:04:56 +08:00
|
|
|
|
beego.Info(enc.ConvertString(string(bytesErr)))
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}else{
|
|
|
|
|
beego.Error("Error: Stderr => " + err.Error())
|
2017-05-09 10:04:56 +08:00
|
|
|
|
return err
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := cmd.Wait(); err != nil {
|
|
|
|
|
|
|
|
|
|
beego.Error("Error: ", err.Error())
|
|
|
|
|
|
2017-05-09 10:04:56 +08:00
|
|
|
|
return err
|
2017-05-06 16:16:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-09 10:04:56 +08:00
|
|
|
|
return nil
|
2017-05-06 16:16:27 +08:00
|
|
|
|
|
|
|
|
|
}
|