aboutsummaryrefslogtreecommitdiffstats
path: root/screenplain/export/pdf.py
blob: 6955616b6b8770bce68484484b33a98945c39a56 (plain) (blame)
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# Copyright (c) 2014 Martin Vilcans
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php

import sys

try:
    import reportlab
except ImportError:
    sys.stderr.write('ERROR: ReportLab is required for PDF output\n')
    raise
del reportlab

from reportlab.lib import pagesizes
from reportlab.platypus import (
    BaseDocTemplate,
    Paragraph,
    Frame,
    PageTemplate,
    Spacer,
)
from reportlab import platypus
from reportlab.lib.units import inch
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_RIGHT

from screenplain.types import (
    Action, Dialog, DualDialog, Transition, Slug
)
from screenplain import types

font_size = 12
line_height = 12
lines_per_page = 55
characters_per_line = 61
character_width = 1.0 / 10 * inch  # Courier pitch is 10 chars/inch
frame_height = line_height * lines_per_page
frame_width = characters_per_line * character_width

page_width, page_height = pagesizes.letter
left_margin = 1.5 * inch
right_margin = page_width - left_margin - frame_width
top_margin = 1 * inch
bottom_margin = page_height - top_margin - frame_height


default_style = ParagraphStyle(
    'default',
    fontName='Courier',
    fontSize=font_size,
    leading=line_height,
    spaceBefore=0,
    spaceAfter=0,
    leftIndent=0,
    rightIndent=0,
)
centered_style = ParagraphStyle(
    'default-centered', default_style,
    alignment=TA_CENTER,
)

# Screenplay styles
character_style = ParagraphStyle(
    'character', default_style,
    spaceBefore=line_height,
    leftIndent=19 * character_width,
    keepWithNext=1,
)
dialog_style = ParagraphStyle(
    'dialog', default_style,
    leftIndent=9 * character_width,
    rightIndent=frame_width - (45 * character_width),
)
parenthentical_style = ParagraphStyle(
    'parenthentical', default_style,
    leftIndent=13 * character_width,
    keepWithNext=1,
)
action_style = ParagraphStyle(
    'action', default_style,
    spaceBefore=line_height,
)
centered_action_style = ParagraphStyle(
    'centered-action', action_style,
    alignment=TA_CENTER,
)
slug_style = ParagraphStyle(
    'slug', default_style,
    spaceBefore=line_height,
    spaceAfter=line_height,
    keepWithNext=1,
)
transition_style = ParagraphStyle(
    'transition', default_style,
    spaceBefore=line_height,
    spaceAfter=line_height,
    alignment=TA_RIGHT,
)

# Title page styles
title_style = ParagraphStyle(
    'title', default_style,
    fontSize=24, leading=36,
    alignment=TA_CENTER,
)
contact_style = ParagraphStyle(
    'contact', default_style,
    leftIndent=3.9 * inch,
    rightIndent=0,
)


class DocTemplate(BaseDocTemplate):
    def __init__(self, *args, **kwargs):
        self.has_title_page = kwargs.pop('has_title_page', False)
        frame = Frame(
            left_margin, bottom_margin, frame_width, frame_height,
            id='normal',
            leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0
        )
        pageTemplates = [
            PageTemplate(id='standard', frames=[frame])
        ]
        BaseDocTemplate.__init__(
            self, pageTemplates=pageTemplates, *args, **kwargs
        )

    def handle_pageBegin(self):
        self.canv.setFont('Courier', font_size, leading=line_height)
        if self.has_title_page:
            page = self.page  # self.page is 0 on first page
        else:
            page = self.page + 1
        if page >= 2:
            self.canv.drawRightString(
                left_margin + frame_width,
                page_height - 42,
                '%s.' % page
            )
        self._handle_pageBegin()


def add_paragraph(story, para, style):
    story.append(Paragraph(
        '<br/>'.join(line.to_html() for line in para.lines),
        style
    ))


def add_slug(story, para, style, is_strong):
    for line in para.lines:
        if is_strong:
            html = '<b><u>' + line.to_html() + '</u></b>'
        else:
            html = line.to_html()
        story.append(Paragraph(html, style))


def add_dialog(story, dialog):
    story.append(Paragraph(dialog.character.to_html(), character_style))
    for parenthetical, line in dialog.blocks:
        if parenthetical:
            story.append(Paragraph(line.to_html(), parenthentical_style))
        else:
            story.append(Paragraph(line.to_html(), dialog_style))


def add_dual_dialog(story, dual):
    # TODO: format dual dialog
    add_dialog(story, dual.left)
    add_dialog(story, dual.right)


def get_title_page_story(screenplay):
    """Get Platypus flowables for the title page

    """
    # From Fountain spec:
    # The recommendation is that Title, Credit, Author (or Authors, either
    # is a valid key syntax), and Source will be centered on the page in
    # formatted output. Contact and Draft date would be placed at the lower
    # left.

    def add_lines(story, attribute, style, space_before=0):
        lines = screenplay.get_rich_attribute(attribute)
        if not lines:
            return 0

        if space_before:
            story.append(Spacer(frame_width, space_before))

        total_height = 0
        for line in lines:
            html = line.to_html()
            para = Paragraph(html, style)
            width, height = para.wrap(frame_width, frame_height)
            story.append(para)
            total_height += height
        return space_before + total_height

    title_story = []
    title_height = sum((
        add_lines(title_story, 'Title', title_style),
        add_lines(
            title_story, 'Credit', centered_style, space_before=line_height
        ),
        add_lines(title_story, 'Author', centered_style),
        add_lines(title_story, 'Authors', centered_style),
        add_lines(title_story, 'Source', centered_style),
    ))

    lower_story = []
    lower_height = sum((
        add_lines(lower_story, 'Draft date', default_style),
        add_lines(
            lower_story, 'Contact', contact_style, space_before=line_height
        ),
        add_lines(
            lower_story, 'Copyright', centered_style, space_before=line_height
        ),
    ))

    if not title_story and not lower_story:
        return []

    story = []
    top_space = min(
        frame_height / 3.0,
        frame_height - lower_height - title_height
    )
    if top_space > 0:
        story.append(Spacer(frame_width, top_space))
    story += title_story
    # The minus 6 adds some room for rounding errors and whatnot
    middle_space = frame_height - top_space - title_height - lower_height - 6
    if middle_space > 0:
        story.append(Spacer(frame_width, middle_space))
    story += lower_story

    story.append(platypus.PageBreak())
    return story


def to_pdf(
    screenplay, output_filename,
    template_constructor=DocTemplate,
    is_strong=False,
):
    story = get_title_page_story(screenplay)
    has_title_page = bool(story)

    for para in screenplay:
        if isinstance(para, Dialog):
            add_dialog(story, para)
        elif isinstance(para, DualDialog):
            add_dual_dialog(story, para)
        elif isinstance(para, Action):
            add_paragraph(
                story, para,
                centered_action_style if para.centered else action_style
            )
        elif isinstance(para, Slug):
            add_slug(story, para, slug_style, is_strong)
        elif isinstance(para, Transition):
            add_paragraph(story, para, transition_style)
        elif isinstance(para, types.PageBreak):
            story.append(platypus.PageBreak())
        else:
            # Ignore unknown types
            pass

    doc = template_constructor(
        output_filename,
        pagesize=(page_width, page_height),
        has_title_page=has_title_page
    )
    doc.build(story)