Exemple #1
0
 def _build_billing_and_shipping_information(self) -> LayoutElement:
     table_001: Table = Table(number_of_rows=6, number_of_columns=2)
     table_001.add(
         Paragraph(
             "BILL TO",
             background_color=HexColor("016934"),
             font_color=X11Color("White"),
         ))
     table_001.add(
         Paragraph(
             "SHIP TO",
             background_color=HexColor("016934"),
             font_color=X11Color("White"),
         ))
     table_001.add(Paragraph("[Recipient Name]"))  # BILLING
     table_001.add(Paragraph("[Recipient Name]"))  # SHIPPING
     table_001.add(Paragraph("[Company Name]"))  # BILLING
     table_001.add(Paragraph("[Company Name]"))  # SHIPPING
     table_001.add(Paragraph("[Street Address]"))  # BILLING
     table_001.add(Paragraph("[Street Address]"))  # SHIPPING
     table_001.add(Paragraph("[City, State, ZIP Code]"))  # BILLING
     table_001.add(Paragraph("[City, State, ZIP Code]"))  # SHIPPING
     table_001.add(Paragraph("[Phone]"))  # BILLING
     table_001.add(Paragraph("[Phone]"))  # SHIPPING
     table_001.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2),
                                        Decimal(2))
     table_001.no_borders()
     return table_001
Exemple #2
0
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_circle_annotation(
            rectangle=(Decimal(128), Decimal(128), Decimal(64), Decimal(64)),
            interior_color=X11Color("Plum"),
            color=X11Color("Crimson"),
        )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
    def test_add_circle_annotation(self):

        # create output directory if it does not exist yet
        if not self.output_file.parent.exists():
            self.output_file.parent.mkdir()

        # attempt to read PDF
        doc = None
        with open(self.input_file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_circle_annotation(
            rectangle=Rectangle(Decimal(128), Decimal(128), Decimal(64), Decimal(64)),
            stroke_color=X11Color("Plum"),
            fill_color=X11Color("Crimson"),
        )

        # attempt to store PDF
        with open(self.output_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(self.output_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
    def test_write_document(self):

        sentences = [
            "THE BOAT WILL ARRIVE ON MONDAY",
            "SHE LIVES AT THE HOUSE WITH THE BLUE DOOR",
            "A FRIEND IN NEED IS A FRIEND INDEED",
            "AN APPLE A DAY KEEPS THE DOCTOR AWAY",
        ]

        pdf = Document()
        page = Page()
        pdf.append_page(page)

        # layout
        layout = SingleColumnLayout(page)

        # add title
        layout.add(
            Paragraph(
                "Secret Code Puzzle",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            )
        )

        # add text
        layout.add(
            Paragraph(
                """
                There are three riddles below written in a secret code.
                Can you unravel them?
                Once you have, copy the sentence on the line underneath the code.
                
                Hint: Each letter of the alphabet has been replaced by a number. 
                All the riddles use the same code.
                """,
                respect_newlines_in_text=True,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            )
        )

        # add grid
        for s in sentences:
            layout.add(self._build_table_for_sentence(s))
            layout.add(Paragraph(" ", respect_spaces_in_text=True))

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / ("output.pdf")

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()

        # add page to document
        pdf.append_page(page)

        # set layout
        layout = MultiColumnLayout(page)

        # add chart
        layout.add(Chart(self._create_plot()))

        layout.switch_to_next_column()

        # add Heading
        layout.add(
            Heading(
                "3D Density Chart",
                font_color=X11Color("YellowGreen"),
                font_size=Decimal(20),
            )
        )
        layout.add(
            Paragraph(
                "The mplot3D toolkit of Matplotlib allows to easily create 3D scatterplots. "
                "Note that most of the customisations presented in the Scatterplot section will work in 3D as well. "
                "The result can be a bit disappointing since each marker is represented as a dot, not as a sphere.."
            )
        )
        layout.add(
            Paragraph(
                "Check out https://python-graph-gallery.com/ for more wonderful examples of plots in Python."
            )
        )
        layout.add(
            Barcode(
                data="https://python-graph-gallery.com/",
                type=BarcodeType.QR,
                stroke_color=X11Color("YellowGreen"),
            )
        )

        # write
        file = self.output_dir / "output.pdf"
        with open(file, "wb") as pdf_file_handle:
            PDF.dumps(pdf_file_handle, pdf)

        return True
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create document
        pdf = Document()

        # add page
        page = Page()
        pdf.append_page(page)

        layout = SingleColumnLayout(page)

        # write title
        layout.add(
            Paragraph("Nonogram",
                      font_size=Decimal(20),
                      font_color=X11Color("YellowGreen")))

        # write text
        layout.add(
            Paragraph(
                """
            Nonograms, also known as Paint by Numbers, Picross, Griddlers, Pic-a-Pix, and various other names, 
            are picture logic puzzles in which cells in a grid must be colored or left blank according to numbers 
            at the side of the grid to reveal a hidden picture. 
            In this puzzle type, the numbers are a form of discrete tomography that measures how many 
            unbroken lines of filled-in squares there are in any given row or column. 
            For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, 
            in that order, with at least one blank square between successive sets.
            """,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        # write nonogram
        ng = Nonogram(
            # "https://i.pinimg.com/originals/f8/23/88/f823882e7c5fa42790e78f43ecf7e8bf.jpg"
            "https://cdn.shopify.com/s/files/1/2123/8425/products/166422700-LRG_242a4c8b-cad5-476e-afd1-c8b882d48fc2_530x.jpg"
        )
        layout.add(ng)

        # determine output location
        out_file = self.output_dir / ("output.pdf")

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
Exemple #7
0
    def _do_layout_without_padding(
        self, page: Page, bounding_box: Rectangle
    ) -> Rectangle:

        # scale to fit
        self.scale_down(bounding_box.width, bounding_box.height)

        # translate points to fit in box
        self.translate_to_align(
            bounding_box.x, bounding_box.y + bounding_box.height - self.get_height()
        )

        # write content
        stroke_rgb = (self.stroke_color or X11Color("Black")).to_rgb()
        fill_rgb = (self.fill_color or X11Color("White")).to_rgb()
        COLOR_MAX = Decimal(255.0)
        content = "q %f %f %f RG  %f %f %f rg %f w " % (
            Decimal(stroke_rgb.red / COLOR_MAX),
            Decimal(stroke_rgb.green / COLOR_MAX),
            Decimal(stroke_rgb.blue / COLOR_MAX),
            Decimal(fill_rgb.red / COLOR_MAX),
            Decimal(fill_rgb.green / COLOR_MAX),
            Decimal(fill_rgb.blue / COLOR_MAX),
            self.line_width,
        )
        content += "%f %f m " % (self.points[0][0], self.points[0][1])
        for p in self.points:
            content += " %f %f l " % (p[0], p[1])

        operator: str = "B"
        if self.stroke_color is None:
            operator = "F"
        if self.fill_color is None:
            operator = "S"
        content += " %s " % operator
        content += " Q"

        # append to page
        self._append_to_content_stream(page, content)

        # calculate bounding box
        layout_rect = Rectangle(
            bounding_box.x,
            bounding_box.y + bounding_box.height - self.get_height(),
            self.get_width(),
            self.get_height(),
        )

        # set bounding box
        self.set_bounding_box(layout_rect)

        # return
        return layout_rect
Exemple #8
0
 def __init__(
     self,
     text: str,
     respect_newlines_in_text: bool = False,
     respect_spaces_in_text: bool = False,
     font: Union[Font, str] = "Helvetica",
     font_size: Decimal = Decimal(12),
     text_alignment: Alignment = Alignment.LEFT,
     vertical_alignment: Alignment = Alignment.TOP,
     horizontal_alignment: Alignment = Alignment.LEFT,
     font_color: Color = X11Color("Black"),
     border_top: bool = False,
     border_right: bool = False,
     border_bottom: bool = False,
     border_left: bool = False,
     border_color: Color = X11Color("Black"),
     border_width: Decimal = Decimal(1),
     padding_top: Decimal = Decimal(0),
     padding_right: Decimal = Decimal(0),
     padding_bottom: Decimal = Decimal(0),
     padding_left: Decimal = Decimal(0),
     background_color: typing.Optional[Color] = None,
     parent: typing.Optional["LayoutElement"] = None,
 ):
     super().__init__(
         text=text,
         font=font,
         font_size=font_size,
         vertical_alignment=vertical_alignment,
         horizontal_alignment=horizontal_alignment,
         font_color=font_color,
         border_top=border_top,
         border_right=border_right,
         border_bottom=border_bottom,
         border_left=border_left,
         border_color=border_color,
         border_width=border_width,
         padding_top=padding_top,
         padding_right=padding_right,
         padding_bottom=padding_bottom,
         padding_left=padding_left,
         background_color=background_color,
         parent=parent,
     )
     self.respect_newlines_in_text = respect_newlines_in_text
     self.respect_spaces_in_text = respect_spaces_in_text
     assert text_alignment in [
         Alignment.LEFT,
         Alignment.CENTERED,
         Alignment.RIGHT,
         Alignment.JUSTIFIED,
     ]
     self.text_alignment = text_alignment
    def test_write_document(self):

        pdf = Document()
        page = Page()
        pdf.append_page(page)

        # layout
        layout = MultiColumnLayout(page, number_of_columns=2)

        #
        # add title
        layout.add(
            Paragraph(
                """
                Help the person find their way home by colouring in a path through the stepping stones by making a sentence.  
                A really fun way to practice the alphabet!
                """,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        seq = [x for x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
        layout.add(
            SteppingStonePuzzle(
                seq,
                seq,
                "https://icons.iconarchive.com/icons/chanut/role-playing/128/King-icon.png",
                "https://icons.iconarchive.com/icons/chanut/role-playing/128/Castle-icon.png",
            ))

        # go to next column
        layout.switch_to_next_column()

        # add title
        layout.add(
            Paragraph(
                "Stepping Stones",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            ))

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / ("output.pdf")

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)
Exemple #10
0
 def __init__(
     self,
     text: str,
     font: Union[Font, str] = "Helvetica",
     font_size: Decimal = Decimal(12),
     font_color: Color = X11Color("Black"),
     border_top: bool = False,
     border_right: bool = False,
     border_bottom: bool = False,
     border_left: bool = False,
     border_color: Color = X11Color("Black"),
     border_width: Decimal = Decimal(1),
     padding_top: Decimal = Decimal(0),
     padding_right: Decimal = Decimal(0),
     padding_bottom: Decimal = Decimal(0),
     padding_left: Decimal = Decimal(0),
     vertical_alignment: Alignment = Alignment.TOP,
     horizontal_alignment: Alignment = Alignment.LEFT,
     background_color: typing.Optional[Color] = None,
     parent: typing.Optional["LayoutElement"] = None,
 ):
     super().__init__(
         border_top=border_top,
         border_right=border_right,
         border_bottom=border_bottom,
         border_left=border_left,
         border_color=border_color,
         border_width=border_width,
         padding_top=padding_top,
         padding_right=padding_right,
         padding_bottom=padding_bottom,
         padding_left=padding_left,
         vertical_alignment=vertical_alignment,
         horizontal_alignment=horizontal_alignment,
         background_color=background_color,
         parent=parent,
     )
     self.text = text
     if isinstance(font, str):
         self.font: Font = FontType1()
         font_to_copy: typing.Optional[Font] = AdobeFontMetrics.get(font)
         self.font[Name("Encoding")] = Name("WinAnsiEncoding")
         assert font_to_copy
         for k, v in font_to_copy.items():
             self.font[k] = v
         assert self.font
     else:
         self.font = font
     self.font_color = font_color
     self.font_size = font_size
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()

        # add page to document
        pdf.append_page(page)

        # set layout
        layout = MultiColumnLayout(page)

        # add chart
        layout.add(Chart(self._create_plot()))

        layout.switch_to_next_column()

        # add Heading
        layout.add(
            Heading("3D Plot",
                    font_color=X11Color("Orange"),
                    font_size=Decimal(20)))
        layout.add(
            Paragraph(
                "Demonstrates plotting a 3D surface colored with the coolwarm color map. "
                "The surface can be made opaque by using antialiased=False."))
        layout.add(
            Paragraph(
                "Check out https://python-graph-gallery.com/ for more wonderful examples of plots in Python."
            ))
        layout.add(
            Barcode(
                data="https://python-graph-gallery.com/",
                type=BarcodeType.QR,
                stroke_color=X11Color("Orange"),
            ))

        # write
        file = self.output_dir / "output.pdf"
        with open(file, "wb") as pdf_file_handle:
            PDF.dumps(pdf_file_handle, pdf)

        return True
Exemple #12
0
 def __init__(
     self,
     text: str,
     outline_text: typing.Optional[str] = None,
     outline_level: int = 0,
     respect_newlines_in_text: bool = False,
     font: Union[Font, str] = "Helvetica",
     font_size: Decimal = Decimal(12),
     horizontal_alignment: Alignment = Alignment.LEFT,
     vertical_alignment: Alignment = Alignment.TOP,
     font_color: Color = X11Color("Black"),
     border_top: bool = False,
     border_right: bool = False,
     border_bottom: bool = False,
     border_left: bool = False,
     border_color: Color = X11Color("Black"),
     border_width: Decimal = Decimal(1),
     padding_top: Decimal = Decimal(0),
     padding_right: Decimal = Decimal(0),
     padding_bottom: Decimal = Decimal(0),
     padding_left: Decimal = Decimal(0),
     background_color: typing.Optional[Color] = None,
     parent: typing.Optional["LayoutElement"] = None,
 ):
     super().__init__(
         text=text,
         respect_newlines_in_text=respect_newlines_in_text,
         font=font,
         font_size=font_size,
         vertical_alignment=vertical_alignment,
         horizontal_alignment=horizontal_alignment,
         font_color=font_color,
         border_top=border_top,
         border_right=border_right,
         border_bottom=border_bottom,
         border_left=border_left,
         border_color=border_color,
         border_width=border_width,
         padding_top=padding_top,
         padding_right=padding_right,
         padding_bottom=padding_bottom,
         padding_left=padding_left,
         background_color=background_color,
         parent=parent,
     )
     self.outline_text = outline_text or text
     self.outline_level = outline_level
     self.has_added_outline = False
Exemple #13
0
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_redact_annotation(
            overlay_text="Lorem Ipsum",
            repeat_overlay_text=True,
            fill_color=X11Color("AliceBlue"),
            rectangle=Rectangle(Decimal(72.86), Decimal(486.82), Decimal(129),
                                Decimal(13)),
        )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #14
0
    def test_add_polygon_annotation(self):

        # create output directory if it does not exist yet
        if not self.output_file.parent.exists():
            self.output_file.parent.mkdir()

        # attempt to read PDF
        doc = None
        with open(self.input_file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_polygon_annotation(
            points=[
                (Decimal(72), Decimal(390)),
                (Decimal(242), Decimal(500)),
                (Decimal(156), Decimal(390)),
            ],
            stroke_color=X11Color("Crimson"),
        )

        # attempt to store PDF
        with open(self.output_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(self.output_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #15
0
    def test_add_polyline_annotation_using_lineart_factory(self):

        # create output directory if it does not exist yet
        if not self.output_file.parent.exists():
            self.output_file.parent.mkdir()

        # attempt to read PDF
        doc = None
        with open(self.input_file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_polyline_annotation(
            points=LineArtFactory.droplet(
                Rectangle(Decimal(100), Decimal(100), Decimal(100),
                          Decimal(100))),
            stroke_color=X11Color("Crimson"),
        )

        # attempt to store PDF
        with open(self.output_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(self.output_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #16
0
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_polygon_annotation(
            points=LineArtFactory.sticky_note(
                Rectangle(Decimal(128), Decimal(128), Decimal(64),
                          Decimal(64))),
            stroke_color=X11Color("PowderBlue"),
        )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #17
0
 def __init__(
     self,
     border_top: bool = False,
     border_right: bool = False,
     border_bottom: bool = False,
     border_left: bool = False,
     border_color: Color = X11Color("Black"),
     border_width: Decimal = Decimal(1),
     padding_top: Decimal = Decimal(0),
     padding_right: Decimal = Decimal(0),
     padding_bottom: Decimal = Decimal(0),
     padding_left: Decimal = Decimal(0),
     background_color: typing.Optional[Color] = None,
     parent: typing.Optional["LayoutElement"] = None,
 ):
     super(UnorderedList, self).__init__(
         border_top=border_top,
         border_right=border_right,
         border_bottom=border_bottom,
         border_left=border_left,
         border_color=border_color,
         border_width=border_width,
         padding_top=padding_top,
         padding_right=padding_right,
         padding_bottom=padding_bottom,
         padding_left=padding_left,
         background_color=background_color,
         parent=parent,
     )
     self.parent = parent
     self.items: typing.List[LayoutElement] = []
Exemple #18
0
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_text_annotation(
            contents="The quick brown fox ate the lazy mouse",
            rectangle=Rectangle(Decimal(128), Decimal(128), Decimal(64), Decimal(64)),
            name_of_icon="Key",
            open=True,
            color=X11Color("Orange"),
        )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
    def test_add_link_annotation(self):

        # create output directory if it does not exist yet
        if not self.output_file.parent.exists():
            self.output_file.parent.mkdir()

        # attempt to read PDF
        doc = None
        with open(self.input_file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_link_annotation(
            page=Decimal(0),
            destination_type=DestinationType.FIT,
            color=X11Color("Red"),
            rectangle=Rectangle(Decimal(128), Decimal(128), Decimal(64), Decimal(64)),
        )

        # attempt to store PDF
        with open(self.output_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(self.output_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #20
0
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_stamp_annotation(
            name="Confidential",
            contents="Approved by Joris Schellekens",
            color=X11Color("White"),
            rectangle=(Decimal(128), Decimal(128), Decimal(32), Decimal(64)),
        )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #21
0
    def test_add_rubber_stamp_annotation(self):

        # create output directory if it does not exist yet
        if not self.output_file.parent.exists():
            self.output_file.parent.mkdir()

        # attempt to read PDF
        doc = None
        with open(self.input_file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # add annotation
        doc.get_page(0).append_stamp_annotation(
            name=RubberStampAnnotationIconType.CONFIDENTIAL,
            contents="Approved by Joris Schellekens",
            color=X11Color("Red"),
            rectangle=Rectangle(Decimal(128), Decimal(56), Decimal(132),
                                Decimal(58)),
        )

        # attempt to store PDF
        with open(self.output_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(self.output_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create document
        pdf = Document()

        # add page
        page = Page()
        pdf.append_page(page)

        Paragraph(
            "Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious volume of forgotten lore",
            font_size=Decimal(20),
            horizontal_alignment=Alignment.RIGHT,
        ).layout(
            page,
            Rectangle(Decimal(20), Decimal(600), Decimal(500), Decimal(124)),
        )

        # add rectangle annotation
        page.append_square_annotation(
            stroke_color=X11Color("Red"),
            rectangle=Rectangle(Decimal(20), Decimal(600), Decimal(500),
                                Decimal(124)),
        )

        # determine output location
        out_file = self.output_dir / "output.pdf"

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)
    def _build_table_for_sentence(self, sentence: str) -> Table:
        t = Table(number_of_columns=len(sentence), number_of_rows=3)
        for c in sentence:
            if c in [".", "?", "!", ",", " "]:
                t.add(
                    TableCell(
                        Paragraph(c, respect_spaces_in_text=True),
                        background_color=X11Color("SlateGray"),
                    )
                )
            else:
                num = ord(c.upper()) - ord("A") + 1
                t.add(
                    Paragraph(
                        str(num),
                        font_size=Decimal(6),
                        text_alignment=Alignment.CENTERED,
                    )
                )

        for c in sentence:
            t.add(Paragraph(" ", respect_spaces_in_text=True))

        for c in sentence:
            t.add(
                TableCell(
                    Paragraph(" ", respect_spaces_in_text=True),
                    border_top=False,
                    border_left=False,
                    border_right=False,
                )
            )

        t.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2), Decimal(2))
        return t
Exemple #24
0
    def append_highlight_annotation(
        self,
        rectangle: Rectangle,
        color: Color = X11Color("Yellow"),
        contents: Optional[str] = None,
    ) -> "Page":
        # create generic annotation
        annot = self._create_annotation(rectangle=rectangle,
                                        color=color,
                                        contents=contents)

        # (Required) The type of annotation that this dictionary describes; shall
        # be Highlight, Underline, Squiggly, or StrikeOut for a highlight,
        # underline, squiggly-underline, or strikeout annotation, respectively.
        annot[Name("Subtype")] = Name("Highlight")

        # (Required) An array of 8 × n numbers specifying the coordinates of n
        # quadrilaterals in default user space. Each quadrilateral shall
        # encompasses a word or group of contiguous words in the text
        # underlying the annotation. The coordinates for each quadrilateral shall
        # be given in the order
        # x1 y1 x2 y2 x3 y3 x4 y4
        annot[Name("QuadPoints")] = List().set_can_be_referenced(
            False)  # type: ignore [attr-defined]
        # x1, y1
        annot["QuadPoints"].append(pDecimal(rectangle.get_x()))
        annot["QuadPoints"].append(pDecimal(rectangle.get_y()))
        # x4, y4
        annot["QuadPoints"].append(pDecimal(rectangle.get_x()))
        annot["QuadPoints"].append(
            pDecimal(rectangle.get_y() + rectangle.get_height()))
        # x2, y2
        annot["QuadPoints"].append(
            pDecimal(rectangle.get_x() + rectangle.get_width()))
        annot["QuadPoints"].append(pDecimal(rectangle.get_y()))
        # x3, y3
        annot["QuadPoints"].append(
            pDecimal(rectangle.get_x() + rectangle.get_width()))
        annot["QuadPoints"].append(
            pDecimal(rectangle.get_y() + rectangle.get_height()))

        # border
        annot[Name("Border")] = List().set_can_be_referenced(
            False)  # type: ignore [attr-defined]
        annot["Border"].append(pDecimal(0))
        annot["Border"].append(pDecimal(0))
        annot["Border"].append(pDecimal(1))

        # CA
        annot[Name("CA")] = pDecimal(1)

        # append to /Annots
        if "Annots" not in self:
            self[Name("Annots")] = List()
        assert isinstance(self["Annots"], List)
        self["Annots"].append(annot)

        # return
        return self
Exemple #25
0
    def __init__(
        self,
        border_top: bool = False,
        border_right: bool = False,
        border_bottom: bool = False,
        border_left: bool = False,
        border_color: Color = X11Color("Black"),
        border_width: Decimal = Decimal(1),
        padding_top: Decimal = Decimal(0),
        padding_right: Decimal = Decimal(0),
        padding_bottom: Decimal = Decimal(0),
        padding_left: Decimal = Decimal(0),
        horizontal_alignment: Alignment = Alignment.LEFT,
        vertical_alignment: Alignment = Alignment.TOP,
        background_color: typing.Optional[Color] = None,
        parent: typing.Optional["LayoutElement"] = None,
    ):
        # borders
        self.border_top = border_top
        self.border_right = border_right
        self.border_bottom = border_bottom
        self.border_left = border_left
        assert border_width >= 0
        self.border_width = border_width
        self.border_color = border_color

        # padding
        assert padding_top >= 0
        assert padding_right >= 0
        assert padding_bottom >= 0
        assert padding_left >= 0
        self.padding_top = padding_top
        self.padding_right = padding_right
        self.padding_bottom = padding_bottom
        self.padding_left = padding_left

        # alignment
        assert horizontal_alignment in [
            Alignment.LEFT,
            Alignment.CENTERED,
            Alignment.RIGHT,
            Alignment.JUSTIFIED,
        ]
        assert vertical_alignment in [
            Alignment.TOP, Alignment.MIDDLE, Alignment.BOTTOM
        ]
        self.horizontal_alignment = horizontal_alignment
        self.vertical_alignment = vertical_alignment

        # background color
        self.background_color = background_color

        # linkage (for lists, tables, etc)
        self.parent = parent

        # layout
        self.bounding_box: typing.Optional[Rectangle] = None
    def _test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # determine output location
        out_file = self.output_dir / (file.stem + "_out.pdf")

        # attempt to read PDF
        doc = None
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle)

        # determine free space
        space_finder = FreeSpaceFinder(doc.get_page(0))

        # debug purposes
        if self.in_debug:
            for i in range(0, len(space_finder.grid)):
                for j in range(0, len(space_finder.grid[i])):
                    if space_finder.grid[i][j]:
                        continue
                    w = Decimal(space_finder.grid_resolution)
                    x = Decimal(i) * w
                    y = Decimal(j) * w
                    doc.get_page(0).append_square_annotation(
                        Rectangle(x, y, w, w), stroke_color=X11Color("Salmon"))

        # add annotation
        w, h = doc.get_page(0).get_page_info().get_size()
        free_rect = space_finder.find_free_space(
            Rectangle(
                Decimal(w / Decimal(2)),
                Decimal(h * Decimal(2)),
                Decimal(64),
                Decimal(64),
            ))
        if free_rect is not None:
            doc.get_page(0).append_square_annotation(
                rectangle=free_rect,
                stroke_color=HexColor("#F75C03"),
                fill_color=HexColor("#04A777"),
            )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create document
        pdf = Document()

        # add page
        page = Page()
        pdf.append_page(page)

        layout = MultiColumnLayout(page, number_of_columns=2)

        layout.add(Heading("The Raven", font_size=Decimal(20)))
        layout.add(
            Paragraph(
                "Edgar Allen Poe",
                font="Helvetica-Oblique",
                font_size=Decimal(8),
                font_color=X11Color("SteelBlue"),
            )
        )
        for i in range(0, 100):
            layout.add(
                Heading("Heading %d" % i, font_size=Decimal(20), outline_level=1)
            )
            for _ in range(0, random.choice([10, 20, 3])):
                layout.add(
                    Paragraph(
                        "Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore- While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. Tis some visitor, I muttered, tapping at my chamber door- Only this and nothing more.",
                        font_size=Decimal(12),
                        font_color=X11Color("SlateGray"),
                        horizontal_alignment=Alignment.LEFT,
                    )
                )

        # determine output location
        out_file = self.output_dir / "output.pdf"

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create document
        pdf = Document()

        # add page
        page = Page()
        pdf.append_page(page)
        layout = SingleColumnLayout(page)

        # title
        layout.add(
            Paragraph(
                "Lissajours Line Art",
                font_size=Decimal(20),
                font_color=X11Color("Blue"),
            ))

        # table
        N = 7
        fill_colors = [
            HSVColor(Decimal(x / N), Decimal(1), Decimal(1))
            for x in range(0, N)
        ]
        stroke_colors = [HSVColor.darker(x) for x in fill_colors]
        fixed_bb = Rectangle(Decimal(0), Decimal(0), Decimal(100),
                             Decimal(100))
        t = Table(number_of_rows=N, number_of_columns=N)
        for i in range(0, N):
            for j in range(0, N):
                t.add(
                    Shape(
                        LineArtFactory.lissajours(fixed_bb, i + 1, j + 1),
                        fill_color=fill_colors[(i + j) % N],
                        stroke_color=stroke_colors[(i + j) % N],
                        line_width=Decimal(2),
                    ))

        t.set_padding_on_all_cells(Decimal(10), Decimal(10), Decimal(10),
                                   Decimal(10))
        layout.add(t)

        # determine output location
        out_file = self.output_dir / ("output.pdf")

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
    def test_document(self, file):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # get text
        txt_ground_truth_file = self.input_dir / (file.stem + ".txt")
        txt_ground_truth = ""
        with open(txt_ground_truth_file, "r") as txt_ground_truth_file_handle:
            txt_ground_truth = txt_ground_truth_file_handle.read()

        words = [x for x in re.split("[^a-zA-Z]+", txt_ground_truth) if len(x) > 5]
        w = words[5] if len(words) > 5 else None

        if w is None:
            return True

        # determine output location
        out_file = self.output_dir / (file.stem + "_" + w + "_out.pdf")

        # attempt to read PDF
        doc = None
        l = RegularExpressionTextExtraction(w)
        with open(file, "rb") as in_file_handle:
            print("\treading (1) ..")
            doc = PDF.loads(in_file_handle, [l])

        # add annotation
        print(
            "\tAdding %d annotations"
            % len(l.get_matched_text_render_info_events_per_page(0))
        )
        for e in l.get_matched_text_render_info_events_per_page(0):
            baseline = e.get_baseline()
            doc.get_page(0).append_square_annotation(
                rectangle=Rectangle(
                    Decimal(baseline.x0),
                    Decimal(baseline.y0 - 2),
                    Decimal(baseline.x1 - baseline.x0),
                    Decimal(12),
                ),
                stroke_color=X11Color("Firebrick"),
            )

        # attempt to store PDF
        with open(out_file, "wb") as out_file_handle:
            print("\twriting ..")
            PDF.dumps(out_file_handle, doc)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            print("\treading (2) ..")
            doc = PDF.loads(in_file_handle)

        return True
Exemple #30
0
    def test_write_document(self):

        # create output directory if it does not exist yet
        if not self.output_dir.exists():
            self.output_dir.mkdir()

        # create document
        pdf = Document()

        bb = Rectangle(Decimal(20), Decimal(600), Decimal(500), Decimal(124))
        for va in [Alignment.TOP, Alignment.MIDDLE, Alignment.BOTTOM]:
            for ha in [Alignment.LEFT, Alignment.CENTERED, Alignment.RIGHT]:
                page = Page()
                pdf.append_page(page)
                Paragraph(
                    "%s %s  - Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious volume of forgotten lore"
                    % (str(va), str(ha)),
                    font_size=Decimal(20),
                    vertical_alignment=va,
                    horizontal_alignment=ha,
                    padding_top=Decimal(5),
                    padding_right=Decimal(5),
                    padding_bottom=Decimal(5),
                    padding_left=Decimal(5),
                    background_color=X11Color("Salmon"),
                ).layout(
                    page,
                    bb,
                )

                # add rectangle annotation
                page.append_square_annotation(
                    stroke_color=X11Color("Red"),
                    rectangle=bb,
                )

        # determine output location
        out_file = self.output_dir / "output.pdf"

        # attempt to store PDF
        with open(out_file, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)