Exemplo n.º 1
0
def test_extract_page_from_pdf_request_page_out_of_bounds():
    with pytest.raises(PdfReadError) as e:
        file_data = base64.b64decode(one_page_pdf)
        extract_page_from_pdf(BytesIO(file_data), 4)

    assert 'Page number requested: 4 of 1 does not exist in document' in str(
        e.value)
Exemplo n.º 2
0
def test_extract_page_from_pdf_one_page_pdf():
    file_data = base64.b64decode(one_page_pdf)
    pdf_page = extract_page_from_pdf(BytesIO(file_data), 0)

    pdf_original = PyPDF2.PdfFileReader(BytesIO(file_data))

    pdf_new = PyPDF2.PdfFileReader(BytesIO(pdf_page))

    assert pdf_original.getPage(0).extractText() == pdf_new.getPage(
        0).extractText()
Exemplo n.º 3
0
    def from_invalid_pdf_file(cls, pdf_file, page):
        pdf_page = extract_page_from_pdf(BytesIO(pdf_file), int(page) - 1)

        response = requests.post(
            '{}/precompiled/overlay.png{}'.format(
                current_app.config['TEMPLATE_PREVIEW_API_HOST'],
                '?page_number={}'.format(page)
            ),
            data=pdf_page,
            headers={'Authorization': 'Token {}'.format(current_app.config['TEMPLATE_PREVIEW_API_KEY'])}
        )

        return (response.content, response.status_code, response.headers.items())
Exemplo n.º 4
0
    def from_valid_pdf_file(cls, pdf_file, page):
        pdf_page = extract_page_from_pdf(BytesIO(pdf_file), int(page) - 1)

        response = requests.post(
            '{}/precompiled-preview.png{}'.format(
                current_app.config['TEMPLATE_PREVIEW_API_HOST'],
                '?hide_notify=true' if page == '1' else ''
            ),
            data=base64.b64encode(pdf_page).decode('utf-8'),
            headers={'Authorization': 'Token {}'.format(current_app.config['TEMPLATE_PREVIEW_API_KEY'])}
        )

        return (response.content, response.status_code, response.headers.items())
Exemplo n.º 5
0
def preview_letter_template_by_notification_id(service_id, notification_id,
                                               file_type):
    if file_type not in ('pdf', 'png'):
        raise InvalidRequest({'content': ["file_type must be pdf or png"]},
                             status_code=400)

    page = request.args.get('page')

    notification = get_notification_by_id(notification_id)
    template = dao_get_template_by_id(notification.template_id,
                                      notification.template_version)
    metadata = {}

    if template.is_precompiled_letter:
        try:

            pdf_file, metadata = get_letter_pdf_and_metadata(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                'Error extracting requested page from PDF file for notification_id {} type {} {}'
                .format(notification_id, type(e), e),
                status_code=500)

        page_number = page if page else "1"
        content = base64.b64encode(pdf_file).decode('utf-8')
        content_outside_printable_area = metadata.get(
            "message") == "content-outside-printable-area"
        page_is_in_invalid_pages = page_number in metadata.get(
            'invalid_pages', '[]')

        if content_outside_printable_area and (file_type == "pdf"
                                               or page_is_in_invalid_pages):
            path = '/precompiled/overlay.{}'.format(file_type)
            query_string = '?page_number={}'.format(
                page_number) if file_type == 'png' else ''
            content = pdf_file
        elif file_type == 'png':
            query_string = '?hide_notify=true' if page_number == '1' else ''
            path = '/precompiled-preview.png'
        else:
            path = None

        if file_type == 'png':
            try:
                pdf_page = extract_page_from_pdf(BytesIO(pdf_file),
                                                 int(page_number) - 1)
                if content_outside_printable_area and page_is_in_invalid_pages:
                    content = pdf_page
                else:
                    content = base64.b64encode(pdf_page).decode('utf-8')
            except PdfReadError as e:
                raise InvalidRequest(
                    'Error extracting requested page from PDF file for notification_id {} type {} {}'
                    .format(notification_id, type(e), e),
                    status_code=500)

        if path:
            url = current_app.config[
                'TEMPLATE_PREVIEW_API_HOST'] + path + query_string
            response_content = _get_png_preview_or_overlaid_pdf(
                url, content, notification.id, json=False)
        else:
            response_content = content
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version),
            "template_type": template.template_type
        }

        service = dao_fetch_service_by_id(service_id)
        letter_logo_filename = service.letter_branding and service.letter_branding.filename
        data = {
            'letter_contact_block': notification.reply_to_text,
            'template': template_for_letter_print,
            'values': notification.personalisation,
            'date': notification.created_at.isoformat(),
            'filename': letter_logo_filename,
        }

        url = '{}/preview.{}{}'.format(
            current_app.config['TEMPLATE_PREVIEW_API_HOST'], file_type,
            '?page={}'.format(page) if page else '')
        response_content = _get_png_preview_or_overlaid_pdf(url,
                                                            data,
                                                            notification.id,
                                                            json=True)

    return jsonify({"content": response_content, "metadata": metadata})
Exemplo n.º 6
0
def preview_letter_template_by_notification_id(service_id, notification_id,
                                               file_type):
    if file_type not in ('pdf', 'png'):
        raise InvalidRequest({'content': ["file_type must be pdf or png"]},
                             status_code=400)

    page = request.args.get('page')

    notification = get_notification_by_id(notification_id)

    template = dao_get_template_by_id(notification.template_id)

    if template.is_precompiled_letter:
        try:

            pdf_file = get_letter_pdf(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                'Error extracting requested page from PDF file for notification_id {} type {} {}'
                .format(notification_id, type(e), e),
                status_code=500)

        content = base64.b64encode(pdf_file).decode('utf-8')

        if file_type == 'png':
            try:
                page_number = page if page else "1"

                pdf_page = extract_page_from_pdf(BytesIO(pdf_file),
                                                 int(page_number) - 1)
                content = base64.b64encode(pdf_page).decode('utf-8')
            except PdfReadError as e:
                raise InvalidRequest(
                    'Error extracting requested page from PDF file for notification_id {} type {} {}'
                    .format(notification_id, type(e), e),
                    status_code=500)

            url = '{}/precompiled-preview.png{}'.format(
                current_app.config['TEMPLATE_PREVIEW_API_HOST'],
                '?hide_notify=true' if page_number == '1' else '')

            content = _get_png_preview(url,
                                       content,
                                       notification.id,
                                       json=False)
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version)
        }

        service = dao_fetch_service_by_id(service_id)

        data = {
            'letter_contact_block': notification.reply_to_text,
            'template': template_for_letter_print,
            'values': notification.personalisation,
            'dvla_org_id': service.dvla_organisation_id,
        }

        url = '{}/preview.{}{}'.format(
            current_app.config['TEMPLATE_PREVIEW_API_HOST'], file_type,
            '?page={}'.format(page) if page else '')
        content = _get_png_preview(url, data, notification.id, json=True)

    return jsonify({"content": content})
Exemplo n.º 7
0
def preview_letter_template_by_notification_id(service_id, notification_id,
                                               file_type):
    if file_type not in ("pdf", "png"):
        raise InvalidRequest({"content": ["file_type must be pdf or png"]},
                             status_code=400)

    page = request.args.get("page")

    notification = get_notification_by_id(notification_id)

    template = dao_get_template_by_id(notification.template_id)

    if template.is_precompiled_letter:
        try:

            pdf_file = get_letter_pdf(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                "Error extracting requested page from PDF file for notification_id {} type {} {}"
                .format(notification_id, type(e), e),
                status_code=500,
            )

        content = base64.b64encode(pdf_file).decode("utf-8")
        overlay = request.args.get("overlay")
        page_number = page if page else "1"

        if overlay:
            path = "/precompiled/overlay.{}".format(file_type)
            query_string = "?page_number={}".format(
                page_number) if file_type == "png" else ""
            content = pdf_file
        elif file_type == "png":
            query_string = "?hide_notify=true" if page_number == "1" else ""
            path = "/precompiled-preview.png"
        else:
            path = None

        if file_type == "png":
            try:
                pdf_page = extract_page_from_pdf(BytesIO(pdf_file),
                                                 int(page_number) - 1)
                content = pdf_page if overlay else base64.b64encode(
                    pdf_page).decode("utf-8")
            except PdfReadError as e:
                raise InvalidRequest(
                    "Error extracting requested page from PDF file for notification_id {} type {} {}"
                    .format(notification_id, type(e), e),
                    status_code=500,
                )

        if path:
            url = current_app.config[
                "TEMPLATE_PREVIEW_API_HOST"] + path + query_string
            response_content = _get_png_preview_or_overlaid_pdf(
                url, content, notification.id, json=False)
        else:
            response_content = content
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version),
        }

        service = dao_fetch_service_by_id(service_id)
        letter_logo_filename = service.letter_branding and service.letter_branding.filename
        data = {
            "letter_contact_block": notification.reply_to_text,
            "template": template_for_letter_print,
            "values": notification.personalisation,
            "date": notification.created_at.isoformat(),
            "filename": letter_logo_filename,
        }

        url = "{}/preview.{}{}".format(
            current_app.config["TEMPLATE_PREVIEW_API_HOST"],
            file_type,
            "?page={}".format(page) if page else "",
        )
        response_content = _get_png_preview_or_overlaid_pdf(url,
                                                            data,
                                                            notification.id,
                                                            json=True)

    return jsonify({"content": response_content})