Beispiel #1
0
def send_email_create_contract(req_pay):
    content = render_to_string("admin/email/student/create_contract.html",
                               {"data": req_pay})
    subject = "[ODIN] Hợp đồng khoá học"

    student_debts = StudentDebt.objects.filter(
        centre=req_pay.centre,
        course=req_pay.course,
        student__user__email=req_pay.email)
    if student_debts.count() > 0:
        contract = create_contract_info(student_debts[0])
        pdf = html_to_pdf(template='admin/contract/index.html',
                          data=contract,
                          stylesheets=[
                              CSS('static/css/contract.css'),
                              CSS('static/assets/css/bootstrap.min.css')
                          ])
        attach_file = {
            "name":
            "Hợp đồng khoá học sinh viên %s.pdf" % req_pay.full_name,
            "content": pdf,
            "mimetype": "application/pdf"
        }
        send_email_to_user(to_name=req_pay.full_name,
                           to_email=req_pay.email,
                           subject=subject,
                           content=content,
                           attach_files=[attach_file])
Beispiel #2
0
    def _compute_overlay_element(self, element: str):
        overlay_layout = (
            '@page {size: A4 %s; margin: 0;}' % self.page_orientation +
            '\nheader {position: fixed; width: 100%; top: 0;}' +
            '\nfooter {position: fixed; width: 100%; bottom: 0;}')
        stylesheets = [CSS(string=overlay_layout)]
        for sheet in self.stylesheets:
            stylesheets.append(CSS(string=sheet or ''))

        html = HTML(
            string=getattr(self, '{}_html'.format(element)),
            base_url=self.base_url,
            )
        element_doc = html.render(stylesheets=stylesheets)
        element_page = element_doc.pages[0]
        element_body = PdfGenerator.get_element(
            element_page._page_box.all_children(), 'body')
        element_body = element_body.copy_with_children(
            element_body.all_children())
        element_html = PdfGenerator.get_element(
            element_page._page_box.all_children(), element)

        if element == 'header':
            element_height = element_html.height
        if element == 'footer':
            element_height = element_page.height - element_html.position_y

        return element_body, element_height
Beispiel #3
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
Beispiel #4
0
def generate_PDF(request, id):
    invoice = get_object_or_404(Invoice, id=id)
    lineitem = invoice.lineitem_set.all()

    context = {
        "company": {
            "name": "DB Project",
            "address": "University of Engineering and Technology, Lahore",
            "phone": "(+92) XXX XXXX",
            "email": "*****@*****.**",
        },
        "invoice_id": invoice.id,
        "invoice_total": invoice.total_amount,
        "customer": invoice.customer,
        "customer_email": invoice.customer_email,
        "date": invoice.date,
        "due_date": invoice.due_date,
        "billing_address": invoice.billing_address,
        "message": invoice.message,
        "lineitem": lineitem,
    }
    # Use False instead of output path to save pdf to a variable
    html_template = get_template(
        '/home/Mahnoorkh/dpharmacy/invoice/templates/invoice/pdf_template.html'
    ).render(context)
    pdf_file = HTML(string=html_template).write_pdf(stylesheets=[
        CSS(os.path.join(BASE_DIR, 'static/css/invoice-template-1.css')),
        CSS(os.path.join(BASE_DIR, 'static/img/uetlogo.png')),
        CSS(string='@page { size: A3; margin: 1cm }')
    ])
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="invoice.pdf"'
    return response

    return response
Beispiel #5
0
 def get_stylesheets(self):
     return [
         CSS(find_static('css/normalize.css')),
         CSS(find_static('css/bootstrap/bootstrap.min.css')),
         CSS(find_static('css/base.css')),
         CSS(find_static('css/pdf.css'))
     ]
Beispiel #6
0
    def extract(self, ordered):

        if ordered:
            text = self._unifyTextOrdered()
        else:
            text = self._unifyTextUnordered()

        first_page = '<h1 class="session-name">{}</h1>\n'.format(
            self.title) + '<p class="date">{}</p>\n'.format(
                self.date) + '<p class="author">{}</p>\n\n'.format(self.author)

        font_config = FontConfiguration()
        html = markdown.markdown(
            text,
            extensions=[
                'markdown_katex',
            ],
            extension_configs={
                'markdown_katex': {
                    'no_inline_svg': True,  # fix for WeasyPrint
                    'insert_fonts_css': False,
                },
            })

        html = first_page + html
        css = CSS(filename=path.join(self.appPath, 'style.css'),
                  font_config=font_config)
        katexCss = CSS(filename=path.join(self.appPath, 'katex.min.css'),
                       font_config=font_config)
        HTML(string=html).write_pdf(self.exportPath,
                                    stylesheets=[katexCss, css],
                                    font_config=font_config)
Beispiel #7
0
def test_python_render(tmpdir):
    """Test rendering with the Python API."""
    base_url = resource_filename('dummy.html')
    html_string = '<body><img src=pattern.png>'
    css_string = '''
        @page { margin: 2px; size: 8px; background: #fff }
        body { margin: 0; font-size: 0 }
        img { image-rendering: pixelated }

        @media screen { img { transform: rotate(-90deg) } }
    '''
    html = FakeHTML(string=html_string, base_url=base_url)
    css = CSS(string=css_string)

    png_bytes = html.write_png(stylesheets=[css])
    pdf_bytes = html.write_pdf(stylesheets=[css])
    assert png_bytes.startswith(b'\211PNG\r\n\032\n')
    assert pdf_bytes.startswith(b'%PDF')
    check_png_pattern(png_bytes)
    # TODO: check PDF content? How?

    png_file = _fake_file()
    html.write_png(png_file, stylesheets=[css])
    assert png_file.getvalue() == png_bytes
    pdf_file = _fake_file()
    html.write_pdf(pdf_file, stylesheets=[css])
    # assert pdf_file.read_binary() == pdf_bytes

    png_file = tmpdir.join('1.png')
    pdf_file = tmpdir.join('1.pdf')
    html.write_png(png_file.strpath, stylesheets=[css])
    html.write_pdf(pdf_file.strpath, stylesheets=[css])
    assert png_file.read_binary() == png_bytes
    # assert pdf_file.read_binary() == pdf_bytes

    png_file = tmpdir.join('2.png')
    pdf_file = tmpdir.join('2.pdf')
    with open(png_file.strpath, 'wb') as png_fd:
        html.write_png(png_fd, stylesheets=[css])
    with open(pdf_file.strpath, 'wb') as pdf_fd:
        html.write_pdf(pdf_fd, stylesheets=[css])
    assert png_file.read_binary() == png_bytes
    # assert pdf_file.read_binary() == pdf_bytes

    x2_png_bytes = html.write_png(stylesheets=[css], resolution=192)
    check_png_pattern(x2_png_bytes, x2=True)

    screen_css = CSS(string=css_string, media_type='screen')
    rotated_png_bytes = html.write_png(stylesheets=[screen_css])
    check_png_pattern(rotated_png_bytes, rotated=True)

    assert FakeHTML(
        string=html_string, base_url=base_url, media_type='screen'
    ).write_png(
        stylesheets=[io.BytesIO(css_string.encode('utf8'))]
    ) == rotated_png_bytes
    assert FakeHTML(
        string=f'<style>{css_string}</style>{html_string}',
        base_url=base_url, media_type='screen'
    ).write_png() == rotated_png_bytes
Beispiel #8
0
def generate_pdf(request):
    module_dir = os.path.dirname(__file__)  # get current directory
    file_path = os.path.join(module_dir,
                             'templates/calculdej/calculdejresultat.html')
    file_pathCss = os.path.join(module_dir, "../static/css/style.css")
    file_pathBase = os.path.join(module_dir, "../templates/baseActivite.html")

    dossier = Dossier.objects.filter(dernier=True).reverse()[0]

    html_string = render_to_string(
        file_path, {
            'imc': dossier.imc,
            'DET': dossier.det,
            'MB': dossier.mb,
            'DEI': dossier.de,
            'niveau': dossier.niveau
        })
    HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(
        "pdfResultats.pdf",
        stylesheets=[
            CSS(file_pathCss),
            CSS("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
                )
        ])
    with open("pdfResultats.pdf", 'rb') as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=pdfResultats.pdf'
        return response
    pdf.closed
    dossier.dernier = False
    dossier.save()
    return render(request, 'calculdej/pdf.html', locals())
Beispiel #9
0
def index(request):

    data = {
        "First Name": ["Rajadip", "Ruturaj", "Pranali"],
        "Last Name": ["Patil", "Salokhe", "Jadhav"],
        "Email": ["[email protected]", "[email protected]", "[email protected]"],
        "Age": [21, 22, 23],
        "Salary": [3.5, 4, 4.5],
        "Gender": ["Male", "Male", "Female"],
        "Date of Birth": ["01 Jan, 1995", "01 Feb,1995", "03 March, 1995"],
        "City": ["Kolhapur", "Pune", "Mumbai"],
        "Pincode": ["461012", "411022", "400125"]
    }

    html_template = render_to_string("reporting/rajadip_assignment.html",
                                     {'data': data})

    css_1 = CSS(string="@page{ @bottom-center{ content:counter(page) } }")
    css_2 = CSS(
        string="@page{ @top-center{ content:'This is Commom header' } }")

    pdf_file = HTML(string=html_template,
                    base_url=request.build_absolute_uri()).write_pdf(
                        stylesheets=[css_1, css_2])

    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="home_page.pdf"'
    return response
Beispiel #10
0
def to_pdf_cv(request, cv_lang, cv_id):
    '''
        Generata pdf for CVs
    '''
    context = query_student(request.user.id)
    letter = get_object_or_404(Letter, id=cv_id, user_id=request.user.id)
    context.update({
        'cv_lang': cv_lang,
        'cv_id': cv_id,
        'letter': letter,
        'is_pdf_view': True
    })

    html_file = ''.join(['resumeApp/cv_', cv_lang, '.html'])
    font_config = FontConfiguration()
    html_string = render_to_string(html_file, context)
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    css = [
        CSS(css_dir + '/screens/common_style.css'),
        CSS(fonts_dir + '/thsarabunnew.css', font_config=font_config),
        CSS(css_dir + '/screens/cv_screen.css'),
    ]
    pdf_file = html.write_pdf(stylesheets=css, font_config=font_config)
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="cv.pdf"'

    return response
Beispiel #11
0
def generar_base_pdf(request, encabezado_url: str, contexto_documento: dict,
                     template: str) -> BytesIO:
    html_get_template = get_template(
        'emails/base/base_pagina_carta.html').render()
    html = HTML(string=html_get_template,
                base_url=request.build_absolute_uri())
    main_doc_base = html.render(
        stylesheets=[CSS('static/css/pdf_carta_email.css')])
    context = {"encabezado_url": encabezado_url}
    html_get_template = get_template('emails/base/encabezado.html').render(
        context)
    html = HTML(string=html_get_template,
                base_url=request.build_absolute_uri())
    header_logo = html.render(stylesheets=[
        CSS(string='div {position: fixed; top: 0, margin:0, padding:0}')
    ])

    header_logo_page = header_logo.pages[0]
    header_logo_body = get_page_body(header_logo_page._page_box.all_children())
    header_logo_body = header_logo_body.copy_with_children(
        header_logo_body.all_children())

    for i, page in enumerate(main_doc_base.pages):
        page_body = get_page_body(page._page_box.all_children())
        page_body.children += header_logo_body.all_children()

    output_base = BytesIO()
    main_doc_base.write_pdf(target=output_base)
    pdf_base_reader = PdfFileReader(output_base)

    # CREACION DE DOCUMENTO
    output_documento = BytesIO()
    html_get_template_documento = get_template(template).render(
        contexto_documento)
    html_documento = HTML(string=html_get_template_documento,
                          base_url=request.build_absolute_uri())
    width = '215mm'
    height = '279mm'
    size = 'size: %s %s' % (width, height)
    margin = 'margin: 0.8cm 0.8cm 0.8cm 0.8cm'

    css_string = '@page {text-align: justify; font-family: Arial;font-size: 0.6rem;%s;%s}' % (
        size, margin)
    main_doc_documento = html_documento.render(
        stylesheets=[CSS(string=css_string)])
    main_doc_documento.write_pdf(target=output_documento)
    pdf_documento_reader = PdfFileReader(output_documento)
    cantidad_hojas = pdf_documento_reader.getNumPages()

    # COMBINA BASE CON DOCUMENTO HOJA POR HOJA
    writer_con_logo = PdfFileWriter()
    for nro_hora in range(cantidad_hojas):
        page_object_base = pdf_base_reader.getPage(0)
        page_object_documento = pdf_documento_reader.getPage(nro_hora)
        page_object_documento.mergePage(page_object_base)
        writer_con_logo.addPage(page_object_documento)
    writer_con_logo.write(output_documento)
    output_base.close()
    return output_documento
Beispiel #12
0
def pdf_generation(template_src, context_dict):
	template = get_template(template_src)
	context = context_dict
	html_template = template.render(context)
	pdf_file = HTML(string=html_template).write_pdf(
		stylesheets=[CSS(settings.STATICFILES_DIRS[0] + '/css/sb-admin.css'), CSS(settings.STATICFILES_DIRS[0] + '/css/sb-admin.css')])
	response = HttpResponse(pdf_file, content_type='application/pdf')
	response['Content-Disposition'] = 'filename="recibo.pdf"'
	return response
Beispiel #13
0
def weasyprint_pdf_view(request):
    html_string = render_to_string('invoice.html')
    response = HttpResponse(content_type='application/pdf')
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    html.write_pdf(response,
                   stylesheets=[
                       CSS(settings.STATIC_ROOT + '/css/pdf.css'),
                       CSS(string='body { font-family: serif !important }'),
                   ])
    return response
Beispiel #14
0
def run(url, size_image, dir, run_print, apiurl="http://*****:*****@?,.|"
    title =  ''.join(e for e in data['title'] if e.isalnum() or e.isspace() or e in symbols)
    file_name = f"{fileTime}-{title}.pdf"
    file_path = f"{dir}/{file_name}"

    output = """
    <h1 id='pf-title'> {title} </h1>
    <div id='pf-src'> <a id='pf-src-url' href='{url}'><img id='pf-src-icon' src='https://s2.googleusercontent.com/s2/favicons?domain={domain}'>{url}</a></div>
    <span id="pf-author">{author}</span>
    <span id="pf-date">{date}</span>
    <br>
    <div id="pf-content">
    {content}
    </div>
    """.format(title=data['title'], url=unquote(url), domain=urlparse(url).netloc, author=data['byline'], date=easternTime, content=data['content'])

    DEBUG = False
    # DEBUG = True
    if DEBUG:
        print(output)
    html = HTML(string=output)
    css = CSS(f'{dir_path}/static/read.css')
    cssImage = CSS(
        string='img {{max-width: {}% !important;}}'.format(size_image))

    html.write_pdf(file_path, stylesheets=[css, cssImage])

    if run_print:
        print('printing...')
        subprocess.run("lpr -P EPSON_WF-3730_Series '{}'".format(
            file_path), shell=True, check=True, universal_newlines=True)
        print('done!')
    
    if run_open:
        subprocess.run("open '{}'".format(file_path), shell=True, check=True, universal_newlines=True)

    return file_name
 def get(self):
     body = self.get_argument('body')
     location = self.get_argument('location')
     url = ('static/websafe/' + time.strftime("%Y%m%d-%H%M%S") +
            '_' + location + '.pdf')
     HTML(string=str(body),
          base_url="file://%s/" % (ROOT)) \
         .write_pdf(url,
             stylesheets=[CSS('static/css/websafepdf.css'),
                          CSS(string='@page { size: A4; margin: 1cm }')])
     self.write(json.dumps({"success":True, "url":url}))
    def get(self, *args, **kwargs):
        if self.Action:
            # ! Source
            ## https://simpleisbetterthancomplex.com/tutorial/2016/08/08/how-to-export-to-pdf.html

            pdfFileName = '%s_%s.pdf' % (
                self.request.user.username,
                datetime.datetime.now().strftime("%H%M%S%m%d%Y"))

            if self.Action == "ExportAll":
                html_string = render_to_string(
                    template_pdfRenderer, {
                        'DataSets':
                        UserTasks.objects.filter(
                            Task_Owner=self.request.user.uuid)
                    })
                html = HTML(string=html_string).write_pdf(
                    target='userdata/ExportedPDFs/%s' % (pdfFileName),
                    stylesheets=[
                        CSS('CrudSimulation\static\css\material.min.css'),
                        CSS('CrudSimulation\static\css\sc_require-min.css')
                    ])
                fs = FileSystemStorage('')

                with fs.open("userdata/ExportedPDFs/" + pdfFileName) as pdf:
                    response = HttpResponse(pdf,
                                            content_type='application/pdf')
                    response[
                        'Content-Disposition'] = 'attachment; filename="%s.pdf"' % (
                            pdfFileName)
                    return response

                return HttpResponseRedirect(reverse('data_user_view'))

            elif "Delete" in self.Action:
                try:
                    if "All" in self.Action:
                        UserTasks.objects.all().delete()
                        messages.success(self.request, "DeletionSuccess")
                    else:
                        UserTasks.objects.filter(
                            Task_UUID=self.kwargs['dataAttached']).delete()
                        messages.success(self.request, "DeletionSuccess")

                except:
                    messages.error(self.request, "DeletionFailed")

                finally:
                    return HttpResponseRedirect(reverse('data_user_view'))

        else:
            print("No other such candidate!")
            messages.error(self.request, "")
Beispiel #17
0
def booking_form(request, booking_number):

    gh = Guesthouse.objects.get(pk=settings.GH_ID)

    printpdf = request.GET.get("printpdf", "NO")

    room = Room_allocation.objects.filter(
        booking_id=booking_number).select_related('booking', 'guest', 'bed',
                                                  'room', 'floor',
                                                  'block').first()

    if not room:
        room = Booking.objects.filter(
            booking_number=booking_number).select_related('guest').first()
        bk_num = room.booking_number
    else:
        bk_num = room.booking_id

    if printpdf == "YES":
        if room:
            html_string = render_to_string('guesthouse/booking_form_pdf.html',
                                           {
                                               'room': room,
                                               'gh': gh,
                                               'bk_num': bk_num
                                           })

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

            html.write_pdf(target=settings.TMP_FILES + bk_num + '_pdf.pdf',
                           stylesheets=[
                               CSS(settings.CSS_FILES + 'style.default.css'),
                               CSS(settings.CSS_FILES + 'custom.css'),
                               CSS(settings.VENDOR_FILES +
                                   'bootstrap/css/bootstrap.min.css')
                           ],
                           presentational_hints=True)

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

            return response

    return render(request, 'guesthouse/booking_form.html', {
        'room': room,
        'gh': gh,
        'bk_num': bk_num
    })
Beispiel #18
0
async def render_pdf(request):

    form_data = {}
    temp_dir = None

    if not request.content_type == "multipart/form-data":
        logger.info(
            "Bad request. Received content type %s instead of multipart/form-data.",
            request.content_type,
        )
        return web.Response(status=400, text=f"Multipart request required.")

    reader = await request.multipart()

    with tempfile.TemporaryDirectory() as temp_dir:
        while True:
            part = await reader.next()

            if part is None:
                break

            if (
                part.name in ["html", "css"]
                or part.name.startswith("attachment.")
                or part.name.startswith("asset.")
            ):
                form_data[part.name] = await save_part_to_file(part, temp_dir)

        if "html" not in form_data:
            logger.info("Bad request. No html file provided.")
            return web.Response(status=400, text=f"No html file provided.")

        html = HTML(filename=form_data["html"], url_fetcher=url_fetcher)
        if "css" in form_data:
            css = CSS(filename=form_data["css"], url_fetcher=url_fetcher)
        else:
            css = CSS(string="@page { size: A4; margin: 2cm 2.5cm; }")

        attachments = [
            attachment
            for name, attachment in form_data.items()
            if name.startswith("attachment.")
        ]
        pdf_filename = os.path.join(temp_dir, "output.pdf")

        try:
            html.write_pdf(pdf_filename, stylesheets=[css], attachments=attachments)
        except Exception:
            logger.exception("PDF generation failed")
            return web.Response(status=500, text="PDF generation failed.")
        else:
            return await stream_file(request, pdf_filename, "application/pdf")
Beispiel #19
0
    def get(self, request, *args, **kwargs):
        """
        Handles get request to the 'download_ticket' named route

        Returns:
            A PDF response containing the ticket
        """
        user = request.user
        deal_id = kwargs['deal_id']
        deal = Deal.objects.get(pk=deal_id)
        quantity = int(request.GET.get('qty'))
        price = quantity * deal.price
        qr_img, unique_id = self.generate_unique_code(deal, user)
        logo_url = deal.advertiser.logo_image_url()

        # add ticket to database
        ticket = Ticket(
            user=user, item=deal, quantity=quantity,
            advertiser=deal.advertiser, ticket_id=unique_id
        )
        ticket.save()

        context = {
            'deal': deal,
            'logo_url': logo_url,
            'qr_img': qr_img,
            'issue_date': ticket.date_created,
            'quantity': quantity,
            'price': price,
            'user': user
        }
        html_template = get_template('tickets/ticket.html')
        rendered_html = html_template.render(
            RequestContext(request, context)).encode(encoding="UTF-8")
        styles = [
            CSS(string='.well-print { background-color: grey !important }'),
            CSS(
                settings.STATIC_ROOT + '/bootstrap/dist/css/bootstrap.min.css'
            ),
            CSS(settings.STATIC_ROOT + '/css/base_styles.css'),
        ]
        pdf_file = HTML(
            string=rendered_html,
            base_url=request.build_absolute_uri()
        ).write_pdf(stylesheets=styles)

        http_response = HttpResponse(pdf_file, content_type='application/pdf')
        http_response['Content-Disposition'] = ('attachment; '
                                                'filename=%s') % deal.slug
        return http_response
Beispiel #20
0
def md_to_pdf(path_to_md: Union[str, Path], author: str, title: str,
              size: str) -> None:
    path_to_md = Path(str(path_to_md))
    log.info("Converting %s to HTML", str(path_to_md))
    html = markdown2.markdown_path(
        path_to_md,
        extras=[
            "fenced-code-blocks",
            "cuddled-lists",
            "strike",
            "target-blank-links",
            "tables",
            "metadata",  # TODO for headers, footers…
            "header-ids",
        ],
    )

    # TODO write to a temporary file
    html_path = path_to_md.parent / (path_to_md.stem + ".html")
    with open(html_path, "w", encoding="utf-8") as html_file:
        html_file.write(html)

    log.info("Converting %s to PDF", str(path_to_md))
    pdf_path = path_to_md.parent / (path_to_md.stem + ".pdf")
    font_config = FontConfiguration()
    pdf_writer = HTML(string=html)
    css = CSS(
        string=importlib.resources.read_text("md_to_pdf", "main.css"),
        font_config=font_config,
    )
    css_size = CSS(
        string=importlib.resources.read_text("md_to_pdf", f"{size}.css"),
        font_config=font_config,
    )
    css_custom = CSS(
        string=f"""
          @page {{
            @top-left {{
              content: "{title}";
            }}
            @bottom-left {{
              content: "{author}";
            }}
          }}
        """,
        font_config=font_config,
    )
    pdf_writer.write_pdf(pdf_path,
                         stylesheets=[css, css_size, css_custom],
                         font_config=font_config)
    def render_html(self,
                    application,
                    letter,
                    css="static/style.css",
                    **kwargs):
        """
        Fetches the html for the given application/letter and returns bytes of the rendered pdf.

        Parameters
        ----------
        application : str (guid)
            The guid of the application the decision is attached to
        letter : str (guid)
            The guid of the letter ([lookup.letter] or [decision].[letter]) to render
        css : str
            The filepath of the css to use while rendering the letter pdf.

        Returns
        -------
        bytes
            The bytes of the rendered letter pdf.
        """
        html = self.retrieve_html(application, letter)
        logging.debug("Retrieved letter html: %s", html)
        pdf_css = CSS(css)
        pdf_obj = HTML(string=html)
        pdf_bytes = pdf_obj.write_pdf(stylesheets=[pdf_css])
        return pdf_bytes
Beispiel #22
0
def pdf_gen():
    marca = Marca.objects.all()
    html_string = render_to_string('pdf_template/marca.html', {'marca': marca})
    html = HTML(string=html_string)
    filename = 'marca_reporte_' + date.today().strftime("%d-%m-%Y")
    # change to an absolute uri for local change
    # keep it in temp for only download option
    name = '{0}.pdf'.format(filename)
    #uri = 'media/pdf_repo/' + name
    try:
        os.mkdir( os.path.join(settings.MEDIA_ROOT, 'pdf_repo', '{0}'.format(now().year)))
    except:
        pass
    uri = 'media/pdf_repo/{0}/{1}'.format(now().year, name)
    html.write_pdf(target=uri, stylesheets=[CSS('static/css/w3.css')]);
    # f = open(j)
    # myFile = File(f)
    Reportes.objects.create(nombre=filename, fecha_creacion=date.today().strftime("%Y-%m-%d"), file_path=uri)
    # Reportes.objects.create('marca_reporte' , date.today(), 'marca_reporte_17-12-2020.pdf')
    # html.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(target='/tmp/mypdf.pdf')
    # html.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(target='/tmp/mypdf.pdf')
    # fs = FileSystemStorage('./media/pdf_repo/')
    # with fs.open('mypdf.pdf') as pdf:
    #    response = HttpResponse(pdf, content_type='application/pdf')
    #   response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
    #  return response
Beispiel #23
0
def create_zip(zip_name, zip_id, home, family, fonts):
    zip_to_send = zipfile.ZipFile(zip_name,
                                  mode="x",
                                  compression=zipfile.ZIP_DEFLATED)

    for font in fonts:
        font_file = open(
            home + "/.fonts/" + font["variant"] + "-" + zip_id + ".otf", "wb+")
        font_bytes = bytearray(font["data"])
        font_file.write(font_bytes)
        zip_to_send.writestr(family + " " + font["variant"] + ".otf",
                             font_bytes)
        font_file.close()

    #Add readme
    readme_file = open("README.txt", "r")
    zip_to_send.writestr("README.txt", readme_file.read())
    readme_file.close()

    html = HTML(filename="specimen.html")
    css = CSS(string=".cus-font { font-family: '" + family + "';}")
    pdf = html.write_pdf(stylesheets=[css])

    zip_to_send.writestr("specimen.pdf", pdf)
    zip_to_send.close()
Beispiel #24
0
    def get(self, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        font_config = FontConfiguration()
        html = HTML(
            string=render_to_string(self.template_name, context=context))
        css_files = ['css/bootstrap.min.css', 'css/print.css']
        css_files = [
            'css/print.css',
        ]
        css_str = ""
        for f in css_files:
            with open(finders.find(f), 'r') as fh:
                css_str += fh.read()
        css = CSS(string=css_str)

        # Create a PDF response and use Weasy to print to it
        response = HttpResponse(content_type="application/pdf")
        response[
            'Content-Disposition'] = 'filename="relief_sale_receipt_{}.pdf"'.format(
                slugify(self.object.name))
        html.write_pdf(target=response,
                       stylesheets=[
                           css,
                       ],
                       font_config=font_config)

        return response
Beispiel #25
0
def renderPDF(request, template, pageData1, pageData2, pageData3, pageData4,
              pdfName, loopRefNum, csScript):

    c = {
        'pageData1': pageData1,
        'pageData2': pageData2,
        'pageData3': pageData3,
        'pageData4': pageData4,
        'loopRef': loopRefNum,
    }

    html_string = render_to_string(template, c)

    html = HTML(string=html_string).write_pdf(
        '{}/Project_SMO_Inventory/static/src/mypdf.pdf'.format(dirreq),
        stylesheets=[
            CSS(string='@page {size: ' + csScript + '; margin:35px;}')
        ])

    fs = FileSystemStorage(
        '{}/Project_SMO_Inventory/static/src/'.format(dirreq))

    with fs.open('mypdf.pdf') as pdf:

        response = HttpResponse(pdf, content_type='application/pdf')

        response[
            'Content-Disposition'] = 'attachment; filename="' + pdfName + '.pdf"'

        return response

    return response
Beispiel #26
0
def generate_report(request):
    start = request.GET.get('start')
    end = request.GET.get('end')
    print(start)
    print(end)

    if all((start, end)):
        template = 'reports/statistics_report.html'
        data = get_table_graph_data(start=start, end=end)
        print(f'data =================================\n{data}')

        context = {'data': data, 'start': start, 'end': end}

        template = get_template(template)
        html = template.render(context)

        css_string = """@page {
			size: a4 portrait;
			margin: 1mm;
			counter-increment: page;
		}"""

        pdf_file = HTML(string=html,
                        base_url=request.build_absolute_uri()).write_pdf(
                            stylesheets=[CSS(string=css_string)],
                            presentational_hints=True)
        response = HttpResponse(pdf_file, content_type='application/pdf')
        response['Content-Disposition'] = 'filename="Report.pdf"'
        return response
        return HttpResponse(response.getvalue(),
                            content_type='application/pdf')
    else:
        return HttpResponse('Please choose a date range')
Beispiel #27
0
def createPdf(htmlreport, outfile=None, css=None):
    debug_mode = App.config.getConfiguration().debug_mode
    # XXX css must be a local file - urllib fails under robotframework tests.
    css_def = ''
    if css:
        if css.startswith("http://") or css.startswith("https://"):
            # Download css file in temp dir
            u = urllib2.urlopen(css)
            _cssfile = Globals.INSTANCE_HOME + '/var/' + tmpID() + '.css'
            localFile = open(_cssfile, 'w')
            localFile.write(u.read())
            localFile.close()
        else:
            _cssfile = css
        cssfile = open(_cssfile, 'r')
        css_def = cssfile.read()
    if not outfile:
        outfile = Globals.INSTANCE_HOME + "/var/" + tmpID() + ".pdf"

    from weasyprint import HTML, CSS
    import os
    if css:
        HTML(string=htmlreport,
             encoding='utf-8').write_pdf(outfile,
                                         stylesheets=[CSS(string=css_def)])
    else:
        HTML(string=htmlreport, encoding='utf-8').write_pdf(outfile)

    if debug_mode:
        htmlfilepath = Globals.INSTANCE_HOME + "/var/" + tmpID() + ".html"
        htmlfile = open(htmlfilepath, 'w')
        htmlfile.write(htmlreport)
        htmlfile.close()
    return open(outfile, 'r').read()
Beispiel #28
0
    def get(self, request, *args, **kwargs):
        context = super(DisaggregationPrint, self).get_context_data(**kwargs)
        hmtl_string = render(
            request, self.template_name, {
                'data': context['data'],
                'program_selected': context['program_selected']
            })
        pdffile = HTML(string=hmtl_string.content)

        result = pdffile.write_pdf(stylesheets=[
            CSS(string='@page {\
                size: letter; margin: 1cm;\
                @bottom-right{\
                    content: "Page " counter(page) " of " counter(pages);\
                };\
            }')
        ])
        res = HttpResponse(result, content_type='application/pdf')
        res['Content-Disposition'] = 'attachment; \
            filename=indicators_disaggregation_report.pdf'

        res['Content-Transfer-Encoding'] = 'binary'
        # return super(DisaggregationReport, self).get(
        #   request, *args, **kwargs)
        return res
Beispiel #29
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
Beispiel #30
0
def generate_pdf(request, id_passageiro_passagem):
    """Generate pdf."""
    # Model data
    font_config = FontConfiguration()
    passageiro_passagem = get_object_or_404(PassageiroPassagem, pk=id_passageiro_passagem)
    remarcacoes = RemarcacaoPassagem.objects.filter(passageiro_passagem=passageiro_passagem)

    css = CSS(string='''
    .box-trecho {
	background-color:#F0F8FF;
	border: 1px solid;
	margin: 3px;
    font-size: 12px;
	padding: 8px;

}''', font_config=font_config)

    # Rendered
    html_string = render_to_string('passagem_emitida.html', {'passageiro_passagem': passageiro_passagem,
    'remarcacoes': remarcacoes})
    html = HTML(string=html_string)
    result = html.write_pdf(stylesheets=[css], font_config=font_config)

    # Creating http response
    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    #response['Content-Disposition'] = 'inline; filename=list_people.pdf'
    #response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'rb')
        response.write(output.read())

    return response