Exemple #1
0
def test_fill_with_radiobutton(template_with_radiobutton_stream, data_dict):
    elements = TemplateMiddleware().build_elements(
        template_with_radiobutton_stream)

    data_dict["radio_1"] = 0
    data_dict["radio_2"] = 1
    data_dict["radio_3"] = 2

    radio_button_tracker = {}

    for k, v in data_dict.items():
        if k in elements:
            elements[k].value = v

            if elements[k].type == ElementType.text:
                elements[k].font = TextConstants().global_font
                elements[k].font_size = TextConstants().global_font_size
                elements[k].font_color = TextConstants().global_font_color
                elements[k].text_x_offset = TextConstants(
                ).global_text_x_offset
                elements[k].text_y_offset = TextConstants(
                ).global_text_y_offset
                elements[k].text_wrap_length = TextConstants(
                ).global_text_wrap_length
            elements[k].validate_constants()
            elements[k].validate_value()
            elements[k].validate_text_attributes()

    result_stream = Filler().fill(template_with_radiobutton_stream, elements)

    assert result_stream != template_with_radiobutton_stream

    for element in TemplateCore().iterate_elements(result_stream):
        key = TemplateCore().get_element_key(element)

        if isinstance(data_dict[key], bool) or isinstance(data_dict[key], str):
            assert element[
                TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)
        else:
            assert element[TemplateConstants().parent_key][
                TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)

        if isinstance(data_dict[key], bool):
            assert element[TemplateConstants().checkbox_field_value_key] == (
                pdfrw.PdfName.Yes if data_dict[key] else pdfrw.PdfName.Off)
        elif isinstance(data_dict[key], int):
            if key not in radio_button_tracker:
                radio_button_tracker[key] = 0
            radio_button_tracker[key] += 1

            if data_dict[key] == radio_button_tracker[key] - 1:
                assert element[TemplateConstants().
                               checkbox_field_value_key] == BasePdfName(
                                   "/" + str(data_dict[key]), False)
            else:
                assert (element[TemplateConstants().checkbox_field_value_key]
                        == pdfrw.PdfName.Off)
def ast_to_pdf(asdl_ast):
    constructor_name = asdl_ast.production.constructor.name

    if constructor_name == 'PdfDict':
        pdict = {}
        for arg in asdl_ast['args'].value:
            # apply
            name = BasePdfName(asdl_ast['name'].value)
            if name in ['/Parent', '/P', '/Dest', '/Prev']:
                pass
            op = ast_to_pdf(asdl_ast['op'].value)

            pdict[name] = op

        x = PdfDict(pdict)

    elif constructor_name == 'PdfArray':
        parray = []
        for arg in asdl_ast['args'].value:
            args.append(ast_to_pdf(arg))

        x = PdfArray(pdfarray)

    elif constructor_name == 'PdfList':
        var = asdl_ast['value'].value

        x = PdfArray(list(var))

    elif constructor_name == 'PdfObject':
        var = asdl_ast['value'].value
        
        x = PdfObject(var)

    elif constructor_name == 'PdfStr':
        var = asdl_ast['value'].value
        
        x = PdfStr(var)

    elif constructor_name == 'BasePdfName':
        var = asdl_ast['value'].value
        
        x = BasePdfName(var)

    return x
Exemple #3
0
def test_simple_fill_with_radiobutton(template_with_radiobutton_stream,
                                      data_dict):
    data_dict["radio_1"] = 0
    data_dict["radio_2"] = 1
    data_dict["radio_3"] = 2

    radio_button_tracker = {}

    result_stream = Filler().simple_fill(template_with_radiobutton_stream,
                                         data_dict, True)

    assert result_stream != template_with_radiobutton_stream

    for element in TemplateCore().iterate_elements(result_stream):
        key = TemplateCore().get_element_key(element)

        if isinstance(data_dict[key], bool):
            assert element[TemplateConstants().checkbox_field_value_key] == (
                pdfrw.PdfName.Yes if data_dict[key] else pdfrw.PdfName.Off)
        elif isinstance(data_dict[key], int):
            if key not in radio_button_tracker:
                radio_button_tracker[key] = 0
            radio_button_tracker[key] += 1

            if data_dict[key] == radio_button_tracker[key] - 1:
                assert element[TemplateConstants().
                               checkbox_field_value_key] == BasePdfName(
                                   "/" + str(data_dict[key]), False)
            else:
                assert (element[TemplateConstants().checkbox_field_value_key]
                        == pdfrw.PdfName.Off)
        else:
            assert (element[TemplateConstants().text_field_value_key][1:-1] ==
                    data_dict[key])
        assert element[
            TemplateConstants().field_editable_key] != pdfrw.PdfObject(1)
Exemple #4
0
    def fill(
        template_stream: bytes,
        elements: Dict[str, "ElementMiddleware"],
        sejda: bool = False,
    ) -> bytes:
        """Fills a PDF using watermarks."""

        template_pdf = pdfrw.PdfReader(fdata=template_stream)

        texts_to_draw = {}
        text_watermarks = []

        radio_button_tracker = {}

        for page, _elements in (TemplateCore().get_elements_by_page(
                template_pdf, sejda).items()):
            texts_to_draw[page] = []
            text_watermarks.append(b"")
            for _element in _elements:
                key = TemplateCore().get_element_key(_element, sejda)

                update_dict = {
                    TemplateConstants().field_editable_key.replace("/", ""):
                    pdfrw.PdfObject(1)
                }
                if elements[key].type == ElementType.checkbox:
                    if sejda and elements[key].value is True:
                        texts_to_draw[page].append([
                            Utils().checkbox_radio_to_draw(elements[key]),
                            TemplateCore().get_draw_checkbox_radio_coordinates(
                                _element)[0],
                            TemplateCore().get_draw_checkbox_radio_coordinates(
                                _element)[1],
                        ])
                    else:
                        update_dict[TemplateConstants().
                                    checkbox_field_value_key.replace(
                                        "/", "")] = Utils().bool_to_checkbox(
                                            elements[key].value)
                elif elements[key].type == ElementType.radio:
                    if key not in radio_button_tracker:
                        radio_button_tracker[key] = 0
                    radio_button_tracker[key] += 1

                    if elements[key].value == radio_button_tracker[key] - 1:
                        if sejda:
                            texts_to_draw[page].append([
                                Utils().checkbox_radio_to_draw(elements[key]),
                                TemplateCore(
                                ).get_draw_checkbox_radio_coordinates(
                                    _element)[0],
                                TemplateCore(
                                ).get_draw_checkbox_radio_coordinates(_element)
                                [1],
                            ])
                        else:
                            _element.update(
                                pdfrw.PdfDict(
                                    **{
                                        TemplateConstants().checkbox_field_value_key.replace(
                                            "/", ""):
                                        BasePdfName(
                                            "/" +
                                            str(elements[key].value), False),
                                    }))

                    _element[TemplateConstants().parent_key].update(
                        pdfrw.PdfDict(
                            **{
                                TemplateConstants().field_editable_key.replace(
                                    "/", ""):
                                pdfrw.PdfObject(1)
                            }))
                    continue
                else:
                    texts_to_draw[page].append([
                        elements[key],
                        TemplateCore().get_draw_text_coordinates(_element)[0],
                        TemplateCore().get_draw_text_coordinates(_element)[1],
                    ])
                if sejda:
                    _element[TemplateConstants().parent_key].update(
                        pdfrw.PdfDict(**update_dict))
                else:
                    _element.update(pdfrw.PdfDict(**update_dict))

        for page, texts in texts_to_draw.items():
            _watermarks = WatermarkCore().create_watermarks_and_draw(
                template_stream, page, "text", texts)
            for i, watermark in enumerate(_watermarks):
                if watermark:
                    text_watermarks[i] = watermark

        return WatermarkCore().merge_watermarks_with_pdf(
            Utils().generate_stream(template_pdf), text_watermarks)
Exemple #5
0
    def simple_fill(
        template_stream: bytes,
        data: Dict[str, Union[str, bool, int]],
        editable: bool,
    ) -> bytes:
        """Fills a PDF form in simple mode."""

        template_pdf = pdfrw.PdfReader(fdata=template_stream)
        data = Utils().bool_to_checkboxes(data)

        radio_button_tracker = {}

        for element in TemplateCore().iterate_elements(template_pdf):
            key = TemplateCore().get_element_key(element)

            if key in data.keys():
                update_dict = {}
                if data[key] in [
                        pdfrw.PdfName.Yes,
                        pdfrw.PdfName.Off,
                ]:
                    update_dict = {
                        TemplateConstants().checkbox_field_value_key.replace(
                            "/", ""):
                        data[key]
                    }
                elif isinstance(data[key], int):
                    if key not in radio_button_tracker:
                        radio_button_tracker[key] = 0
                    radio_button_tracker[key] += 1

                    if data[key] == radio_button_tracker[key] - 1:
                        element.update(
                            pdfrw.PdfDict(
                                **{
                                    TemplateConstants().checkbox_field_value_key.replace(
                                        "/", ""):
                                    BasePdfName("/" + str(data[key]), False),
                                }))

                        if not editable:
                            element[TemplateConstants().parent_key].update(
                                pdfrw.PdfDict(
                                    **{
                                        TemplateConstants().field_editable_key.replace(
                                            "/", ""):
                                        pdfrw.PdfObject(1)
                                    }))
                        continue
                else:
                    update_dict = {
                        TemplateConstants().text_field_value_key.replace(
                            "/", ""):
                        data[key]
                    }

                if not editable:
                    update_dict[TemplateConstants().field_editable_key.replace(
                        "/", "")] = pdfrw.PdfObject(1)

                element.update(pdfrw.PdfDict(**update_dict))

        return Utils().generate_stream(template_pdf)