-
Notifications
You must be signed in to change notification settings - Fork 5
/
cmd-pdf.go
69 lines (56 loc) · 1.5 KB
/
cmd-pdf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
. "github.com/spf13/cobra"
"io/ioutil"
"os"
"os/exec"
"strconv"
"strings"
)
func cmdPdf(rootCmd *Command) {
rootCmd.AddCommand(&Command{
Use: "pdf [item id] | pdf [item id] [pdf file name]",
Short: "Save item as PDF",
Long: "Save item as PDF",
Run: func(cmd *Command, args []string) {
if len(args) < 1 {
fatal("not enough arguments")
}
itemId, err := strconv.Atoi(args[0])
failOnError(err)
item, err := itemRepository.ItemOfId(itemId)
failOnError(err)
tempDir, err := ioutil.TempDir("/tmp", "kobito")
failOnError(err)
defer os.RemoveAll(tempDir)
// HTML を書き込む
ioutil.WriteFile(tempDir+"/index.html", []byte(item.Html), os.ModePerm)
// CSS などをコピーする
assets := []string{
"highlight.pack.js",
"github.min.css",
"markdown.css",
}
kobitoPath, err := kobitoPath()
failOnError(err)
for _, asset := range assets {
err := os.Symlink(kobitoPath+"/Contents/Resources/"+asset, tempDir+"/"+asset)
failOnError(err)
}
// 保存先ファイルを作る
var pdfFilename string
if len(args) >= 2 {
pdfFilename = args[1]
} else {
pdfFilename = strings.Replace(item.Title, "/", ":", -1) + ".pdf"
}
pdfFile, err := os.OpenFile(pdfFilename, os.O_WRONLY|os.O_CREATE, 0600)
failOnError(err)
defer pdfFile.Close()
// PDFに変換する
cupsfilter := exec.Command("/usr/sbin/cupsfilter", tempDir+"/index.html")
cupsfilter.Stdout = pdfFile
cupsfilter.Run()
},
})
}