use os.path.join to create paths for pdf files

This commit is contained in:
Stephan Telling 2017-04-30 11:28:10 +02:00
parent 61b670931c
commit 16eb7cf594
No known key found for this signature in database
GPG key ID: D4892289F36ADA9B

View file

@ -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,7 +15,7 @@ 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,
@ -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