diff --git a/src/shop/pdf.py b/src/shop/pdf.py index ebad4b6d..32cafc92 100644 --- a/src/shop/pdf.py +++ b/src/shop/pdf.py @@ -3,7 +3,9 @@ from wkhtmltopdf.views import PDFTemplateResponse from PyPDF2 import PdfFileWriter, PdfFileReader from django.test.client import RequestFactory from django.conf import settings -import io, logging +import logging +import io +import os logger = logging.getLogger("bornhack.%s" % __name__) @@ -13,10 +15,10 @@ def generate_pdf_letter(filename, template, formatdict): request.user = AnonymousUser() request.session = {} - ### produce text-only PDF from template + # produce text-only PDF from template pdfgenerator = PDFTemplateResponse( request=request, - template=template, + template=template, context=formatdict, cmd_options={ 'margin-top': 50, @@ -26,33 +28,35 @@ def generate_pdf_letter(filename, template, formatdict): textonlypdf = io.BytesIO() textonlypdf.write(pdfgenerator.rendered_content) - ### create a blank pdf to work with + # create a blank pdf to work with finalpdf = PdfFileWriter() - ### open the text-only pdf + # open the text-only pdf pdfreader = PdfFileReader(textonlypdf) - ### get watermark from watermark file - watermark = PdfFileReader(open("%s/pdf/%s" % (settings.STATICFILES_DIRS[0], settings.PDF_LETTERHEAD_FILENAME), 'rb')) + # get watermark from watermark file + watermark = PdfFileReader( + open(os.path.join(settings.STATICFILES_DIRS[0], 'pdf', settings.PDF_LETTERHEAD_FILENAME), 'rb') + ) - ### add the watermark to all pages + # add the watermark to all pages for pagenum in range(pdfreader.getNumPages()): page = watermark.getPage(0) try: page.mergePage(pdfreader.getPage(pagenum)) except ValueError: - ### watermark pdf might be broken? + # watermark pdf might be broken? return False - ### add page to output + # add page to output finalpdf.addPage(page) - ### save the generated pdf to the archive - fullpath = settings.PDF_ARCHIVE_PATH+filename + # save the generated pdf to the archive + fullpath = os.path.join(settings.PDF_ARCHIVE_PATH, filename) with open(fullpath, 'wb') as fh: finalpdf.write(fh) logger.info('Saved pdf to archive: %s' % fullpath) - ### return a file object with the data + # return a file object with the data returnfile = io.BytesIO() finalpdf.write(returnfile) return returnfile