forked from ystyle/kaf-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepub.go
72 lines (64 loc) · 1.72 KB
/
epub.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
70
71
72
package kafcli
import (
"bytes"
"fmt"
"github.com/bmaupin/go-epub"
"os"
"path/filepath"
"time"
)
type EpubConverter struct{}
func (convert EpubConverter) wrapTitle(title, content string) string {
var buff bytes.Buffer
buff.WriteString(htmlTitleStart)
buff.WriteString(title)
buff.WriteString(htmlTitleEnd)
buff.WriteString(content)
return buff.String()
}
func (convert EpubConverter) Build(book Book) error {
fmt.Println("正在生成epub")
start := time.Now()
// 写入样式
tempDir, err := os.MkdirTemp("", "kaf-cli")
defer func() {
if err := os.RemoveAll(tempDir); err != nil {
panic(fmt.Sprintf("创建临时文件夹失败: %s", err))
}
}()
pageStylesFile := filepath.Join(tempDir, "page_styles.css")
err = os.WriteFile(pageStylesFile, []byte(fmt.Sprintf(cssContent, book.Align, book.Bottom, book.Indent)), 0666)
if err != nil {
return fmt.Errorf("无法写入样式文件: %w", err)
}
// Create a ne EPUB
e := epub.NewEpub(book.Bookname)
e.SetLang(book.Lang)
// Set the author
e.SetAuthor(book.Author)
css, err := e.AddCSS(pageStylesFile, "")
if err != nil {
return fmt.Errorf("无法写入样式文件: %w", err)
}
if book.Cover != "" {
img, err := e.AddImage(book.Cover, filepath.Base(book.Cover))
if err != nil {
return fmt.Errorf("添加封面失败: %w", err)
}
e.SetCover(img, "")
}
for _, section := range book.SectionList {
e.AddSection(convert.wrapTitle(section.Title, section.Content), section.Title, "", css)
}
// Write the EPUB
fmt.Println("正在生成电子书...")
epubName := book.Out + ".epub"
err = e.Write(epubName)
if err != nil {
// handle error
}
// 计算耗时
end := time.Now().Sub(start)
fmt.Println("生成EPUB电子书耗时:", end)
return nil
}