add pdf code and pdf letterheads

This commit is contained in:
Thomas Steen Rasmussen 2016-05-16 20:54:34 +02:00
parent 029ca1cf00
commit 1abbf3acc6
6 changed files with 47 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View file

@ -3,3 +3,5 @@ django-allauth>=0.23.0
django-bootstrap3>=7.0.0
django-environ>=0.4.0
psycopg2>=2.6.1
PyPDF2>=1.25.1
django-wkhtmltopdf>=3.0.0

45
shop/pdf.py Normal file
View file

@ -0,0 +1,45 @@
from wkhtmltopdf.views import PDFTemplateResponse
from PyPDF2 import PdfFileWriter, PdfFileReader
from django.test.client import RequestFactory
from django.conf import settings
import StringIO
def generate_pdf_letter(template, formatdict):
### produce text-only PDF from template
pdfgenerator = PDFTemplateResponse(
request=RequestFactory().get('/'),
template=template,
context=formatdict,
cmd_options={
'margin-top': 40,
'margin-bottom': 50,
},
)
textonlypdf = StringIO.StringIO()
textonlypdf.write(pdfgenerator.rendered_content)
### create a blank pdf to work with
finalpdf = PdfFileWriter()
### open the text-only pdf
pdfreader = PdfFileReader(textonlypdf)
### get watermark from watermark file
watermark = PdfFileReader(open(settings.LETTERHEAD_PDF_PATH, 'rb'))
### add the watermark to all pages
for pagenum in xrange(pdfreader.getNumPages()):
page = pdfreader.getPage(pagenum)
try:
page.mergePage(watermark.getPage(0))
except ValueError:
### watermark pdf might be broken?
return False
### add page to output
finalpdf.addPage(page)
### return a file object with the data
returnfile = StringIO.StringIO()
finalpdf.write(returnfile)
return returnfile