-
Notifications
You must be signed in to change notification settings - Fork 21
/
OffScreenHTML.py
executable file
·100 lines (75 loc) · 2.62 KB
/
OffScreenHTML.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
#!/usr/bin/env python
"""
test of rendering HTML to an off-screen bitmap
This version uses a wx.GCDC, so you can have an alpha background.
Works on OS-X, may need an explicit alpha bitmap on other platforms
"""
import wx
import wx.html
class OffScreenHTML:
def __init__(self, width, height):
self.width = width
self.height = height
self.Buffer = wx.Bitmap(width, height)
self.HR = wx.html.HtmlDCRenderer()
# a bunch of defaults...
self.BackgroundColor = "white"
self.BackgroundColor = (255, 255, 255, 50)
self.Padding = 10
def Render(self, source):
"""
Render the html source to the bitmap
"""
DC = wx.MemoryDC()
DC.SelectObject(self.Buffer)
DC = wx.GCDC(DC)
DC.SetBackground(wx.Brush(self.BackgroundColor))
DC.Clear()
self.HR.SetDC(DC, 1.0)
self.HR.SetSize(self.width - 2 * self.Padding, self.height)
self.HR.SetHtmlText(source)
self.HR.Render(self.Padding, self.Padding, [])
self.RenderedSize = (self.width, self.HR.GetTotalHeight() + 2 * self.Padding)
def SaveAsPNG(self, filename):
sub = self.Buffer.GetSubBitmap(wx.Rect(0, 0, *self.RenderedSize) )
print("saving as: ", filename)
sub.SaveFile(filename, wx.BITMAP_TYPE_PNG)
class Text2html:
"""
A simple class for converting plain text to basic HTML
This is an alternative to using <pre> -- I want it to wrap, but otherwise preserve newlines, etc.
"""
def __init__(self):
pass
def Convert(self, text):
"""
Takes raw text, and returns html with newlines converted, etc.
"""
print("raw text:", text)
# double returns are a new paragraph
text = text.split("\n\n")
print("split by paragraphs:", text)
text = [p.strip().replace("\n","<br>") for p in text]
print(text)
text = "<p>\n" + "\n</p>\n<p>\n".join(text) + "\n</p>"
return text
if __name__ == "__main__":
HTML = """ <h1> A Title </h1>
<p>This is a simple test of rendering a little text with an html renderer</p>
<p>
Now another paragraph, with a bunch more text in it. This is a test
that will show if it can take care of the basic rendering for us, and
auto-wrap, and all sorts of nifty stuff like that
</p>
<p>
and here is some <b> Bold Text </b>
<p> It does seem to work OK </p>
"""
App = wx.App(False)
OSR = OffScreenHTML(500, 500)
OSR.width = 200
OSR.Render(HTML)
OSR.SaveAsPNG('junk.png')
OSR.width = 300
OSR.Render(HTML)
OSR.SaveAsPNG('junk2.png')