Ejemplo n.º 1
0
 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))
Ejemplo n.º 2
0
def html_to_pdf_view(request):
    ''' converte html para pdf --> html.write_pdf(target='/tmp/mypdf.pdf')    fs = FileSystemStorage('/tmp') '''

    try:
        itens = ItemOrcamento.objects.all
        valor_total = list(
            ItemOrcamento.objects.aggregate(Sum('valor')).values())[0]

        if valor_total != None:
            status = None
        else:
            status = 'disabled'

        context = {
            'itens': itens,
            'valor_total': valor_total,
            'status': status
        }

        html_string = render_to_string('core/orcamento_template.html', context)
        html = HTML(string=html_string)

        with tempfile.TemporaryDirectory() as tmpdirname:
            target_final = '/' + tmpdirname + '/mypdf.pdf'
            html.write_pdf(target=target_final)

            fs = FileSystemStorage(tmpdirname)
            with fs.open('mypdf.pdf') as pdf:
                response = HttpResponse(pdf, content_type='application/pdf')
                response[
                    'Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
            return response

    except Exception as e:
        print(e)
Ejemplo n.º 3
0
def export_pdf(pdf_filename, html_string, css_string):
    font_config = FontConfiguration()
    html = HTML(string=html_string)
    css = CSS(string=css_string, font_config=font_config)
    html.write_pdf(target=pdf_filename,
                   stylesheets=[css],
                   font_config=font_config)
Ejemplo n.º 4
0
def build_summary(outputfile, template_file, db, night=None, stylesheets=None):

    if night is None:
        night = (datetime.today() - timedelta(days=2)).strftime('%Y%m%d')

    template = load_template(template_file)

    runs = read_run(night, db)
    qla_data = get_qla_data(night, db)

    os.makedirs('build', exist_ok=True)

    plot_run_timeline(runs, 'build/runs.svg')
    plot_qla(qla_data, 'build/qla.svg')

    md = template.render(
        night=night,
        run_plot='build/runs.svg',
        qla_plot='build/qla.svg',
    )

    html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
    document = HTML(string=html, base_url='.')

    outputfile = outputfile or 'fact_summary_{}.pdf'.format(night)
    document.write_pdf(outputfile, stylesheets=stylesheets)
Ejemplo n.º 5
0
    def get(self, request, pk, format='json'):
        try:
            todolist = TODOList.objects.get(owner=request.user.id, id=pk)
        except (TypeError, ValueError, OverflowError, TODOList.DoesNotExist):
            return Response('', status.HTTP_403_FORBIDDEN)

        paragraphs = []

        for task in todolist.task_set.all().order_by('deadline'):
            paragraphs.append(
                f'{task.title}, done: {task.done}, deadline: {task.deadline}')

        html_string = render_to_string('todo_list_report.html',
                                       {'paragraphs': paragraphs})

        html = HTML(string=html_string)
        html.write_pdf(target=f'/tmp/{todolist.title}.pdf')

        fs = FileSystemStorage('/tmp')
        with fs.open(f'{todolist.title}.pdf') as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename="{todolist.title}-{str(datetime.now())}.pdf"'
            return response

        return response
Ejemplo n.º 6
0
def relatorio_padrao_grupo(request, pk):
    if pk is 12 and not request.user.has_perm('rol.add_ata'):
        return HttpResponse('GRUPO RESTRITO AO CONSELHO')
    else:
        grupo = TipoGrupo.objects.get(pk=pk)
        if request.user.has_perm('rol.add_ata'):
            turmas = TurmaFrequencia.objects.filter(tipo_grupo_id=pk)
        else:
            turmas = TurmaFrequencia.objects.filter(tipo_grupo_id=pk).filter(
                restrito=False)
        turmas_grupo = []
        for turma in turmas:
            turma.lista_participantes = turma.participantes.all()
            turma.lista_lideranca = turma.lideranca.all()
            turmas_grupo.append(turma)

        tipo = "grupo" + str(pk)

        html_string = render_to_string(
            '../templates/relatorio_padrao_grupo.html', {
                'turmas': turmas_grupo,
                'titulo': grupo.nome
            })

        html = HTML(string=html_string)
        html.write_pdf(target=tipo + '.pdf')
        fs = FileSystemStorage('./')
        with fs.open(tipo + '.pdf') as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename="' + tipo + '.pdf"'
            return response
        return response
Ejemplo n.º 7
0
    def get(request):
        date = request.GET.get('date')
        if not date:
            return json_error('You must specify date')
        date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
        doctor_id = request.GET.get('doctor')
        if not doctor_id:
            return json_error('You must specify doctor')
        try:
            doctor = UserProfile.objects.get(pk=doctor_id)
        except UserProfile.DoesNotExist:
            return json_error('You must specify id of existing doctor')
        create_visit_for_doctor(doctor, date)
        visits = Visit.objects.filter(doctor=doctor, start_date__date=date).order_by('start_date')
        visit_serializer = VisitSerializer(visits, many=True, context={'user': request.user})

        if request.GET.get('export', False):
            context = {
                'visits': visit_serializer.data,
                'doctor': doctor,
                'date': date
            }
            html = render_to_string('export.html', context=context)
            html_document = HTML(string=html)
            pdf_buffer = BytesIO()
            html_document.write_pdf(pdf_buffer)
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="report_%s_%s.pdf"' % (doctor.get_full_name(),
                                                                                           date.strftime("%d %b %Y"))
            return response
        return JsonResponse(visit_serializer.data, safe=False)
Ejemplo n.º 8
0
def html_to_pdf_view(request):
    request.LANG = getattr(settings, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
    translation.activate(request.LANG)
    from django.core.files.storage import FileSystemStorage
    from django.http import HttpResponse
    from django.template.loader import render_to_string

    from weasyprint import HTML
    invoice = cache.get('invoice')
    inv_details = cache.get('inv_details')
    invoice = get_object_or_404(Invoice, invoice_number="INV-00005")
    inv_details = Invoice_details.objects.filter(invoicenumber="INV-00005")
    context = {'invoice': invoice, 'inv_details': inv_details}
    paragraphs = {'invoice': invoice, 'inv_details': inv_details}
    html_string = render_to_string('project/invoice_print.html', context)

    html = HTML(string=html_string)
    html.write_pdf(target='/tmp/mypdf.pdf')

    fs = FileSystemStorage('/tmp')
    with fs.open('mypdf.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
        return response

    return response
Ejemplo n.º 9
0
def Bill_pdf_view(request):
    data = Order.objects.filter(user=request.user).latest('id')
    u = data.user_id
    users = UserProfile.objects.get(user_id=u)
    list = data.item
    itemName = []
    itemprice = []
    for item in list:
        # print(item)
        menu = Menu.objects.get(id=item)
        # print(menu)
        # print(menu.item_name)
        itemName.append(menu.item_name)
        itemprice.append(menu.price)
    context = {
        'orders': data,
        'users': users,
        'menu': itemName,
        'menus': itemprice
    }

    html_string = render_to_string('Bill_pdf.html', context)
    html = HTML(string=html_string)
    html.write_pdf(target='Bill_pdf.pdf')

    fs = FileSystemStorage('')
    with fs.open('Bill_pdf.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response[
            'Content-Disposition'] = 'attatchment; filename="Bill_pdf.pdf"'
        return response
    return response
Ejemplo n.º 10
0
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')
Ejemplo n.º 11
0
   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)
Ejemplo n.º 12
0
def generate_pdf(prefix, data):
    template = get_template(app_settings.BATCH_PDF_TEMPLATE)
    html = HTML(string=template.render(data))
    f = open(f'/tmp/{prefix}.pdf', 'w+b')
    html.write_pdf(target=f)
    f.seek(0)
    return File(f)
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
def pdf_generation_supervisor(request, form_info, t_form_info):
    html_string = render_to_string('track/pdf-output.html', {
        'form': form_info,
        't_form': t_form_info,
    })
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    html.write_pdf(target='report.pdf')
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
def pdf(obj, path, site_url=None):
    activate(obj.language_code)  # required if called from command line

    # first page
    header_url = urljoin(
        site_url,
        reverse('activities:print-preview-header', kwargs={
            'code': obj.code,
        }))
    header_html_source = url_read(header_url)
    header = HTML(string=header_html_source, base_url=site_url).render()

    # other pages
    content_url = urljoin(
        site_url,
        reverse('activities:print-preview-content',
                kwargs={
                    'code': obj.code,
                }))
    content_html_source = url_read(content_url)
    content = HTML(string=content_html_source, base_url=site_url).render()

    header.pages += content.pages

    header.write_pdf(path)
Ejemplo n.º 17
0
def generate_pdf(request, id):
    hasil = RekamMedis.objects.all().select_related(
        'idpendaftaran', 'idantrian').filter(id=id).order_by('created_on')
    print(hasil.get().idpendaftaran.norm.norm)
    pesanobat = PemesananObat.objects.all().filter(idrm=id)
    biayadokter = BiayaPemeriksaan.objects.all()[:1].get()
    totalobat = 0
    for i in pesanobat:
        totalobat += i.subtotal_obat
    harusbayar = biayadokter.biaya_pemeriksaan + totalobat
    uangnya = Pembayaran.objects.all().filter(idpendaftaran=id).get()
    data = {
        'totalobat': totalobat,
        'biayadokter': biayadokter.biaya_pemeriksaan,
        'pesanan': pesanobat,
        'nonota': id,
        'data': hasil.get(),
        'namaakun': request.session['namapegawai'],
        'total': harusbayar,
        'uang': uangnya,
        'kembalian': uangnya.uang_dibayarkan - harusbayar
    }
    html_string = render_to_string('hal_admin/pegawaiadmin/pdf/bayar.html',
                                   data)

    html = HTML(string=html_string)
    html.write_pdf(target='/tmp/mypdf.pdf')

    fs = FileSystemStorage('/tmp')
    with fs.open('mypdf.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        # response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
        return response

    return response
Ejemplo n.º 18
0
def generate_pdf(url, context, ignore_context=False):
    """
    Builds a PDF of the passed in url.
    The URL is fetched relative to the context, unless ignore_context is True
    """

    request = getattr(context, "REQUEST", None)
    base_url = context.getParentDatabase().absolute_url()

    # Use subrequest to access the passed in url
    if ignore_context:
        page = subrequest(url)
    else:
        page = subrequest(url, root=context)

    # Transform the html
    # Have to set the content-type header to text/html before we can transform
    actual_header = request.response.getHeader('Content-Type')
    request.response.setHeader('Content-Type', 'text/html')
    html = transform_html(page.getBody(), request)
    request.response.setHeader('Content-Type', actual_header)

    pdf = HTML(string=html, base_url=base_url, url_fetcher=my_fetcher)

    output = StringIO()
    pdf.write_pdf(output)
    output.seek(0)
    return output
Ejemplo n.º 19
0
def payroll_report_export_pdf(request, **kwargs):
    context = {
        'business': kwargs.get('business'),
        'takehome_total': kwargs.get('takehome_total'),
        'takehome': kwargs.get('takehome'),
        'wcf': kwargs.get('wcf'),
        'nssf': kwargs.get('nssf'),
        'loan_board': kwargs.get('loan_board'),
        'paye': kwargs.get('paye'),
        'bonus': kwargs.get('bonus'),
        'overtime': kwargs.get('overtime'),
        'salaries_total': kwargs.get('salaries_total'),
        'total_expenses': kwargs.get('total_expenses'),
        'employees': kwargs.get('employees'),
        'deduction': kwargs.get('deduction'),
        'sdl': kwargs.get('sdl')
    }
    html_string = render_to_string('payroll-report-pdf.html', context)
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    html.write_pdf(target='/tmp/payroll_report.pdf')

    fs = FileSystemStorage('/tmp')
    with fs.open('payroll_report.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        return response
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
 def printpdf(self, filepath):
     app_path = os.path.abspath(os.path.dirname(__file__))
     path = Path(app_path)
     parentpath = str(path.parent)
     env_path = os.path.join(parentpath, 'data', 'html')
     css_path = os.path.join(env_path, 'style.css')
     env = Environment(loader=FileSystemLoader(env_path))
     template = env.get_template('column_report.html')
     if self.__corrected:
         status = 'Applied'
         null_replaced = 'have been'
     else:
         status = 'Suggested'
         null_replaced = 'will be'
     template_vars = {
         'cname': self.qcfield.name,
         'gen_stat_table': tupples2table(self.prettygeneral.items()),
         'stat_table': tupples2table(self.prettystats.items()),
         'status': status,
         'null_replaced': null_replaced,
         'dcorrections_table': tupples2table(self.dcorrections),
         'ccorrections_table': tupples2table(self.ccorrections),
         'removed_values': list2parag(self.cnulls | self.dnulls),
     }
     html_out = template.render(template_vars)
     document = HTML(string=html_out).render(stylesheets=[css_path])
     document.write_pdf(target=filepath)
Ejemplo n.º 22
0
def printPdf(request, filename, queryset, template):
    html_string = render_to_string('{template}'.format(template=template),
                                   {'entities': queryset})

    html = HTML(string=html_string, base_url=request.build_absolute_uri())

    filename = '{filename}-{date}'.format(
        date=datetime.now().strftime('%Y-%m-%d'),
        filename=filename,
    )

    html.write_pdf(
        target='/tmp/{filename}.pdf'.format(filename=filename),
        stylesheets=[CSS(settings.STATIC_ROOT + '/css/print.css')],
        # presentational_hints=True
    )

    fs = FileSystemStorage('/tmp')
    with fs.open('{filename}.pdf'.format(filename=filename)) as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response[
            'Content-Disposition'] = 'attachment; filename="{filename}.pdf"'.format(
                filename=filename)
        return response

    return response
Ejemplo n.º 23
0
def envia_pdf(request, id, destinatario):
    questionario = Questionario.objects.get(id=id)
    titulo = questionario.titulo
    titulo_formatado = slugify(titulo)
    perguntas = Pergunta.objects.filter(questionario=questionario).distinct()
    context = {
        'questionario': questionario,
        'perguntas': perguntas,
    }
    html_string = render_to_string('core/template_pdf.html', context)
    html = HTML(string=html_string)
    html.write_pdf(target='detalhes-{}.pdf'.format(titulo_formatado))

    fs = FileSystemStorage('/tmp')
    with fs.open('detalhes-{}.pdf'.format(titulo_formatado)) as pdf:
        arquivo = pdf.read()
        response = HttpResponse(arquivo, content_type='application/pdf')
        response[
            'Content-Disposition'] = 'attachment; filename="detalhes-{}.pdf"'.format(
                titulo_formatado)
        email = EmailMessage(
            subject=f'Detalhes { questionario.titulo }',
            body=
            f'Email enviado com o relatório do { questionario.titulo } anexo',
            to=[destinatario],
        )
        email.attach_file('/tmp/detalhes-{}.pdf'.format(titulo_formatado))
        email.send()
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
def create_and_save_doc(document_data, index_html, output_pdf):
    """
    Creates a PDF invoice by filling an HTML template with a YML file.

    Parameters
    ----------
    document_data : dict
        Data to use for filling the HTML template.
    index_html : str
        Absolute path to html template file.
    output_pdf : str
        Name of the output PDF file.

    Returns
    -------
    Saves the output PDF to output/ directory
    """
    pos_number = 1
    document_data['totals'] = {'net': 0, 'gross': 0, 'tax': 0}
    for pos in document_data['positions']:
        if not 'tax_rate' in pos:
            pos['tax_rate'] = document_data['tax_rate']

        pos['pos_number'] = pos_number
        pos['total_net_price'] = pos['net_price'] * pos['amount']
        pos['total_tax'] = \
            pos['total_net_price'] * (pos['tax_rate'] / float(100))
        pos['total_gross_price'] = pos['total_net_price'] + pos['total_tax']

        document_data['totals']['net'] += pos['total_net_price']
        document_data['totals']['gross'] += pos['total_gross_price']
        document_data['totals']['tax'] += pos['total_tax']

        pos['amount'] = locale.format_string("%.2f", pos['amount'])
        pos['tax_rate'] = locale.format_string("%.2f", pos['tax_rate'])
        pos['net_price'] = locale.format_string("%.2f", pos['net_price'])
        pos['total_net_price'] = \
            locale.format_string("%.2f", pos['total_net_price'])
        pos['text'] = pos['text'].replace('\n', '<br>')

        pos_number += 1

    document_data['totals']['net'] = \
        locale.format_string("%.2f", document_data['totals']['net'])
    document_data['totals']['gross'] = \
        locale.format_string("%.2f", document_data['totals']['gross'])
    document_data['totals']['tax'] = \
        locale.format_string("%.2f", document_data['totals']['tax'])

    with codecs.open(index_html, encoding="utf-8") as index_file:
        html_text = index_file.read()

        compiler = Compiler()
        template = compiler.compile(html_text)

        html_text = template(document_data)

        weasytemplate = HTML(string=html_text)
        weasytemplate.write_pdf(os.path.join('/app', 'output', output_pdf))
    return
Ejemplo n.º 26
0
def render_pdf():
    with open(index_html, encoding="utf-8") as index_file:
        env = Environment(loader=FileSystemLoader('.'))
        template = env.get_template(index_html)
        html_text = template.render(document_data)
        weasytemplate = HTML(string=html_text, base_url=base_url)
        weasytemplate.write_pdf(output_pdf)
Ejemplo n.º 27
0
 def pdf(self, text=TEXT):
     """ Generate a PDF file from the report data. """
     self.logger.debug("Generating the PDF report...")
     html = HTML(string=self.html())
     css_file = self.css or join(dirname(abspath(__file__)),
                                 "{}.css".format(self.theme))
     css = [css_file, CSS(string=PAGE_CSS % self.__dict__)]
     html.write_pdf("{}.pdf".format(self.filename), stylesheets=css)
Ejemplo n.º 28
0
 def convert_rst(self, output_path):
     rst_file = self.read_file_to_bytes()
     html_code = core.publish_string(source=rst_file,
                                     writer_name='html').decode()
     result = html_code[html_code.find('<body>') +
                        6:html_code.find('</body>')].strip()
     html = HTML(string=result)
     html.write_pdf(output_path, )
Ejemplo n.º 29
0
def generate_invoice_pdf(data):
    file_path = os.path.join(settings.MEDIA_ROOT, 'static', 'invoice')
    html_string = render_to_string('invoice_pdf.html', data)
    html = HTML(string=html_string)
    file_path = f'{file_path}/invoice.pdf'
    html.write_pdf(target=file_path)
    print(file_path)
    return file_path
Ejemplo n.º 30
0
 def getAllBooks1PDF(self):
     fn = self.getAllBooks1HTML()
     if fn:
         html = HTML(fn, encoding='utf8')
         css = CSS(string='body { font-family: "Microsoft YaHei" }')
         fnOut = '%s.pdf' % BOT_NAME
         html.write_pdf(fnOut, stylesheets=[css])
         return fnOut
Ejemplo n.º 31
0
 def getBookPDF(self, name):
     fn = self.getBookHTML(name)
     if fn:
         html = HTML(fn, encoding='utf8')
         css = CSS(string='body { font-family: "Microsoft YaHei" }')
         fnOut = '%s.pdf' % name
         html.write_pdf(fnOut, stylesheets=[css])
         return fnOut
Ejemplo n.º 32
0
def writepdf(file_data):
    global global_root_dir, image_base
    font_config = FontConfiguration()
    css = read_css()
    image_base_url()
    html = HTML(string=file_data, base_url=image_base, encoding="utf8")
    # print(css)
    html.write_pdf(filename + '.pdf', stylesheets=css, font_config=font_config)
Ejemplo n.º 33
0
def generate_pdf(template, data, filename):
    template_rendered = render_template(template, data=data)
    html_file = HTML(string=template_rendered,
                     base_url=current_app.config['API_ENDPOINT'],
                     encoding="utf-8")
    file_abs_path = str(BACKEND_DIR) + "/static/pdf/" + filename
    html_file.write_pdf(file_abs_path)
    return file_abs_path
Ejemplo n.º 34
0
def convert_html_to_pdf(html_path, output_path, encoding='utf-8'):
    try:
        html = HTML(html_path, encoding=encoding)
        html.write_pdf(output_path)
        return True
    except Exception as e:
        print("exception occurred: {}".format(str(e)))
        return False
Ejemplo n.º 35
0
def pdf(obj, path, site_url=None):
    activate(obj.language_code)  # required if called from command line
    url = urljoin(site_url,
                  reverse('scoops:print-preview', kwargs={
                      'code': obj.code,
                  }))
    html_source = url_read(url)
    html_obj = HTML(string=html_source, base_url=site_url).render()
    html_obj.write_pdf(path)
Ejemplo n.º 36
0
    def raport_to_pdf_view(self, request, surveys, today):

        html_string = render_to_string('pdf_template.html', {
            'surveys': surveys,
            'today': today
        })
        html = HTML(string=html_string)
        html.write_pdf(target='media/pdf_report/survey_report.pdf',
                       stylesheets=[CSS('survey/static/css/PDFstyle.css')])
Ejemplo n.º 37
0
 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))
Ejemplo n.º 38
0
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)
Ejemplo n.º 39
0
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
Ejemplo n.º 40
0
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
Ejemplo n.º 41
0
def createPdf(htmlreport, outfile=None, css=None, images={}):
    """create a PDF from some HTML.
    htmlreport: rendered html
    outfile: pdf filename; if supplied, caller is responsible for creating
             and removing it.
    css: remote URL of css file to download
    images: A dictionary containing possible URLs (keys) and local filenames
            (values) with which they may to be replaced during rendering.
    # WeasyPrint will attempt to retrieve images directly from the URL
    # referenced in the HTML report, which may refer back to a single-threaded
    # (and currently occupied) zeoclient, hanging it.  All image source
    # URL's referenced in htmlreport should be local files.
    """
    # A list of files that should be removed after PDF is written
    cleanup = []
    css_def = ''
    if css:
        if css.startswith("http://") or css.startswith("https://"):
            # Download css file in temp dir
            u = urllib2.urlopen(css)
            _cssfile = tempfile.mktemp(suffix='.css')
            localFile = open(_cssfile, 'w')
            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, 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
Ejemplo n.º 42
0
 def _get_pdf(self, markup):
     logger = logging.getLogger(__name__)
     base_url = self.base_url if self.base_url else ''
     pdf_file = StringIO.StringIO()
     logger.info("Creating weasy")
     weasy = HTML(
         file_obj=StringIO.StringIO(markup.encode("UTF-8")),
         encoding='UTF-8',
         base_url=base_url,
         url_fetcher=self._url_fetcher
     )
     logger.info("Starting pdf generation")
     weasy.write_pdf(pdf_file)
     logger.info("PDF generated, returning")
     return pdf_file.getvalue()
Ejemplo n.º 43
0
    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
Ejemplo n.º 44
0
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)
Ejemplo n.º 45
0
def pdf(obj, path, site_url=None):
    activate(obj.language_code)  # required if called from command line

    # first page
    header_url = urljoin(site_url, reverse('activities:print-preview-header', kwargs={'code': obj.code, }))
    header_html_source = url_read(header_url)
    header = HTML(string=header_html_source, base_url=site_url).render()

    # other pages
    content_url = urljoin(site_url, reverse('activities:print-preview-content', kwargs={'code': obj.code, }))
    content_html_source = url_read(content_url)
    content = HTML(string=content_html_source, base_url=site_url).render()

    header.pages += content.pages

    header.write_pdf(path)
Ejemplo n.º 46
0
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)
Ejemplo n.º 47
0
def main():
    submissions = {}
    submissions_path = get_submissions_path(app.root_path)
    for submission_pkl in sorted(glob.glob(os.path.join(submissions_path, '*.pkl'))):
        with open(submission_pkl, 'rb') as submission_file:
            submission = cPickle.loads(submission_file.read())
            submissions[submission['student_email']] = submission
        os.unlink(submission_pkl)

    for s in submissions.values():
        weasy = HTML(string=s['receipt'])
        pdf_path = os.path.join(submissions_path, s['student_name'] + ".pdf")
        weasy.write_pdf(pdf_path)
        response = send_welcome_mail(s, pdf_path)
        print "Response " + str(response.status_code) + " for " + s['student_name'] + " - ",
        print response.json()
        os.unlink(pdf_path)
Ejemplo n.º 48
0
    def execute(self, id_user, id_meeting, css=None, qs=None):
        render = RenderHtml(id_user, id_meeting, self.__dirToProject, css=css, qs=qs)

        value = render.render_doc()

        with codecs.open(self.__dir, 'w', 'utf8') as file:
            file.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
Ejemplo n.º 49
0
   def savePDFURL(self, pdf_filename, soup, url, keys, school_name):
       try:
          weasyprint = HTML(string=soup.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
          return

       sep_filename = "pdfs/sep.pdf"
       self.makeSepPageURL(sep_filename, url, keys, 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)
Ejemplo n.º 50
0
    def process_IN_CREATE(self, event):
        if event.pathname.endswith(".html"):
            print "Creating:", event.pathname

            print "Loading file"
            wprint = HTML(filename=event.pathname)
            print "writing thumbnail"
            wprint.write_png(event.pathname.replace(".html", "_thumbnail.png")+".partial", resolution=10)
            print "writing pdf"
            wprint.write_pdf(event.pathname.replace(".html", ".pdf")+".partial")
            print "writing png"
            wprint.write_png(event.pathname.replace(".html", ".png")+".partial", resolution=300)

            # Remove the ".partial" to indicate that it's done generating both.
            for suffix in ('.pdf', '.png', '_thumbnail.png'):
                dest = event.pathname.replace(".html", suffix)
                src = dest + ".partial"
                os.rename(src, dest)
Ejemplo n.º 51
0
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
Ejemplo n.º 52
0
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
           css_file_path=None, base_url=None):
    """
    Converts input markdown to styled HTML and renders it to a PDF file.

    Args:
        pdf_file_path: output PDF file path.
        md_content: input markdown raw string content.
        md_file_path: input markdown file path.
        css_file_path: input styles path (CSS).
        base_url: absolute base path for markdown linked content (as images).

    Returns:
        None

    Raises:
        ValidationError: if md_content and md_file_path are empty.
    """

    # Convert markdown to html
    raw_html = ''
    extras = ['cuddled-lists', 'tables']
    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
Ejemplo n.º 53
0
def create_pdf(username, totals):
    """Test out functionality."""
    html = HTML(string='<body width="600px"><div class="top"><br /><br /><h4>SPRY Report</h4><p>Data about <b>{}</b></p></div>\
        <div><img class="insta" src="./{}.jpg"/></div\
        <div>Total accounts found: {}</div></body>'.format(username, username, totals))
    css = CSS(string='''
    .top { text-align: center; border-bottom: 2px dashed deepskyblue; padding: 5px; }
    p { font-family: mono; font-size: 12px; }
    h2,h3,h4 { font-family: "Andale Mono"; font-size: 14px; }
    ul,li { font-family: "Andale Mono"; font-size: 11px; letter-spacing: 0.08em; }
    ul { list-style: none; }
    ul { width: 500px; margin-bottom: 20px; border-top: 1px solid #ccc; }
    li { border-bottom: 1px solid #ccc; float: left; display: inline;}
    #double li { width:50%;}
    #triple li { width:33.333%; }
    #six li { width:16.666%; }
    #quad li { width:25%; }
    ''')
    html.write_pdf(
        '{}-report.pdf'.format(username), stylesheets=[css])
Ejemplo n.º 54
0
Archivo: hello.py Proyecto: mreider/qcv
def pdf(first_name,last_name):

    theme = Themes.query.filter_by(first_name=first_name).filter_by(last_name=last_name).first()
    if theme:
        htmlcontent = theme.html_content
        css = theme.css_content
    user = UserProfile.query.filter_by(first_name=first_name).filter_by(last_name=last_name).first()
    if user:
        positions = Positions.query.filter_by(user_id=user.user_id).all()
        educations = Education.query.filter_by(user_id=user.user_id).all()
        certifications = Certifications.query.filter_by(user_id=user.user_id).all()
    if htmlcontent:
        content = render_template_string(htmlcontent,first_name=first_name,last_name=last_name,
                                       user=user,positions=positions,educations=educations,
                                        certifications=certifications)
        print 'Saved content'
    else:
        content = render_template('basictheme.html',
                                   user=user,positions=positions,educations=educations,
                                    certifications=certifications)

    data = render_template('resume.html',theme=content,themestyle=css,first_name=first_name,last_name=last_name)
    html = HTML(string=data)
    css_file = file('print.css','r')
    css_content = css_file.read()

    css_content = css_content % (first_name+'.'+last_name+'s CV')
    css = CSS(string=css_content)
    output_file = '/tmp/cv.pdf'
    if os.path.exists(output_file):
        os.remove(output_file)
    html.write_pdf(output_file,stylesheets=[css])
    content = file(output_file).read()
    print 'PDF Generated at %s'%output_file
    return Response(content,
                       mimetype="application/pdf",
                       headers={"Content-Disposition":
                                    "attachment;filename=resume.pdf"})
Ejemplo n.º 55
0
    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
Ejemplo n.º 56
0
 def form_valid(self, form):
     self.post_data = self.request.POST
     if 'download' in self.post_data:
         html = self.render_to_response(self.get_context_data(form=form))
         f = open(os.path.join(
             os.path.dirname(__file__), './static/payslip/css/payslip.css'))
         html = HTML(string=html.render().content)
         pdf = html.write_pdf(stylesheets=[CSS(string=f.read())])
         f.close()
         resp = HttpResponse(pdf, content_type='application/pdf')
         resp['Content-Disposition'] = \
             u'attachment; filename="{}_{}.pdf"'.format(
                 self.date_start.year, self.date_start.month)
         return resp
     return self.render_to_response(self.get_context_data(form=form))
Ejemplo n.º 57
0
def generate_pdf(refer, request, context):
	"""
	generate_pdf

	:param refer: Refer info
	:type refer: TODO 
	:param request: The request info 
	:type request: django.core.handlers.wsgi.WSGIRequest  
	:param context: context
	:type context: TODO
	:returns: None -- Creates PDF file in refer/pdf directory
	"""
	try:
		from weasyprint import HTML
		# path contains leading / so use string join instead of path join
		img = ''.join([settings.INSTALLATION_PATH, context['current_practice_photo']]) 
		html = render_to_string('DoctorCom/Messaging/PreviewDialog.html', 
			{'pdf': True, 'practice_photo_path': img}, context)

		htmlobj = HTML(string=html)
		pdf = htmlobj.write_pdf() 

		encrypted_data = refer.encrypt_file(request, pdf)

		refer_pdf = '%s/refer/pdf' % (settings.MEDIA_ROOT,)
		if not os.path.exists(refer_pdf):
			os.makedirs(refer_pdf)		

		f = create_file('refer/pdf/%s' % refer.uuid)
		f.set_contents(encrypted_data)
		f.close()
	except IOError as e:
		err_email_body = '\n'.join([
				('PDF folder not exist!'),
				''.join(['Server: ', settings.SERVER_ADDRESS]),
				''.join(['Session: ', str(request.session.session_key)]),
				''.join(['Message: ', (u'PDF folder not exist: media/refer/pdf')]),
				''.join(['Exception: ', str(e)]),
				''.join(['Exception data: ', str(e.args)]),
			])
		mail_admins('PDF folder not exist', err_email_body)
Ejemplo n.º 58
0
    def asPDF(html, header=None, water=None, images=None):
        """
        Renders an html as PDF.
        Uses the "report.css" as stylesheet
        """

        # url fetcher for weasyprint
        def report_fetcher(url):
            logger.debug('Getting url for weasyprint {}'.format(url))
            if url.startswith('stock://'):
                imagePath = stock.getStockImagePath(url[8:])
                with open(imagePath, 'rb') as f:
                    image = f.read()
                return dict(string=image,
                            mime_type='image/png')
            elif url.startswith('image://'):
                img = ''  # Empty image
                if isinstance(images, dict):
                    img = images.get(url[8:], None)
                    logger.debug('Getting image {}? {}'.format(url[8:], img is not None))
                return dict(string=img,
                            mime_type='image/png')
            else:
                return default_url_fetcher(url)

        with open(stock.getStockCssPath('report.css'), 'r') as f:
            css = f.read()

        css = (
            css.replace("{header}", _('Report') if header is None else header)
                .replace('{page}', _('Page'))
                .replace('{of}', _('of'))
                .replace('{water}', 'UDS Report' if water is None else water)
                .replace('{printed}', _('Printed in {now:%Y, %b %d} at {now:%H:%M}').format(now=datetime.now()))
        )

        h = HTML(string=html, url_fetcher=report_fetcher)
        c = CSS(string=css)

        return h.write_pdf(stylesheets=[c])
Ejemplo n.º 59
0
    def __call__(self, REQUEST, RESPONSE):
        content = super(ExportaConsultaPDFView, 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 = []
        css_path = '{0}/++resource++smdu.participacao/css/proposta.css'.format(portal_url)
        r = requests.get(css_path)
        stylesheets.append(CSS(string=r.content))
        css_path = '{0}/++resource++smdu.participacao/css/print_proposta.css'.format(portal_url)
        r = requests.get(css_path)
        stylesheets.append(CSS(string=r.content))
        css_path = '{0}/++resource++smdu.participacao/css/print.css'.format(portal_url)
        r = requests.get(css_path)
        stylesheets.append(CSS(string=r.content))
        
        consulta_exportada_pdf = html.write_pdf(stylesheets=stylesheets)

        RESPONSE.setHeader('Content-Type', 'application/pdf; charset=utf-8')
        RESPONSE.setHeader('Content-Length', len(consulta_exportada_pdf))
        RESPONSE.setHeader('Content-Disposition', 'attachment; filename="Relatorio.pdf"')
        return consulta_exportada_pdf
Ejemplo n.º 60
0
 def html2file(self, html, filename):
     pdf = HTML(string=html)
     pdf.write_pdf(filename)