Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Refactor PDF generation code for workouts

Roland Geider5c91ac1fc736
diff --git a/wger/manager/helpers.py b/wger/manager/helpers.py
index 3185a4d8d..446d0aadf 100644
--- a/wger/manager/helpers.py
+++ b/wger/manager/helpers.py
@@ -36,11 +36,25 @@ from wger.utils.helpers import normalize_decimal
from wger.utils.pdf import styleSheet
-def render_workout_day(day, nr_of_weeks, images=False, comments=False):
+def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_table=False):
'''
Render a table with reportlab with the contents of the training day
+
+ :param day: a workout day object
+ :param nr_of_weeks: the numbrer of weeks to render, default is 7
+ :param images: boolean indicating whether to also draw exercise images
+ in the PDF (actually only the main image)
+ :param comments: boolean indicathing whether the exercise comments will
+ be rendered as well
+ :param only_table: boolean indicating whether to draw a table with space
+ for weight logs or just a list of the exercises
'''
+ # If rendering only the table, reset the nr of weeks, since these columns
+ # will not be rendered anyway.
+ if only_table:
+ nr_of_weeks = 0
+
data = []
# Init some counters and markers, this will be used after the iteration to
@@ -152,9 +166,14 @@ def render_workout_day(day, nr_of_weeks, images=False, comments=False):
# Put everything together and manually set some of the widths
t = Table(data, style=table_style)
if len(t._argW) > 1:
- t._argW[0] = 0.6 * cm # Numbering
- t._argW[1] = 4 * cm # Exercise
- t._argW[2] = 2.5 * cm # Repetitions
+ if only_table:
+ t._argW[0] = 0.6 * cm # Numbering
+ t._argW[1] = 8 * cm # Exercise
+ t._argW[2] = 3.5 * cm # Repetitions
+ else:
+ t._argW[0] = 0.6 * cm # Numbering
+ t._argW[1] = 4 * cm # Exercise
+ t._argW[2] = 2.5 * cm # Repetitions
return KeepTogether(t)
diff --git a/wger/manager/tests/test_pdf.py b/wger/manager/tests/test_pdf.py
index d255d81b8..8141e36fb 100644
--- a/wger/manager/tests/test_pdf.py
+++ b/wger/manager/tests/test_pdf.py
@@ -76,6 +76,67 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):
self.assertGreater(int(response['Content-Length']), 29000)
self.assertLess(int(response['Content-Length']), 35000)
+ def export_pdf_with_comments(self, fail=False):
+ '''
+ Helper function to test exporting a workout as a pdf, with exercise coments
+ '''
+
+ response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
+ 'comments': 0}))
+
+ if fail:
+ self.assertIn(response.status_code, (403, 404, 302))
+ else:
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/pdf')
+ self.assertEqual(response['Content-Disposition'],
+ 'attachment; filename=Workout-3-log.pdf')
+
+ # Approximate size only
+ self.assertGreater(int(response['Content-Length']), 29000)
+ self.assertLess(int(response['Content-Length']), 35000)
+
+ def export_pdf_with_images(self, fail=False):
+ '''
+ Helper function to test exporting a workout as a pdf, with exercise images
+ '''
+
+ response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
+ 'images': 1}))
+
+ if fail:
+ self.assertIn(response.status_code, (403, 404, 302))
+ else:
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/pdf')
+ self.assertEqual(response['Content-Disposition'],
+ 'attachment; filename=Workout-3-log.pdf')
+
+ # Approximate size only
+ self.assertGreater(int(response['Content-Length']), 29000)
+ self.assertLess(int(response['Content-Length']), 35000)
+
+ def export_pdf_with_images_and_comments(self, fail=False):
+ '''
+ Helper function to test exporting a workout as a pdf, with images and comments
+ '''
+
+ response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3,
+ 'images': 1,
+ 'comments': 1}))
+
+ if fail:
+ self.assertIn(response.status_code, (403, 404, 302))
+ else:
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/pdf')
+ self.assertEqual(response['Content-Disposition'],
+ 'attachment; filename=Workout-3-log.pdf')
+
+ # Approximate size only
+ self.assertGreater(int(response['Content-Length']), 29000)
+ self.assertLess(int(response['Content-Length']), 35000)
+
def test_export_pdf_anonymous(self):
'''
Tests exporting a workout as a pdf as an anonymous user
diff --git a/wger/manager/urls.py b/wger/manager/urls.py
index e5932396c..e62ae1aa0 100644
--- a/wger/manager/urls.py
+++ b/wger/manager/urls.py
@@ -94,12 +94,21 @@ patterns_workout = [
url(r'^(?P<id>\d+)/pdf/log/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
pdf.workout_log,
name='pdf-log'),
+ url(r'^(?P<id>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)$',
+ pdf.workout_log,
+ name='pdf-log'),
url(r'^(?P<id>\d+)/pdf/log$',
pdf.workout_log,
name='pdf-log'),
+ url(r'^(?P<id>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
+ pdf.workout_view,
+ name='pdf-table'),
url(r'^(?P<id>\d+)/pdf/table/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
pdf.workout_view,
name='pdf-table'),
+ url(r'^(?P<id>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)$',
+ pdf.workout_view,
+ name='pdf-table'),
url(r'^(?P<id>\d+)/pdf/table$',
pdf.workout_view,
name='pdf-table'),
diff --git a/wger/manager/views/pdf.py b/wger/manager/views/pdf.py
index d8667e082..adc0ad3d8 100644
--- a/wger/manager/views/pdf.py
+++ b/wger/manager/views/pdf.py
@@ -92,7 +92,7 @@ def workout_log(request, id, images=False, comments=False, uidb64=None, token=No
# Iterate through the Workout and render the training days
for day in workout.canonical_representation['day_list']:
- elements.append(render_workout_day(day, nr_of_weeks=7, images=images, comments=comments))
+ elements.append(render_workout_day(day, images=images, comments=comments))
elements.append(Spacer(10 * cm, 0.5 * cm))
# Footer, date and info
@@ -103,18 +103,25 @@ def workout_log(request, id, images=False, comments=False, uidb64=None, token=No
doc.build(elements)
# Create the HttpResponse object with the appropriate PDF headers.
- # response['Content-Disposition'] = 'attachment; filename=Workout-{0}-log.pdf'.format(id)
+ response['Content-Disposition'] = 'attachment; filename=Workout-{0}-log.pdf'.format(id)
response['Content-Length'] = len(response.content)
return response
-def workout_view(request, id, uidb64=None, token=None):
+def workout_view(request, id, images=False, comments=False, uidb64=None, token=None):
'''
Generates a PDF with the contents of the workout, without table for logs
'''
- # Create the HttpResponse object with the appropriate PDF headers.
- response = HttpResponse(content_type='application/pdf')
+ '''
+ Generates a PDF with the contents of the given workout
+
+ See also
+ * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
+ * http://www.reportlab.com/apis/reportlab/dev/platypus.html
+ '''
+ comments = bool(int(comments))
+ images = bool(int(images))
# Load the workout
if uidb64 is not None and token is not None:
@@ -127,10 +134,12 @@ def workout_view(request, id, uidb64=None, token=None):
return HttpResponseForbidden()
workout = get_object_or_404(Workout, pk=id, user=request.user)
+ # Create the HttpResponse object with the appropriate PDF headers.
+ response = HttpResponse(content_type='application/pdf')
+
# Create the PDF object, using the response object as its "file."
doc = SimpleDocTemplate(response,
pagesize=A4,
- # pagesize = landscape(A4),
leftMargin=cm,
rightMargin=cm,
topMargin=0.5 * cm,
@@ -142,175 +151,21 @@ def workout_view(request, id, uidb64=None, token=None):
# container for the 'Flowable' objects
elements = []
- # table data, here we will put the workout info
- data = []
-
- # Init several counters and markers, this will be used after the iteration to
- # set different borders and colours
- day_markers = []
- exercise_markers = {}
- group_exercise_marker = {}
- group_day_marker = {}
-
- # Background colour for days
- # Reportlab doesn't use the HTML hexadecimal format, but has a range of
- # 0 till 1, so we have to convert here.
- header_colour = colors.Color(int('73', 16) / 255.0,
- int('8a', 16) / 255.0,
- int('5f', 16) / 255.0)
-
- #
- # Iterate through the Workout
- #
+ # Set the title
+ p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
+ {'description': workout},
+ styleSheet["HeaderBold"])
+ elements.append(p)
+ elements.append(Spacer(10 * cm, 0.5 * cm))
- # Days
+ # Iterate through the Workout and render the training days
for day in workout.canonical_representation['day_list']:
- set_count = 1
- day_markers.append(len(data))
- group_day_marker[day['obj'].id] = {'start': len(data), 'end': len(data)}
-
- if not exercise_markers.get(day['obj'].id):
- exercise_markers[day['obj'].id] = []
-
- p = Paragraph('<para align="center">%(days)s: %(description)s</para>' %
- {'days': day['days_of_week']['text'],
- 'description': day['obj'].description},
- styleSheet["Bold"])
-
- data.append([p])
-
- # Sets
- for set in day['set_list']:
- group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}
-
- # Exercises
- for exercise in set['exercise_list']:
- group_exercise_marker[set['obj'].id]['end'] = len(data)
-
- # Note: '+1' here because there's an emtpy cell between days
- exercise_markers[day['obj'].id].append(len(data) + 1)
-
- # Process the settings
- if exercise['has_weight']:
- setting_out = []
- for i in exercise['setting_text'].split(u'–'):
- setting_out.append(Paragraph(i, styleSheet["Small"], bulletText=''))
- else:
- setting_out = Paragraph(exercise['setting_text'], styleSheet["Small"])
-
- data.append([set_count,
- Paragraph(exercise['obj'].name, styleSheet["Small"]),
- setting_out])
- set_count += 1
-
- data.append([''])
- group_day_marker[day['obj'].id]['end'] = len(data)
-
- # Set the widths and heights of rows and columns
- # Note: 'None' is treated as 'automatic'. Either there is only one value for the whole list
- # or exactly one for every row/column
- colwidths = None
- rowheights = [None] * len(data)
-
- table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),
- ('FONTSIZE', (0, 0), (-1, -1), 8),
- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
-
- # Note: a padding of 3 seems to be the default
- ('LEFTPADDING', (0, 0), (-1, -1), 2),
- ('RIGHTPADDING', (0, 0), (-1, -1), 2),
- ('TOPPADDING', (0, 0), (-1, -1), 3),
- ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ]
-
- # Set specific styles, e.g. background for title cells
- for marker in day_markers:
- # Set background colour for headings
- table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
- table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))
-
- # Make the headings span the whole width
- table_style.append(('SPAN', (0, marker), (-1, marker)))
-
- # Manually set
- rowheights[marker - 1] = 5
-
- # Combine the cells for exercises on the same set
- counter = 1
- for marker in group_exercise_marker:
- counter += 1
- start_marker = group_exercise_marker[marker]['start']
- end_marker = group_exercise_marker[marker]['end']
-
- table_style.append(('SPAN', (0, start_marker), (0, end_marker)))
- table_style.append(('BOX',
- (0, start_marker),
- (-1, end_marker),
- 0.25,
- colors.black))
-
- if counter % 2:
- table_style.append(('BACKGROUND',
- (0, start_marker),
- (-1, end_marker),
- colors.lavender))
-
- for marker in group_day_marker:
- start_marker = group_day_marker[marker]['start']
- end_marker = group_day_marker[marker]['end']
-
- table_style.append(('BOX',
- (0, start_marker),
- (-1, end_marker - 2),
- 1.25,
- colors.black))
-
- # Set the table data
- if data:
- t = Table(data, colwidths, rowheights, style=table_style)
-
- # Manually set the width of the columns
- if len(t._argW) > 1:
- t._argW[0] = 0.6 * cm # Numbering
- t._argW[1] = 10 * cm # Exercise
- t._argW[2] = 2.5 * cm # Repetitions
-
- # There is nothing to output
- else:
- t = Paragraph(_('<i>This is an empty workout, what did you expect on the PDF?</i>'),
- styleSheet["Normal"])
-
- #
- # Add all elements to the document
- #
-
- # Set the title (if available)
- if workout.comment:
- p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
- {'description': workout.comment},
- styleSheet["Bold"])
- elements.append(p)
-
- # Filler
+ elements.append(render_workout_day(day, images=images, comments=comments, only_table=True))
elements.append(Spacer(10 * cm, 0.5 * cm))
- # Append the table
- elements.append(t)
-
# Footer, date and info
elements.append(Spacer(10 * cm, 0.5 * cm))
- created = datetime.date.today().strftime("%d.%m.%Y")
- p = Paragraph('''<para align="left">
- %(date)s -
- <a href="%(url)s">%(url)s</a> -
- %(created)s
- %(version)s
- </para>''' %
- {'date': _("Created on the <b>%s</b>") % created,
- 'created': "wger Workout Manager",
- 'version': get_version(),
- 'url': request.build_absolute_uri(workout.get_absolute_url()), },
- styleSheet["Normal"])
- elements.append(p)
+ elements.append(render_footer(request.build_absolute_uri(workout.get_absolute_url())))
# write the document and send the response to the browser
doc.build(elements)
diff --git a/wger/software/templates/changelog.html b/wger/software/templates/changelog.html
index b4a8126ac..1b717ba6a 100644
--- a/wger/software/templates/changelog.html
+++ b/wger/software/templates/changelog.html
@@ -105,6 +105,7 @@
<a href="https://github.com/rolandgeider/wger/issues/190">#190</a>
<a href="https://github.com/rolandgeider/wger/issues/194">#194</a>
<a href="https://github.com/rolandgeider/wger/issues/185">#185</a>
+ <a href="https://github.com/rolandgeider/wger/issues/182">#182</a>
<a href="https://github.com/rolandgeider/wger/issues/178">#179</a>
<a href="https://github.com/rolandgeider/wger/issues/150">#150</a>
</li>