bornhack-website/src/utils/pdf.py

70 lines
1.9 KiB
Python
Raw Normal View History

import logging
import io
import os
from django.contrib.auth.models import AnonymousUser
2017-01-30 11:16:07 +00:00
from wkhtmltopdf.views import PDFTemplateResponse
from PyPDF2 import PdfFileWriter, PdfFileReader
from django.test.client import RequestFactory
from django.conf import settings
2017-03-23 17:32:13 +00:00
logger = logging.getLogger("bornhack.%s" % __name__)
2017-01-30 11:16:07 +00:00
def generate_pdf_letter(filename, template, formatdict):
# conjure up a fake request for PDFTemplateResponse
request = RequestFactory().get('/')
request.user = AnonymousUser()
request.session = {}
# produce text-only PDF from template
2017-01-30 11:16:07 +00:00
pdfgenerator = PDFTemplateResponse(
request=request,
template=template,
2017-01-30 11:16:07 +00:00
context=formatdict,
cmd_options={
'margin-top': 50,
'margin-bottom': 50,
},
)
textonlypdf = io.BytesIO()
2017-01-30 11:16:07 +00:00
textonlypdf.write(pdfgenerator.rendered_content)
# create a blank pdf to work with
2017-01-30 11:16:07 +00:00
finalpdf = PdfFileWriter()
# open the text-only pdf
2017-01-30 11:16:07 +00:00
pdfreader = PdfFileReader(textonlypdf)
# get watermark from watermark file
watermark = PdfFileReader(
open(
os.path.join(
settings.STATICFILES_DIRS[0],
'pdf',
settings.PDF_LETTERHEAD_FILENAME
),
'rb'
)
)
2017-01-30 11:16:07 +00:00
# add the watermark to all pages
2017-01-30 11:16:07 +00:00
for pagenum in range(pdfreader.getNumPages()):
page = watermark.getPage(0)
try:
page.mergePage(pdfreader.getPage(pagenum))
except ValueError:
# watermark pdf might be broken?
2017-01-30 11:16:07 +00:00
return False
# add page to output
2017-01-30 11:16:07 +00:00
finalpdf.addPage(page)
# save the generated pdf to the archive
fullpath = os.path.join(settings.PDF_ARCHIVE_PATH, filename)
with open(fullpath, 'wb') as fh:
2017-01-30 11:16:07 +00:00
finalpdf.write(fh)
logger.info('Saved pdf to archive: %s' % fullpath)
2017-01-30 11:16:07 +00:00
returnfile = io.BytesIO()
2017-01-30 11:22:43 +00:00
finalpdf.write(returnfile)
2017-01-30 11:16:07 +00:00
return returnfile