/
backends.py
109 lines (83 loc) · 3 KB
/
backends.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
# coding: utf8
"""
weasyprint.backends
-------------------
Abstract over the API differences of the various cairo surfaces.
Expected usage:
* Create an instance
* For each page: call .start_page() and paint on the returned context
* Call .finish()
:copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
import io
import math
import shutil
import cairo
from . import draw
from . import pdf
class SimplePDFBackend(object):
enable_hinting = False
def __init__(self, target):
# We’ll change the surface size in .start_page()
self.surface = cairo.PDFSurface(target, 1, 1)
self.started = False
def start_page(self, width, height):
surface = self.surface
# Start a new page, except if this is the first:
if self.started:
surface.show_page()
else:
self.started = True
px_to_pt = pdf.PX_TO_PT
surface.set_size(width * px_to_pt, height * px_to_pt)
context = draw.CairoContext(surface)
context.scale(px_to_pt, px_to_pt)
return context
def finish(self, _document):
self.surface.finish()
class MetadataPDFBackend(SimplePDFBackend):
def __init__(self, target):
self.target = target
self.fileobj = io.BytesIO()
super(MetadataPDFBackend, self).__init__(self.fileobj)
def finish(self, document):
super(MetadataPDFBackend, self).finish(document)
fileobj = self.fileobj
target = self.target
pdf.write_pdf_metadata(document, fileobj)
fileobj.seek(0)
if hasattr(target, 'write'):
shutil.copyfileobj(fileobj, target)
else:
with open(target, 'wb') as fd:
shutil.copyfileobj(fileobj, fd)
class PNGBackend(object):
enable_hinting = True
def __init__(self, target):
self.target = target
self.pages = []
def start_page(self, width, height):
width = int(math.ceil(width))
height = int(math.ceil(height))
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
self.pages.append((width, height, surface))
return draw.CairoContext(surface)
def finish(self, _document):
pages = self.pages
if len(pages) == 1:
_, _, surface = pages[0]
else:
total_height = sum(height for width, height, surface in pages)
max_width = max(width for width, height, surface in pages)
surface = cairo.ImageSurface(
cairo.FORMAT_ARGB32, max_width, total_height)
context = draw.CairoContext(surface)
pos_y = 0
for width, height, page_surface in pages:
pos_x = (max_width - width) // 2
context.set_source_surface(page_surface, pos_x, pos_y)
context.paint()
pos_y += height
surface.write_to_png(self.target)