Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def render_pdf(self):
# Only import weasyprint when required as production
# environment does not have it installed.
from weasyprint import HTML, CSS
# Create HTML
context = dict()
context["chapters"] = Chapter.objects.all()
filename = "CSFG PDF (test)"
context["filename"] = filename
pdf_html = render_to_string("pdf/base.html", context)
html = HTML(
string=pdf_html,
base_url=settings.BUILD_ROOT,
url_fetcher=self.django_url_fetcher,
)
# Get CSS
css_file = finders.find("css/website.css")
css_string = open(css_file, encoding="UTF-8").read()
base_css = CSS(string=css_string)
# Create PDF
return (html.write_pdf(stylesheets=[base_css]), filename)
def bind(self):
logger.debug('Binding %s.pdf', self.file_name)
pdf_path = os.path.join(self.app.output_path, 'pdf')
os.makedirs(pdf_path, exist_ok=True)
all_pages = []
bar = IncrementalBar('Adding chapters to PDF', max=len(self.chapters))
bar.start()
if os.getenv('debug_mode') == 'yes':
bar.next = lambda: None # Hide in debug mode
# end if
try:
html = HTML(string=self.create_intro())
all_pages += html.render().pages
logger.info('Added intro page')
for chapter in self.chapters:
html_string = chapter['body']
html = HTML(string=html_string)
all_pages += html.render().pages
logger.info('Added chapter %d', chapter['id'])
bar.next()
# end for
finally:
bar.clearln()
# bar.finish()
# end try
html = HTML(string=self.make_metadata())
strings, the values are the translations used in the output).
:param locale: None or locale identifier, e.g. 'de_DE' or 'en_US';
The locale used for formatting numeric and date values with
babel. If None (default), the locale will be taken from the
`LC_NUMERIC` or `LC_TIME` environment variables on your
system, for numeric or date values, respectively.
"""
html = self.get_extended_report_html(
year=year,
date_precision=date_precision, combine=combine,
convert_timezone=convert_timezone,
font_size=font_size, template_file=template_file,
payment_kind_translation=payment_kind_translation,
locale=locale)
doc = weasyprint.HTML(string=html)
doc.write_pdf(file_name)
log.info("Saved detailed capital gains report %sto %s",
'for year %i ' % year if year else '',
str(file_name))
content to serve as the header/footer (rather than passing it within the
main HTML).
"""
if processor == XHTML2PDF:
memfile = io.BytesIO()
xhtml2pdf.document.pisaDocument(html, memfile)
# ... returns a document, but we don't use it, so we don't store it to
# stop pychecker complaining
# http://xhtml2pdf.appspot.com/static/pisa-en.html
memfile.seek(0)
return buffer(memfile.read())
# http://stackoverflow.com/questions/3310584
elif processor == WEASYPRINT:
# http://ampad.de/blog/generating-pdfs-django/
return weasyprint.HTML(string=html).write_pdf()
elif processor == PDFKIT:
if _wkhtmltopdf_filename is None:
config = None
else:
# config = pdfkit.configuration(wkhtmltopdf=_wkhtmltopdf_filename)
# Curiously, while pdfkit.configuration just copies the
# wkhtmltopdf parameter to self.wkhtmltopdf, the next stage, in
# pdfkit.pdfkit.PDFKit.__init__, uses
# self.wkhtmltopdf = \
# self.configuration.wkhtmltopdf.decode('utf-8'),
# which then fails with
# AttributeError: 'str' object has no attribute 'decode'.
# So, it seems, we must pre-encode it...
config = pdfkit.configuration(
wkhtmltopdf=_wkhtmltopdf_filename.encode('utf-8'))
def pdfify(enhanced):
enhanced["scan"]["time"] = fromEpoch(enhanced["scan"]["time"])
enhanced["enhanced"]["time"] = fromEpoch(enhanced["enhanced"]["time"])
for system in enhanced["systems"]:
for service in system["services"]:
service["banner"]=product(service["banner"])
for cpe in system["cpes"]:
cpe["cpe"] = toHuman(cpe["cpe"])
html_out = template.render(enhanced)
HTML(string=html_out).write_pdf("report.pdf",
stylesheets=stylesheets)
localFile.write(u.read())
localFile.close()
cleanup.append(_cssfile)
else:
_cssfile = css
cssfile = open(_cssfile, 'r')
css_def = cssfile.read()
htmlreport = to_utf8(htmlreport)
for (key, val) in images.items():
htmlreport = htmlreport.replace(key, val)
# render
htmlreport = to_utf8(htmlreport)
renderer = HTML(string=htmlreport, url_fetcher=senaite_url_fetcher, encoding='utf-8')
pdf_fn = outfile if outfile else tempfile.mktemp(suffix=".pdf")
if css:
renderer.write_pdf(pdf_fn, stylesheets=[CSS(string=css_def)])
else:
renderer.write_pdf(pdf_fn)
# return file data
pdf_data = open(pdf_fn, "rb").read()
if outfile is None:
os.remove(pdf_fn)
for fn in cleanup:
os.remove(fn)
return pdf_data
html_file_name = tmp_dir + "output.html"
# Interpret JS code
if not args.basic:
driver.get("file:///" + html_file_name)
sleep(2)
elem = driver.find_element_by_xpath("//*")
interpreted_html = elem.get_attribute("outerHTML")
with open(html_file_name, "w") as html_out_file:
html_out_file.write(interpreted_html)
# Create final PDF file
pdf = HTML(html_file_name).write_pdf()
f = open("output.pdf",'wb')
f.write(pdf)
if not args.quiet:
stdout.write("\rDone. ")
stdout.flush()
def _create_pdf(rendered_template, absolute_url):
from weasyprint import HTML
pdf_file = HTML(string=rendered_template, base_url=absolute_url).write_pdf()
return pdf_file
def render_to_response(self, context, **response_kwargs):
numbering = self.request.GET.get('q', '')
response = super(WorksheetPrintView, self).render_to_response(
context, **response_kwargs)
response.render()
# return response
pdf_response = HttpResponse(content_type='application/pdf')
pdf_response['Content-Disposition'] = \
'filename={}. {}'.format(numbering, context['file_title'])
# Need to improve for URL outside of the dev env.
html_object = HTML(
string=response.content,
base_url='file://',
)
html_object.write_pdf(pdf_response)
return pdf_response