• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python weasyprint.HTML类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中weasyprint.HTML的典型用法代码示例。如果您正苦于以下问题:Python HTML类的具体用法?Python HTML怎么用?Python HTML使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HTML类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: md2pdf

def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
           css_file_path=None, base_url=None):
    """
    Convert markdown file to pdf with styles
    """

    # Convert markdown to html
    raw_html = ""
    extras = ["cuddled-lists"]
    if md_file_path:
        raw_html = markdown_path(md_file_path, extras=extras)
    elif md_content:
        raw_html = markdown(md_content, extras=extras)

    if not len(raw_html):
        raise ValidationError('Input markdown seems empty')

    # Weasyprint HTML object
    html = HTML(string=raw_html, base_url=base_url)

    # Get styles
    css = []
    if css_file_path:
        css.append(CSS(filename=css_file_path))

    # Generate PDF
    html.write_pdf(pdf_file_path, stylesheets=css)

    return
开发者ID:krichprollsch,项目名称:md2pdf,代码行数:29,代码来源:core.py


示例2: download_pdf

def download_pdf(story, output='', message=True):
    """ Download a story to pdf.
    :type message: bool
    """
    if output == '':
        output = _get_download_name(story)
    output = _add_extension(output, 'pdf')
    if message:
        print 'Downloading \'%s\' to %s...' % (story.title, output)
    html = ''
    for chapter in story.get_chapters():
        if message:
            print 'Adding %s...' % (chapter.title)
        html += '<h2>Chapter %d: %s</h2>' % (chapter.number, chapter.title)
        html += chapter.raw_text
        html += '</br>' * 10
    if message:
        print 'Compiling PDF...'

    # This turned out not to work on the command line as it needed an X interface.
    #pdfkit.from_string(html, output)
    # Instead trying with weasyprint
    content = unicode(html.strip(codecs.BOM_UTF8), 'utf-8')
    h = HTML(content)
    h.write_pdf(output)
开发者ID:Zenohm,项目名称:fanfiction-api,代码行数:25,代码来源:downloader.py


示例3: export_schedule_to_pdf

def export_schedule_to_pdf(request, callgroup):
	from weasyprint import HTML
	context = get_context(request)

	context['site'] = callgroup.description
	month, year = int(request.GET.get('month', 1)), int(request.GET.get('year', 9999))
	weekstart = int(request.GET.get('weekstart', 0))
	monthstart = datetime.date(year, month, day=1)
	context['month'] = monthstart.strftime("%B %Y")
	monthstart = monthstart - datetime.timedelta(days=monthstart.day - 1)
	# make sure we start on a sunday (or monday if weekstart=1)
	monthstart = monthstart - datetime.timedelta(days=(monthstart.isoweekday() % 7)) + \
		datetime.timedelta(weekstart)
	user = request.session['MHL_Users']['MHLUser']
	context['weeks'] = generateOnCallList(callgroup, monthstart, weekstart, user)
	context['days'] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	for _ in range(weekstart):
		context['days'].append(context['days'].pop(0))
	# load template with context and static root for pdf renderer, generate pdf buffer
	static_root = settings.STATICFILES_DIRS[0]
	html = render_to_string('pdf_schedule.html', {'STATIC_ROOT': static_root}, context)
	weasyhtml = HTML(string=html)
	schedcss = join(static_root, 'css', 'pdf_schedule.css')
	pdf = weasyhtml.write_pdf(stylesheets=[schedcss])  # ,target='/tmp/test.pdf') 
	# prepare response, append &nopdf to GET url for test
	response = HttpResponse(pdf, mimetype="application/pdf")
	response["Cache-Control"] = "no-cache"
	response["Accept-Ranges"] = "none"
	response["Content-Disposition"] = "attachment; filename=schedule-%d-%d.pdf" % (year, month)
	return response if 'nopdf' not in request.GET else \
		render_to_response("pdf_schedule.html", context)
开发者ID:DongHuaLu,项目名称:mdcom,代码行数:31,代码来源:utils.py


示例4: pdf_print

def pdf_print(request, requisition_id):
    """Exports the requisition in PDF."""
    # Selecting the requisition
    requisition = get_object_or_404(models.Requisition, pk=requisition_id)

    rendered = render_to_response('purchase/requisition_report.html', {
        'vessel': Vessel.objects.latest('id'),
        'title': _("Requisition"),
        'user': request.user,
        'requisition': requisition,
        'today': datetime.date.today(),
        },
        context_instance=RequestContext(request))

    # Creating the response
    filename = "pharmaship_requisition_{0}.pdf".format(requisition.reference)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{0}"'.format(filename)

    # Converting it into PDF
    html = HTML(string=rendered.content,
                base_url=request.build_absolute_uri()
                )
    html.write_pdf(response,
                   stylesheets=[
                       CSS(settings.BASE_DIR + '/purchase/static/css/purchase/report.css')
                       ])
    return response
开发者ID:tuxite,项目名称:pharmaship,代码行数:28,代码来源:views.py


示例5: make_book

 def make_book(self, filename, config):
     #QtGui.QMessageBox.critical(None, "Network Error","make_book")
     with tempfile.TemporaryDirectory(prefix="pySpellbook-") as tempdir:
         temphtml = tempfile.NamedTemporaryFile(dir=tempdir, delete=False, suffix=".html", mode="w")
         temphtml.write(self.rendered)
         #QtGui.QMessageBox.critical(None, "Network Error","wrote html")
         tmpname = temphtml.name
         temphtml.close()
         #QtGui.QMessageBox.critical(None, "Network Error",tmpname)
         #os.mkdir(os.path.join(tempdir, "resources"))
         #for r in self.resourcelist:
         #    shutil.copy(r, os.path.join(tempdir,"resources"))
         if config['backend'] == 'prince':
             os.system("\"%s\" %s -o %s" % (config['prince_path'], tmpname, filename))
         elif config['backend'] == 'HTML':
             shutil.copy(os.path.join(tempdir, tmpname), filename)
             webbrowser.open_new_tab("file:///%s" % filename)
         elif config['backend'] == 'custom':
             custom_command = config['custom'].replace("$INPUT", temphtml).replace("$OUTPUT", filename)
             shutil.copy(custom_command)
         else:
             if weasy:
                 html = HTML("file://%s" % tmpname)
                 html.write_pdf(target=filename)
             else:
                 import pySpellbook.qtpdf
                 os.chdir(tempdir)
                 printer = pySpellbook.qtpdf.Printer(self.parent)
                 printer.load(tmpname)
                 printer.print(filename)
开发者ID:christofsteel,项目名称:pySpellbook,代码行数:30,代码来源:template.py


示例6: savePDF

   def savePDF(self, pdf_filename, parent_soup, target_node, yes_phrase, url, key, school_name):
       if target_node:
          grandparent_node = target_node.parent.parent
          tag = self.highlightedNode(target_node, yes_phrase, parent_soup)
          self.replaceNode(target_node, tag)
          body = Tag(parent_soup,"body")
          body.append(grandparent_node)
       else:
          body = parent_soup
       try:
          weasyprint = HTML(string=body.prettify())
          tmp_filename = 'pdfs/tmp.pdf'
          weasyprint.write_pdf(tmp_filename,stylesheets=[CSS(string='body { font-size: 10px; font-family: serif !important }')])
       except:
          print "weasyprint failed on url: "+url
          if target_node:
             self.replaceNode(tag, target_node) #return to old state
          return

       if target_node:
          self.replaceNode(tag, target_node) #return to old state

       sep_filename = "pdfs/sep.pdf"
       self.makeSepPage(sep_filename, url, key, school_name)

       merger = PdfFileMerger()
       if (os.path.exists(pdf_filename)):
           merger.append(PdfFileReader(file(pdf_filename, 'rb')))
       merger.append(PdfFileReader(file(sep_filename, 'rb')))
       merger.append(PdfFileReader(file(tmp_filename, 'rb')))
       merger.write(pdf_filename)
开发者ID:schasins,项目名称:school-program-scraping,代码行数:31,代码来源:sfusd_demo.py


示例7: print_certidao

    def print_certidao(self, request, diligencias):
        """
        :param diligencias:
        :return:
        """
        from weasyprint import HTML, CSS
        from django.conf import settings
        from app.models import Diligencia
        from django.utils import datetime_safe


        modelo_html = ''
        for i in range(len(diligencias)):
            if i == 0:                                          #primeira certidão # '<meta charset="utf-8" />'
                modelo_html += '<html>' \
                               '<head>' \
                               '<meta charset="utf-8" />' \
                               '<base href="http://ofjusapp.pythonanywhere.com/">'\
                               '</head>' \
                               '<body>' \
                               '<div style="float: none;">' \
                               '<div>'
                modelo_html += diligencias[i].documento
                modelo_html += '</div>'
            else:                                               #certidões intermediarias
                modelo_html += '<div style="page-break-before:always;">'
                modelo_html += diligencias[i].documento
                modelo_html += '</div>'
        modelo_html += '</div></body></html>'
        pdf_html = HTML(string=modelo_html)
        main_doc = pdf_html.render()
        pdf_file = main_doc.write_pdf()
        diligencias.update(imprimir=False)
        #pdf_file = HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')
        return pdf_file  # returns the response.
开发者ID:dududrauto,项目名称:my-first-blog,代码行数:35,代码来源:printing.py


示例8: render_pdf

 def render_pdf(self):
     total = self.doc['total']
     if self.home_country:
         invoice_country_iso = self.doc['address']['country_iso_alpha2']
         if invoice_country_iso and invoice_country_iso != self.home_country:  # no tax in bill
             total = self.doc['amount']
             self.doc['total'] = total
     tpl = self.jinja_env.get_template('invoice_tpl.html')
     self.invoice_fname = "{date}_CHF{total:.2f}_Nr{nr}_hosting-{name}_ta".format(
         date=self.doc['date'].strftime("%Y-%m-%d"),
         total=total,
         nr=self.doc['nr'],
         name=self.client_name_normalized()
     )
     for file_format in ['html', 'pdf']:
         path = "%s/%s" % (self.output_dir, file_format)
         if not os.path.exists(path):
             os.mkdir(path)
     with codecs.open(
         '%s/html/%s.html' % (self.output_dir, self.invoice_fname),
         'w+', encoding="utf-8"
     ) as invoice_html:
         invoice_html.write(tpl.render(**self.doc))
         invoice_html.seek(0)
         base_url = "%s/html" % self.invoice_template_dir
         html = HTML(invoice_html, base_url=base_url)
         html.write_pdf('%s/pdf/%s.pdf' % (self.output_dir, self.invoice_fname))
开发者ID:yvess,项目名称:desk,代码行数:27,代码来源:invoice.py


示例9: render

 def render(test_id):
     document = HTML(safe_join(suite_directory, test_id + ".htm"), encoding="utf8").render(
         stylesheets=[default_stylesheet], enable_hinting=True
     )
     pages = [
         "data:image/png;base64," + document.copy([page]).write_png().encode("base64").replace("\n", "")
         for page in document.pages
     ]
     return render_template("render.html", **locals())
开发者ID:liujuncn,项目名称:WeasyPrint,代码行数:9,代码来源:web.py


示例10: render

 def render(test_id):
     document = HTML(
         safe_join(suite_directory, test_id + '.htm'),
         encoding='utf8',
     ).render(stylesheets=[default_stylesheet], enable_hinting=True)
     pages = [
         'data:image/png;base64,' + document.copy([page]).write_png(
             )[0].encode('base64').replace('\n', '')
         for page in document.pages]
     return render_template('render.html', **locals())
开发者ID:isleei,项目名称:WeasyPrint,代码行数:10,代码来源:web.py


示例11: generate

def generate():
    name = request.args.get('filename', 'unnamed.pdf')
    app.logger.info('POST  /pdf?filename=%s' % name)
    html = HTML(string=request.data)
    pdf = html.write_pdf()
    response = make_response(pdf)
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] = 'inline;filename=%s' % name
    app.logger.info(' ==> POST  /pdf?filename=%s  ok' % name)
    return response
开发者ID:aquavitae,项目名称:docker-weasyprint,代码行数:10,代码来源:wsgi.py


示例12: make_pdf

def make_pdf(config, data):
    """
    Generate PDF file out of generated 'index.html' page.
    """
    from weasyprint import HTML
    output_dir = config.get('output_dir', 'build')
    output_file = os.path.join(output_dir, config.get('pdf_file', 'resume.pdf'))
    input_file = os.path.join(output_dir, 'index.html')
    theme_location = os.path.join('themes', config['theme'])
    html = HTML(input_file, base_url=theme_location)
    html.write_pdf(output_file)
开发者ID:bretuobay,项目名称:fileutils,代码行数:11,代码来源:build.py


示例13: get_data

 def get_data():
     if 'wsgi.input' in environ and request_body_size:
         request = environ['wsgi.input'].read(request_body_size)
         content = parse_qs(request.decode('utf-8'))['content'][0]
     else:
         content = DEFAULT_CONTENT
     html = HTML(string=content)
     png = BytesIO()
     html.write_png(png)
     png.seek(0)
     return content, b64encode(png.read()).decode('ascii')
开发者ID:prepare,项目名称:WeasyPrint,代码行数:11,代码来源:renderer.py


示例14: generate_pdf

 def generate_pdf(self):
     ''' renders html from file with given context and creates pdf file from it
     '''
     html_string = Template(self.template.template.read()).render(Context(json.loads(self.content)))
     html = HTML(string=html_string, base_url='')
     filename = self.name.replace('/', '.') + '.pdf'
     buffer = BytesIO()
     html.write_pdf(target=buffer)
     pdf = buffer.getvalue()
     buffer.close()
     self.file.save(filename, ContentFile(pdf))
开发者ID:robsontpm,项目名称:templado,代码行数:11,代码来源:models.py


示例15: print_order

def print_order(orders, name, phone):
    template = env.get_template('template.md')

    total = sum(order.price for order in orders)
    md = template.render(name=name, phone=phone, orders=orders, total=total)
    html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
    document = HTML(string=html)

    tmp = tempfile.NamedTemporaryFile(mode='wb', suffix='.pdf')
    document.write_pdf(tmp, stylesheets=[CSS(filename='order-style.css')])

    return tmp
开发者ID:MaxNoe,项目名称:pizza,代码行数:12,代码来源:genorder.py


示例16: render_to_pdf

def render_to_pdf(template_name, pdf_filename=None, template_values=None, css_sheets=None):
    context_extras = {'LANGUAGES': settings.LANGUAGES, 'LANGUAGE_CODE': translation.get_language(),
                      'LANGUAGE_BIDI': translation.get_language_bidi()}
    template_values.update(context_extras)
    html_content = render_to_string(template_name, template_values or {})
    css_objs = [CSS(filename=finders.find(x)) for x in css_sheets] if css_sheets else []
    html_obj = HTML(string=html_content)
    if pdf_filename is None:
        with tempfile.NamedTemporaryFile() as n:
            pdf_filename = n.name

    html_obj.write_pdf(pdf_filename, stylesheets=css_objs)
    return pdf_filename
开发者ID:d9pouces,项目名称:pIGI1300,代码行数:13,代码来源:utils.py


示例17: __call__

    def __call__(self, REQUEST, RESPONSE):
        content = super(ExportaMinutaPDFView, self).__call__(self)
        portal_url = api.portal.get().absolute_url()
        base_url = '{0}/++resource++smdu.participacao/'.format(portal_url)
        html = HTML(string=content, base_url=base_url)
        stylesheets = []
        with open('src/smdu/participacao/browser/static/css/print.css', 'r') as css:
            stylesheets.append(CSS(string=css.read()))
        minuta_exportada_pdf = html.write_pdf(stylesheets=stylesheets)

        RESPONSE.setHeader('Content-Type', 'application/pdf; charset=utf-8')
        RESPONSE.setHeader('Content-Length', len(minuta_exportada_pdf))
        RESPONSE.setHeader('Content-Disposition', 'attachment; filename="Relatorio.pdf"')
        return minuta_exportada_pdf
开发者ID:CGTIC,项目名称:smdu.participacao,代码行数:14,代码来源:views.py


示例18: save

    def save(self):
        # PDF report is a list of all documents
        self.summary = '<h1>%s</h1>' % (self.locale['STR_SUMMARY'])

        # To make one PDF report, we have to get all pages of all documents...
        # First step , we obtain a list of sublists like this :
        # [
        #     [doc1.page1, doc1, page2],
        #     [doc2.page1, doc2.page2],
        #     [doc3.page1, doc3.page2, doc3.page3]
        # ]

        # Rendering content
        content = HTML(string=self.content, encoding="utf-8").render(stylesheets=[self.content_css])

        #Priting summary table BEGIN
        self.summary += '<table style="border:0">'

        def _printSummary(bookmarks, indent=0, numer=''):
            for i, (label, (page, _, _), children) in enumerate(bookmarks, 1):
                tr_style = 'style="border-top:1px solid #CCC;border-bottom:1px solid #CCC"'
                title_td_style = 'style="border:0;text-align:left;width:550px;padding:10px;"'
                page_num_td_style = 'style="border:0;width:50px"'
                if indent == 0 and i == 1:
                    tr_style = 'style="border-bottom:1px solid #CCC"'
                self.summary += ('<tr %s><td %s>%s%s. %s</td><td %s>%d</td></tr>' % (
                    tr_style, title_td_style, '&nbsp;' * indent, numer + str(i), label.lstrip('0123456789. '), page_num_td_style, page + 1))
                _printSummary(children, indent + 2, numer + str(i) + '.')
        _printSummary(content.make_bookmark_tree())

        #Priting summary table END
        self.summary += '</table>'

        homepage = HTML(string=self.homepage, encoding="utf-8").render(stylesheets=[self.homepage_css])
        summary = HTML(string=self.summary, encoding="utf-8").render(stylesheets=[self.homepage_css])

        pdf_report = [homepage, summary, content]
        logging.getLogger().warning(pdf_report[2].make_bookmark_tree())

        all_pages = [doc.pages for doc in pdf_report]

        # Second step, clean sublist and make a simple list
        # http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
        all_pages = [item for sublist in all_pages for item in sublist]

        # ...And combine these pages into a single report Document
        pdf_report[0].copy(all_pages).write_pdf(self.path)

        chmod(self.path, 0644)
        return self.path
开发者ID:pavelpromin,项目名称:mmc,代码行数:50,代码来源:output.py


示例19: render

def render():
    html = request.args['html']
    assert html.strip()

    if html:
        assert 'fuu' not in html
        # Save the input HTML
        with open(INPUT, 'w') as fd:
            fd.write(html.encode('utf-8'))

    html = HTML(INPUT, encoding='utf8')
    html.write_pdf(PDF_OUTPUT)
    html.write_png(PNG_OUTPUT)

    return send_file(PNG_OUTPUT, cache_timeout=0)
开发者ID:PierreBizouard,项目名称:WeasyPrint,代码行数:15,代码来源:run.py


示例20: execute

    def execute(self, id_user, id_meeting):
        render = RenderHtml(id_user, id_meeting, self.__dirToProject)
        value = render.split_question_on_pages()
        with codecs.open(self.__dir, 'w', 'utf8') as f2:
            f2.write(value)

        pdf = HTML(self.__dir)
        newName = str(id_user) + str(id_meeting) + self.__file_name
        pdf.write_pdf(self.__result_dir + newName)

        res = []
        res.append(newName)
        res.append(self.__result_dir)

        return res
开发者ID:markpolyak,项目名称:onlinemkd,代码行数:15,代码来源:PdfGen.py



注:本文中的weasyprint.HTML类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python weather.Weather类代码示例发布时间:2022-05-26
下一篇:
Python db_utils.create_user函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap