-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwqxtPDF.py
91 lines (79 loc) · 2.33 KB
/
wqxtPDF.py
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import shutil
from utils import *
import os
import img2pdf
import time
import fitz # pip3 install pymupdf
class wqxtPDF():
fileExt = ".pdf"
imgExt = ".jpeg"
PDFFolder = "books/PDF";
PDFTempFolder = "books/temp";
lists = [];
filePath = None;
tempPath = None;
def __init__( self, bid, name, bookmarks=[], lists=lists ):
self.bid = bid;
self.name = name;
self.lists = lists;
self.bookmarks = bookmarks;
mkdir(self.PDFFolder);
mkdir(self.PDFTempFolder);
[tempPath, filePath] = self.getFilePath();
self.tempPath = tempPath
self.filePath = filePath;
def getFilePath( self ):
if self.filePath:
return self.filePath;
else:
curTime = int(time.time());
PDFFolder = self.PDFFolder;
PDFTempFolder = self.PDFTempFolder;
bid = self.bid;
name = self.name;
fileExt = self.fileExt;
fileName = "{}_{}_{}{}".format( bid, name, curTime, fileExt );
tempName = "{}_{}_{}_nomarks{}".format( bid, name, curTime, fileExt );
tempNamePath = "/".join([ PDFTempFolder, tempName ]);
fileNamePath = "/".join([ PDFFolder, fileName ]);
return ([ tempNamePath, fileNamePath ]);
def addPage( self, filename ):
self.lists.append( filename );
def addPages( self, filesLists ):
self.lists += filesLists;
def generatePDF( self ):
tempPath = self.tempPath;
filePath = self.filePath;
lists = self.lists;
logging.info("生成pdf文件中");
pfn_bytes = img2pdf.convert( lists, with_pdfrw=False );
with open( tempPath, "wb" ) as f:
f.write(pfn_bytes);
f.close();
logging.info("向pdf写入目录中");
self.addBookMarks();
logging.info("【pdf路径】:\n{}".format( os.path.abspath(filePath) ));
time.sleep(0.1)
fold = os.getcwd() + "/books/IMG/"+self.bid
shutil.rmtree(fold)
print("已删除下载的图片。。。")
def addBookMarks( self ):
tempPath = self.tempPath;
filePath = self.filePath;
doc = fitz.open( tempPath );
toc = doc.getToC();
self.tocAppend( toc, self.bookmarks );
doc.setToC(toc);
doc.save( filePath );
doc.close();
os.remove( tempPath )
def tocAppend( self, toc, lists ):
for chapter in lists:
level = int(chapter['level']);
label = chapter['label'];
pnum = int(chapter['pnum']);
toc.append([ level, label, pnum ]);
if "children" in chapter.keys():
self.tocAppend( toc, chapter['children'] );