Esempio n. 1
0
def create_pdf_for_templated_letter(self, encrypted_letter_data):
    letter_details = current_app.encryption_client.decrypt(
        encrypted_letter_data)
    current_app.logger.info(
        f"Creating a pdf for notification with id {letter_details['notification_id']}"
    )
    logo_filename = f'{letter_details["logo_filename"]}.svg' if letter_details[
        'logo_filename'] else None

    template = LetterPrintTemplate(
        letter_details['template'],
        values=letter_details['values'] or None,
        contact_block=letter_details['letter_contact_block'],
        # letter assets are hosted on s3
        admin_base_url=current_app.config['LETTER_LOGO_URL'],
        logo_file_name=logo_filename,
    )
    with current_app.test_request_context(''):
        html = HTML(string=str(template))

    try:
        pdf = BytesIO(html.write_pdf())
    except WeasyprintError as exc:
        self.retry(exc=exc, queue=QueueNames.SANITISE_LETTERS)

    cmyk_pdf = convert_pdf_to_cmyk(pdf)
    page_count = get_page_count(cmyk_pdf.read())
    cmyk_pdf.seek(0)

    try:
        # If the file already exists in S3, it will be overwritten
        if letter_details["key_type"] == "test":
            bucket_name = current_app.config['TEST_LETTERS_BUCKET_NAME']
        else:
            bucket_name = current_app.config['LETTERS_PDF_BUCKET_NAME']
        s3upload(
            filedata=cmyk_pdf,
            region=current_app.config['AWS_REGION'],
            bucket_name=bucket_name,
            file_location=letter_details["letter_filename"],
        )

        current_app.logger.info(
            f"Uploaded letters PDF {letter_details['letter_filename']} to {bucket_name} for "
            f"notification id {letter_details['notification_id']}")

    except BotoClientError:
        current_app.logger.exception(
            f"Error uploading {letter_details['letter_filename']} to pdf bucket "
            f"for notification {letter_details['notification_id']}")
        return

    notify_celery.send_task(name=TaskNames.UPDATE_BILLABLE_UNITS_FOR_LETTER,
                            kwargs={
                                "notification_id":
                                letter_details["notification_id"],
                                "page_count":
                                page_count,
                            },
                            queue=QueueNames.LETTERS)
def create_content_for_notification(template, personalisation):
    if template.template_type == EMAIL_TYPE:
        template_object = PlainTextEmailTemplate(
            {
                'content': template.content,
                'subject': template.subject,
                'template_type': template.template_type,
            },
            personalisation,
        )
    if template.template_type == SMS_TYPE:
        template_object = SMSMessageTemplate(
            {
                'content': template.content,
                'template_type': template.template_type,
            },
            personalisation,
        )
    if template.template_type == LETTER_TYPE:
        template_object = LetterPrintTemplate(
            {
                'content': template.content,
                'subject': template.subject,
                'template_type': template.template_type,
            },
            personalisation,
            contact_block=template.reply_to_text,
        )

    check_placeholders(template_object)

    return template_object
Esempio n. 3
0
def print_letter_template():
    """
    POST /print.pdf with the following json blob
    {
        "letter_contact_block": "contact block for service, if any",
        "template": {
            "template data, as it comes out of the database"
        }
        "values": {"dict of placeholder values"},
        "filename": {"type": "string"}
    }
    """
    json = get_and_validate_json_from_request(request, preview_schema)
    filename = f'{json["filename"]}.svg' if json['filename'] else None

    template = LetterPrintTemplate(
        json['template'],
        values=json['values'] or None,
        contact_block=json['letter_contact_block'],
        # letter assets are hosted on s3
        admin_base_url=current_app.config['LETTER_LOGO_URL'],
        logo_file_name=filename,
    )
    html = HTML(string=str(template))
    pdf = BytesIO(html.write_pdf())

    cmyk_pdf = convert_pdf_to_cmyk(pdf)

    response = send_file(cmyk_pdf,
                         as_attachment=True,
                         attachment_filename='print.pdf')
    response.headers['X-pdf-page-count'] = get_page_count(cmyk_pdf.read())
    cmyk_pdf.seek(0)
    return response