本文整理汇总了Python中weasyprint.HTML属性的典型用法代码示例。如果您正苦于以下问题:Python weasyprint.HTML属性的具体用法?Python weasyprint.HTML怎么用?Python weasyprint.HTML使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类weasyprint
的用法示例。
在下文中一共展示了weasyprint.HTML属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serve_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def serve_pdf(self, request):
# Render html content through html template with context
template = get_template(settings.PDF_TEMPLATE)
context = {
'invoice': self,
}
html = template.render(context)
# Write PDF to file
document_html = HTML(string=html, base_url=request.build_absolute_uri())
document = document_html.render()
if len(document.pages) > 1:
for page in document.pages[1:]:
str(page)
pdf = document.write_pdf()
else:
pdf = document.write_pdf()
#response = HttpResponse(html)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'filename="Invoice {0} | Invoice {0}.pdf"'.format(self.id)
return response
示例2: run
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def run(self, params={}):
text = params.get('text')
html_template = """
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title></head>
<body><pre>{}</pre></body>
</html>"""
# Wrap text preserving existing newlines
text = '\n'.join(
wrapped for line in text.splitlines() for wrapped in wrap(
line, width=70, expand_tabs=False,
replace_whitespace=False, drop_whitespace=False
)
)
text = escape(text)
html_content = html_template.format(text)
pdf_content = HTML(string=html_content).write_pdf()
b64_content = b64encode(pdf_content).decode()
return {'pdf': b64_content}
示例3: render_doc
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def render_doc(self, content: str, base_url: str, rel_url: str = None):
soup = BeautifulSoup(content, 'html.parser')
self.inject_pgnum(soup)
stylesheet = self.theme.get_stylesheet()
if stylesheet:
style_tag = soup.new_tag('style')
style_tag.string = stylesheet
soup.head.append(style_tag)
if self.combined:
soup = prep_combined(soup, base_url, rel_url)
else:
soup = prep_separate(soup, base_url)
html = HTML(string=str(soup))
return html.render()
示例4: generate_report
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def generate_report(path, theme=None, intype='md'):
"""
This function generates a "report.pdf" from a "report.[md|html]" template using weasyprint.
:param path: path of report.[md|html]
:param theme: full or relative (to "[path]/themes/") path to the CSS theme
:param intype: input format
"""
assert intype in ['html', 'md']
if intype == 'md':
input_file = codecs.open(join(path, 'report.md'), mode="r", encoding="utf-8")
text = input_file.read()
html = markdown(text)
else:
html = open(join(path, 'report.html')).read()
html = HTML(string=html, base_url='file://{}/'.format(abspath(path)))
output = join(path, 'report.pdf')
kwargs = {}
if theme is not None:
theme = join(path, "themes", theme)
if exists(theme):
kwargs['stylesheets'] = [theme]
html.write_pdf(output, **kwargs)
示例5: __init__
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def __init__(self, url, landscape=False):
self.operation = Gtk.PrintOperation()
document = HTML(string=url).render()
self.operation.connect('begin-print', self.begin_print, document)
self.operation.connect('draw-page', self.draw_page, document)
self.operation.set_use_full_page(False)
self.operation.set_unit(Gtk.Unit.POINTS)
self.operation.set_embed_page_setup(True)
if landscape == True:
pageSetup = Gtk.PageSetup()
pageSetup.set_orientation(Gtk.PageOrientation.LANDSCAPE)
self.operation.set_default_page_setup(pageSetup)
settings = Gtk.PrintSettings()
directory = GLib.get_user_special_dir(
GLib.UserDirectory.DIRECTORY_DOCUMENTS) or GLib.get_home_dir()
ext = settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) or 'pdf'
uri = 'file://%s/weasyprint.%s' % (directory, ext)
settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri)
self.operation.set_print_settings(settings)
示例6: render_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def render_pdf(self, input_data, input_data_type, stylesheet):
'''
convert html data to pdf
:param input_data: url to read html or html already
:param input_data_type: artifact data type. most important when data type is url or uri
:param stylesheet: used to apply stylesheets for the pdf document. Most useful when showing
landscape data or font family changes
:return: binary pdf data
'''
if input_data_type and (input_data_type.lower().startswith("url") or input_data_type.lower().startswith("uri")):
html = weasyprint.HTML(url=input_data)
else:
html = weasyprint.HTML(string=input_data)
if stylesheet:
css = [weasyprint.CSS(string=stylesheet)]
else:
css = None
return html.write_pdf(None, css)
示例7: admin_order_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def admin_order_pdf(request, order_id):
order = get_object_or_404(Order, id=order_id)
html = render_to_string('orders/order/pdf.html',
{'order': order})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = f'filename=order_{order.id}.pdf'
weasyprint.HTML(string=html).write_pdf(response,
stylesheets=[weasyprint.CSS(
settings.STATIC_ROOT + 'css/pdf.css')])
return response
示例8: makeReport
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def makeReport(name, links, preds, instnames):
#sort
links = sorted(links)
preds = sorted(preds)
instnames = sorted(instnames)
name = name.strip()
name = name.replace('%20', '-')
with open('./report/template.html', 'r') as f:
template_data = f.read()
template_data = template_data.replace('{{INPUT_NAME}}', name)
links_str = ""
for l in links:
links_str += "<li>"
links_str += '<a href="{0}">{0}</a>'.format(l)
links_str += "</li>"
template_data = template_data.replace('{{SOCIAL_URLS}}', links_str)
preds_str = ""
for p in preds:
preds_str += "<li>"
preds_str += p
preds_str += "</li>"
template_data = template_data.replace('{{GOOGLE_PREDS}}', preds_str)
insta_str = ""
for i in instnames:
insta_str += "<li>"
insta_str += '<a href="https://www.instagram.com/{0}">https://instagram.com/{0}</a>'.format(i)
insta_str += "</li>"
template_data = template_data.replace('{{INSTA_PROFILES}}', insta_str)
with open('tmp.html', 'w') as t:
t.write(template_data)
doc = HTML('tmp.html')
doc.write_pdf('{0}_Report.pdf'.format(name))
os.remove('tmp.html')
示例9: payment_completed
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def payment_completed(order_id):
"""
Task to send an e-mail notification when an order is
successfully created.
"""
order = Order.objects.get(id=order_id)
# create invoice e-mail
subject = f'My Shop - EE Invoice no. {order.id}'
message = 'Please, find attached the invoice for your recent purchase.'
email = EmailMessage(subject,
message,
'admin@myshop.com',
[order.email])
# generate PDF
html = render_to_string('orders/order/pdf.html', {'order': order})
out = BytesIO()
stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
weasyprint.HTML(string=html).write_pdf(out,
stylesheets=stylesheets)
# attach PDF file
email.attach(f'order_{order.id}.pdf',
out.getvalue(),
'application/pdf')
# send e-mail
email.send()
示例10: generate_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def generate_pdf(prefix, data):
template = get_template(BATCH_PDF_TEMPLATE)
html = HTML(string=template.render(data))
f = open("{}/{}.pdf".format(settings.MEDIA_ROOT, prefix), "w+b")
html.write_pdf(target=f)
f.seek(0)
return File(f)
示例11: clean_html_tags
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def clean_html_tags(html):
"""
Simple regex HTML tag cleaner.
"""
return re.sub(r'<.+?>', '', html)
示例12: download_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def download_pdf(data: pd.DataFrame, file_name='output'):
data_html = data.to_html(index=False)
try:
data_pdf = pdf.from_string(data_html, False)
except OSError:
env = Environment(loader=FileSystemLoader(settings.PROJECT_DIR('templates')))
template = env.get_template('pdf_export.html')
template_vars = {"title": file_name.capitalize(),
"table": data_html}
data_pdf = HTML(string=template.render(template_vars)).write_pdf()
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}.{}"'.format(file_name, 'pdf')
response.write(data_pdf)
return response
示例13: admin_order_pdf
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def admin_order_pdf(request, order_id):
order = get_object_or_404(Order, id=order_id)
html = render_to_string('orders/order/pdf.html',
{'order': order})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id)
weasyprint.HTML(string=html).write_pdf(response,
stylesheets=[weasyprint.CSS(
settings.STATIC_ROOT + 'css/pdf.css')])
return response
示例14: generate_PDF
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def generate_PDF():
rotor = ross.rotor_example()
TEMPLATE = 'report.html'
CSS = 'report.css'
OUTPUT_FILENAME = 'my-report.pdf'
ROOT = Path(os.path.dirname(ross.__file__))/'API_Report'
ASSETS_DIR = ROOT/'assets'
TEMPLAT_SRC = ROOT/'templates'
CSS_SRC = ROOT/ 'static/css'
OUTPUT_DIR = ROOT/'output'
env = Environment(loader=FileSystemLoader(str(TEMPLAT_SRC)))
template = env.get_template(TEMPLATE)
css = str(CSS_SRC/ CSS)
bokeh_fig = rotor.plot_rotor()
bokeh_fig.plot_width=500
bokeh_fig.plot_height=400
bokeh_fig.output_backend = 'svg'
bokeh.io.export_svgs(bokeh_fig,filename = Path(ASSETS_DIR)/'plot.svg')
template_vars = {'ASSETS_DIR':ASSETS_DIR,'ROTOR_NAME':'CENTRIFUGAL COMPRESSOR','ROTOR_ID':'0123456789'}
rendered_string = template.render(template_vars)
html = weasyprint.HTML(string=rendered_string)
report = os.path.join(OUTPUT_DIR, OUTPUT_FILENAME)
html.write_pdf(report, stylesheets=[css])
print(f'Report generated in {OUTPUT_DIR}')
示例15: showPreview
# 需要导入模块: import weasyprint [as 别名]
# 或者: from weasyprint import HTML [as 别名]
def showPreview(self, html, landscape=False):
HTML(string=html, base_url=__file__).write_pdf('report.pdf')
if sys.platform == 'linux':
subprocess.call(["xdg-open", 'report.pdf'])
else:
os.startfile('report.pdf')
time.sleep(3)
os.remove('report.pdf')