-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlitehtml-pango-png.py
executable file
·118 lines (102 loc) · 3.18 KB
/
litehtml-pango-png.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env vpython3
import gc
import sys
import os
import io
import logging
import requests
import urllib.parse
from PIL import Image
import logme
from litehtmlpy import litehtmlpango, litehtmlpy
litehtmlpy.debuglog(1)
logger = logging.getLogger(__name__)
class document_container(litehtmlpango.document_container):
def import_css(self, text, url, base_url):
url = urllib.parse.urljoin(base_url, url)
if os.path.exists(url):
with open(url, 'rt') as fp:
data = fp.read()
elif url.split(':')[0] in ('http', 'https'):
r = requests.get(url)
if r.headers['Content-Type'] == 'text/css':
data = r.text
if data is None:
print('unknown import_css', url)
return
return data
class App:
images = {}
url = ''
def GetUrlData(self, url, html=True):
data = None
if os.path.exists(url):
with open(url, 'rb') as fp:
data = fp.read()
elif url.split(':')[0] in ('http', 'https'):
r = requests.get(url)
print(r.headers)
if html:
if r.headers['Content-Type'] == 'text/html':
data = r.text
else:
if r.headers['Content-Type'] == 'image/png':
data = r.content
if data is None:
return None
return data
def HtmlLoadImage(self, cntr, src, baseurl, redraw_on_ready):
if baseurl is not None:
url = urllib.parse.urljoin(baseurl, src)
else:
url = urllib.parse.urljoin(self.url, src)
data = self.GetUrlData(url, False)
print('HtmlLoadImage({}, {})'.format(url, data is not None))
if data is None:
return
try:
im = Image.open(io.BytesIO(data))
except:
print('bang')
return
if 'A' not in im.getbands():
alpha = 1.0
im.putalpha(int(alpha * 256.))
try:
arr = bytearray(im.tobytes('raw', 'BGRa'))
except ValueError:
return
cntr.put_image(url, arr, im.width, im.height)
class Main:
def demo(self):
app = App()
if len(sys.argv) > 1:
fname = sys.argv[1]
else:
fname = 'demo.html'
fname = 'litehtmlt.html'
html = open(fname, 'rt').read()
cntr = document_container(app)
print('max size=', cntr.size)
doc = cntr.fromString(html, None, None)
doc.render(cntr.size[0], litehtmlpy.render_all)
print('doc: width:', doc.width(), 'height:', doc.height())
cntr.size[1] = doc.height()
hdc = cntr.surface(doc.width(), doc.height())
print('*'*10, 'draw')
clip = litehtmlpy.position(0, 0, doc.width(), doc.height())
doc.draw(hdc, 0, 0, clip)
print('x-save')
cntr.save('demo.png')
print('x-save-stream')
with open('demo-1.png', 'wb') as fpo:
rc = cntr.savestream(fpo.write)
print('save result:', rc)
del doc
cntr.clear_images()
del cntr
def main():
app = Main()
app.demo()
main()
gc.collect()