Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def testCGI(data="Hello <b>World</b>"):
"""
This one shows, how to get the resulting PDF as a
file object and then send it to STDOUT
"""
result = cStringIO.StringIO()
pdf = pisa.CreatePDF(
cStringIO.StringIO(data),
result
)
if pdf.err:
print "Content-Type: text/plain"
print
dumpErrors(pdf)
else:
print "Content-Type: application/octet-stream"
print
sys.stdout.write(result.getvalue())
def testBackgroundAndImage(
src="test-background.html",
dest="test-background.pdf"):
"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""
pdf = pisa.CreatePDF(
file(src, "r"),
file(dest, "wb"),
log_warn = 1,
log_err = 1,
path = os.path.join(os.getcwd(), src)
)
dumpErrors(pdf)
if not pdf.err:
pisa.startViewer(dest)
def edit( self, skel, tpl=None, **kwargs ):
"""
Renders a page for modifying an entry.
The template must construct the html-form itself; the required informations
are passed as skel.structure, skel.value and skel.errors.
An jinja2-macro, wich builds such an form, is shipped with the server.
@param skel: Skeleton of the entry which should be modified
@type skel: Skeleton
@param tpl: Name of an different template, which should be used instead of the default one
@param: tpl: String
"""
htmlRes = super( Render, self).edit( skel, tpl, **kwargs )
result = StringIO.StringIO()
pdf = pisa.CreatePDF( StringIO.StringIO(htmlRes.encode('ascii', 'xmlcharrefreplace')), result )
try:
name = str(skel.name.value)
except:
name = "export"
name = "".join( [ x for x in name.lower() if x in "abcdefghijklmnopqrstuvwxyz1234567890 "] )
request.current.get().response.headers['Content-Disposition'] = "attachment; filename=\"%s.pdf\"" % name
request.current.get().response.headers['Content-Type'] = "application/pdf"
return( result.getvalue() )
# where is_export is being used?
setattr(report, 'is_export', True)
context_dict = {
'report': report,
'column_labels': column_labels,
'report_rows': report_rows,
'report_inlines': report_inlines,
'pagesize': 'legal landscape'
}
template = get_template('model_report/export_pdf.html')
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf_encoding='UTF-8'
pdf = pisa.CreatePDF(StringIO.StringIO(html.encode(pdf_encoding)), result, encoding=pdf_encoding)
if not pdf.err:
response = HttpResponse(result.getvalue(), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % report.slug
else:
response = HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
result.close()
return response
def render_to_pdf_http(request, template_name, renderdict, filename):
"""
Take a string of rendered html and pack it into a pdfand return it thtough http
"""
rendered_html = get_template(template_name).render(renderdict)
response = HttpResponse(content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
success = pisa.CreatePDF(rendered_html, dest=response)
if not success:
return HttpResponseServerError()
return response
def render_to_pdf_storage(template_name, renderdict, filename):
def addItemSuccess (self, key, skel, *args, **kwargs ):
"""
Render an page, informing that the entry has been successfully created.
@param key: Urlsafe key of the new entry
@type key: String
@param skel: Skeleton which contains the data of the new entity
@type skel: Skeleton
"""
htmlRes = super( Render, self).addItemSuccess( key, skel, *args, **kwargs )
result = StringIO.StringIO()
pdf = pisa.CreatePDF( StringIO.StringIO(htmlRes.encode('ascii', 'xmlcharrefreplace')), result )
try:
name = str(skel.name.value)
except:
name = "export"
name = "".join( [ x for x in name.lower() if x in "abcdefghijklmnopqrstuvwxyz1234567890 "] )
request.current.get().response.headers['Content-Disposition'] = "attachment; filename=\"%s.pdf\"" % name
request.current.get().response.headers['Content-Type'] = "application/pdf"
return( result.getvalue() )
request = system['request']
buff = StringIO()
if not 'template' in value and not 'html' in value:
raise SethRendererException(u"No template nor html provided")
if not 'html' in value:
try:
html = self.render_template(value['template'], value, request)
except ValueError:
raise SethRendererException(u"Wrong renderer factory conf")
else:
html = value['html']
try:
pdf = pisa.CreatePDF(
StringIO(html.encode('utf-8')), buff, encoding='utf-8'
)
except AttributeError:
raise SethRendererException(u"Error generating PDF file.")
if pdf.err:
raise SethRendererException(u"Error generating PDF file.")
file_name = value.pop('file_name', self.get_filename(value))
self.prepare_response(request, 'application/pdf', file_name, value)
result = buff.getvalue()
buff.close()
return result
def HTML2PDF(data, filename):
"""
Create a PDF file from html source string.
Returns True is the file creation was successful.
: data: html string
: filename: name of file to be saved
"""
try:
# open output file for writing (truncated binary)
with open(filename, "w+b") as resultFile:
# convert HTML to PDF
pisaStatus = pisa.CreatePDF(data.encode("UTF-8"),
dest=resultFile,
encoding='UTF-8')
return pisaStatus.err
except Exception as ex:
# logging.error("Error creating pdf: " + str(ex))
logging.error("Error creating pdf: " + traceback.format_exc())
return False