コード例 #1
0
    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
コード例 #2
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()

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

        ChunkOfText(
            "é",
            font_size=Decimal(24),
        ).layout(
            page,
            Rectangle(Decimal(100), Decimal(600), Decimal(100), Decimal(100)))

        # 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)
コード例 #3
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
コード例 #4
0
 def _build_invoice_information(self) -> LayoutElement:
     table_001: Table = Table(number_of_rows=5, number_of_columns=3)
     table_001.add(Paragraph("[Street Address]"))
     table_001.add(
         Paragraph("Date",
                   font="Helvetica-Bold",
                   horizontal_alignment=Alignment.RIGHT))
     now = datetime.now()
     table_001.add(Paragraph("%d/%d/%d" % (now.day, now.month, now.year)))
     table_001.add(Paragraph("[City, State, ZIP Code]"))
     table_001.add(
         Paragraph("Invoice #",
                   font="Helvetica-Bold",
                   horizontal_alignment=Alignment.RIGHT))
     table_001.add(Paragraph("%d" % random.randint(1000, 10000)))
     table_001.add(Paragraph("[Phone]"))
     table_001.add(
         Paragraph("Due Date",
                   font="Helvetica-Bold",
                   horizontal_alignment=Alignment.RIGHT))
     table_001.add(Paragraph("%d/%d/%d" % (now.day, now.month, now.year)))
     table_001.add(Paragraph("[Email Address]"))
     table_001.add(Paragraph(" "))
     table_001.add(Paragraph(" "))
     table_001.add(Paragraph("[Company Website]"))
     table_001.add(Paragraph(" "))
     table_001.add(Paragraph(" "))
     table_001.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2),
                                        Decimal(2))
     table_001.no_borders()
     return table_001
コード例 #5
0
    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)
コード例 #6
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()

        # 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)
コード例 #7
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()

        # 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)
コード例 #8
0
 def _add_image_to_table(self, url: str, table: Table):
     im = PILImage.open(requests.get(
         url,
         stream=True,
     ).raw)
     table.add(
         Image(
             im,
             width=Decimal(128),
             height=Decimal(128),
             horizontal_alignment=Alignment.CENTERED,
         ))
コード例 #9
0
 def insert_page(
     self,
     page: Page,
     index: typing.Optional[int] = None
 ) -> "Document":  # type: ignore [name-defined]
     """
     This method appends a page (from another Document) to this Document at a given index
     """
     # build XRef
     if "XRef" not in self:
         self[Name("XRef")] = PlainTextXREF()
         self[Name("XRef")].set_parent(self)
     # build Trailer
     if "Trailer" not in self["XRef"]:
         self["XRef"][Name("Trailer")] = Dictionary()
         self["XRef"][Name("Size")] = Decimal(0)
         self["XRef"]["Trailer"].set_parent(self["XRef"])
     # build Root
     if "Root" not in self["XRef"]["Trailer"]:
         self["XRef"]["Trailer"][Name("Root")] = Dictionary()
         self["XRef"]["Trailer"]["Root"].set_parent(self["XRef"]["Trailer"])
     # build Pages
     if "Pages" not in self["XRef"]["Trailer"]["Root"]:
         self["XRef"]["Trailer"][Name("Root")][Name("Pages")] = Dictionary()
         self["XRef"]["Trailer"][Name("Root")][Name("Pages")][Name(
             "Count")] = Decimal(0)
         self["XRef"]["Trailer"][Name("Root")][Name("Pages")][Name(
             "Kids")] = List()
         self["XRef"]["Trailer"][Name("Root")][Name("Pages")][Name(
             "Type")] = Name("Pages")
         self["XRef"]["Trailer"]["Root"]["Pages"].set_parent(
             self["XRef"]["Trailer"]["Root"])
         self["XRef"]["Trailer"]["Root"]["Pages"]["Kids"].set_parent(
             self["XRef"]["Trailer"]["Root"]["Pages"])
     # update /Kids
     kids = self["XRef"]["Trailer"]["Root"]["Pages"]["Kids"]
     assert kids is not None
     assert isinstance(kids, List)
     if index is None:
         index = len(kids)
     kids.insert(index, page)
     # update /Count
     prev_count = self["XRef"]["Trailer"]["Root"]["Pages"]["Count"]
     self["XRef"]["Trailer"]["Root"]["Pages"][Name("Count")] = Decimal(
         prev_count + 1)
     # set /Parent
     page[Name("Parent")] = self["XRef"]["Trailer"]["Root"]["Pages"]
     page.set_parent(kids)  # type: ignore [attr-defined]
     # return
     return self
コード例 #10
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 empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()

        # add page to document
        pdf.append_page(page)

        # set layout
        layout = SingleColumnLayout(page)

        # add barcode
        layout.add(
            Barcode(
                data="123456789128",
                type=BarcodeType.CODE_128,
                width=Decimal(128),
                stroke_color=HexColor("#080708"),
            ))

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

        return True
コード例 #11
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 empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()

        # add page to document
        pdf.append_page(page)

        # add Image
        layout = SingleColumnLayout(page)

        # add image
        im = PILImage.open(
            requests.get(
                "https://images.unsplash.com/photo-1597826368522-9f4cb5a6ba48?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw",
                stream=True,
            ).raw
        )
        layout.add(Image(im, width=Decimal(256)))

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

        return True
コード例 #12
0
    def transform(
        self,
        object_to_transform: Union[io.BufferedIOBase, io.RawIOBase,
                                   AnyPDFType],
        parent_object: Any,
        context: Optional[ReadTransformerContext] = None,
        event_listeners: typing.List[EventListener] = [],
    ) -> Any:

        assert isinstance(object_to_transform, Dictionary)

        # add listener(s)
        for l in event_listeners:
            object_to_transform.add_event_listener(
                l)  # type: ignore [attr-defined]

        # convert using Dictionary transformer
        transformed_root_dictionary: Optional[Dictionary] = None
        for t in self.get_root_transformer().children:
            if isinstance(t, ReadDictionaryTransformer):
                transformed_root_dictionary = t.transform(
                    object_to_transform, parent_object, context, [])
                break

        assert transformed_root_dictionary is not None
        assert isinstance(transformed_root_dictionary, Dictionary)

        #
        # rebuild /Pages if needed
        #

        # list to hold Page objects (in order)
        pages_in_order: typing.List[Page] = []

        # stack to explore Page(s) DFS
        stack_to_handle: typing.List[AnyPDFType] = []
        stack_to_handle.extend(transformed_root_dictionary["Pages"]["Kids"])

        # DFS
        while len(stack_to_handle) > 0:
            obj = stack_to_handle.pop(0)
            if isinstance(obj, Page):
                pages_in_order.append(obj)
            if (isinstance(obj, Dictionary) and "Type" in obj
                    and obj["Type"] == "Pages" and "Kids" in obj
                    and isinstance(obj["Kids"], List)):
                for k in obj["Kids"]:
                    stack_to_handle.insert(0, k)

        # change
        transformed_root_dictionary["Pages"][Name("Kids")] = pList()
        for p in pages_in_order:
            transformed_root_dictionary["Pages"]["Kids"].append(p)
        transformed_root_dictionary["Pages"][Name("Count")] = Decimal(
            len(pages_in_order))

        # return
        return transformed_root_dictionary
コード例 #13
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()

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

        # layout
        layout = SingleColumnLayout(page)

        layout.add(
            Paragraph(
                "pText now support codeblock style paragraphs:",
                font_color=X11Color("YellowGreen"),
                font_size=Decimal(20),
            ))

        # read self
        with open(__file__, "r") as self_file_handle:
            file_contents = self_file_handle.read()

        layout.add(CodeBlock(
            file_contents,
            font_size=Decimal(5),
        ))

        layout.add(
            Paragraph(
                "By default, these LayoutElements are first formatted by black. "
                "The font is Courier, and the background and font_color are adjusted as well.",
                font_size=Decimal(8),
            ))

        # 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)
コード例 #14
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 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
コード例 #15
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()

        # 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)
コード例 #16
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()

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

        N = 4
        colors = [
            HSVColor(Decimal(x / 360.0), Decimal(1), Decimal(1))
            for x in range(0, 360, int(360 / N))
        ]
        t = Table(number_of_rows=N, number_of_columns=N)
        for i in range(0, N):
            for _ in range(0, N):
                t.add(
                    TableCell(
                        Shape(
                            points=BlobFactory.blob(i + 3),
                            stroke_color=colors[i],
                            fill_color=None,
                            line_width=Decimal(1),
                            horizontal_alignment=Alignment.CENTERED,
                        ).scale_up(Decimal(100), Decimal(100))))
        t.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2),
                                   Decimal(2))
        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)

        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
    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)

        rs = []
        for i, s in enumerate(
            [
                "Once upon a midnight dreary,",
                "while I pondered weak and weary,",
                "over many a quaint and curious",
                "volume of forgotten lore",
            ]
        ):
            r = LineOfText(
                s,
                font_size=Decimal(20),
                horizontal_alignment=Alignment.CENTERED,
            ).layout(
                page,
                Rectangle(
                    Decimal(20), Decimal(724 - 24 * i), Decimal(500), Decimal(24)
                ),
            )
            rs.append(r)

        # add rectangle annotation
        page.append_square_annotation(
            stroke_color=X11Color("Salmon"),
            rectangle=Rectangle(
                Decimal(20), Decimal(724 - 24 * 3), Decimal(500), Decimal(24 * 4)
            ),
        )

        # 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)
コード例 #18
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()

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

        for i, c in enumerate([
                X11Color("Red"),
                X11Color("Orange"),
                X11Color("Yellow"),
                X11Color("YellowGreen"),
                X11Color("Blue"),
                X11Color("Purple"),
        ]):
            ChunkOfText("Hello World!", font_size=Decimal(24),
                        font_color=c).layout(
                            page,
                            Rectangle(
                                Decimal(100 + i * 30),
                                Decimal(724 - i * 30),
                                Decimal(100),
                                Decimal(100),
                            ),
                        )

        # 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)
コード例 #19
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()

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

        ul0 = OrderedList()
        ul0.add(Paragraph(text="Ipsum"))
        ul0.add(Paragraph(text="Dolor"))
        ul0.add(Paragraph(text="Sit"))
        ul0.add(Paragraph(text="Amet"))

        ul = OrderedList()
        ul.add(Paragraph(text="Lorem Ipsum Dolor Sit Amet Consectetur Nunc"))
        ul.add(Paragraph(text="Ipsum"))
        ul.add(Paragraph(text="Dolor"))
        ul.add(ul0)
        ul.add(Paragraph(text="Sit"))
        ul.add(Paragraph(text="Amet"))
        ul.layout(
            page,
            bounding_box=Rectangle(Decimal(100), Decimal(600), Decimal(200),
                                   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)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
コード例 #20
0
 def transform(
     self,
     object_to_transform: Union[io.BufferedIOBase, io.RawIOBase,
                                AnyPDFType],
     parent_object: Any,
     context: Optional[ReadTransformerContext] = None,
     event_listeners: typing.List[EventListener] = [],
 ) -> Any:
     assert isinstance(object_to_transform, Decimal)
     return Decimal(object_to_transform).set_parent(
         parent_object)  # type: ignore [attr-defined]
コード例 #21
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()

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

        layout = MultiColumnLayout(page, number_of_columns=2)
        layout.add(
            Paragraph(
                "The Raven",
                font_size=Decimal(20),
                font="Helvetica-Oblique",
                font_color=HexColor("708090"),
            ))

        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.'""",
                text_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))

        # 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)
コード例 #22
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()

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

        bb = Rectangle(Decimal(20), Decimal(600), Decimal(500), Decimal(124))
        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),
            vertical_alignment=Alignment.TOP,
            horizontal_alignment=Alignment.LEFT,
            padding_top=Decimal(5),
            padding_right=Decimal(5),
            padding_bottom=Decimal(5),
            padding_left=Decimal(5),
        ).layout(
            page,
            bb,
        )

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

        # determine output location
        out_file_001 = self.output_dir / "output_001.pdf"
        out_file_002 = self.output_dir / "output_002.pdf"

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

        print("\nSAVING SECOND TIME\n")

        with open(out_file_002, "wb") as in_file_handle:
            PDF.dumps(in_file_handle, pdf)
コード例 #23
0
 def find_free_space(self,
                     needed_space: Rectangle) -> typing.Optional[Rectangle]:
     """
     This function returns a Rectangle (or None) of free space (no text rendering operations, no drawing operations) near the given Rectangle
     """
     w = int(int(needed_space.width) / self.grid_resolution)
     h = int(int(needed_space.height) / self.grid_resolution)
     possible_points: typing.List[typing.Tuple[Decimal, Decimal]] = []
     for i in range(0, len(self.grid) - w):
         for j in range(0, len(self.grid[i]) - h):
             is_free = True
             for k in range(0, w):
                 for l in range(0, h):
                     if not self.grid[i + k][j + l]:
                         is_free = False
                         break
                 if not is_free:
                     break
             if is_free:
                 possible_points.append((
                     Decimal(i * self.grid_resolution),
                     Decimal(j * self.grid_resolution),
                 ))
     # find point closest to desired location
     if len(possible_points) == 0:
         return None
     min_dist = (needed_space.x - possible_points[0][0])**2 + (
         needed_space.y - possible_points[0][1])**2
     min_dist_point = possible_points[0]
     for p in possible_points:
         d = (needed_space.x - p[0])**2 + (needed_space.y - p[1])**2
         if d < min_dist:
             min_dist = d
             min_dist_point = p
     # return
     return Rectangle(
         min_dist_point[0],
         min_dist_point[1],
         needed_space.width,
         needed_space.height,
     )
コード例 #24
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()

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

        t = Table(number_of_rows=3, number_of_columns=2)
        # row 0
        t.add(Paragraph("A"))
        t.add(Paragraph("B"))
        # row 1
        t.add(Paragraph(" ", respect_spaces_in_text=True))
        t.add(Paragraph(" ", respect_spaces_in_text=True))
        # row 2
        t.add(Paragraph(" ", respect_spaces_in_text=True))
        t.add(Paragraph(" ", respect_spaces_in_text=True))

        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                   Decimal(5))
        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)
コード例 #25
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)
コード例 #26
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 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
    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)

        layout.add(
            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),
                text_alignment=Alignment.RIGHT,
                horizontal_alignment=Alignment.RIGHT,
            ))
        layout.add(
            Paragraph(
                "While I nodded, nearly napping, suddenly there came a tapping. As of someone gently rapping, rapping at my chamberdoor.",
                font_size=Decimal(20),
                text_alignment=Alignment.RIGHT,
                horizontal_alignment=Alignment.RIGHT,
            ))

        # 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)
コード例 #28
0
 def _write_background(self, page: Page):
     layout = SingleColumnLayout(page)
     t = Table(number_of_columns=10, number_of_rows=25)
     for i in range(0, 25):
         for j in range(0, 10):
             put_star = random.choice([x <= 3 for x in range(0, 10)])
             if i < 11 and j >= 5:
                 t.add(Paragraph(" ", respect_spaces_in_text=True))
                 continue
             if put_star:
                 c = random.choice(
                     [
                         self.ACCENT_COLOR_1,
                         self.ACCENT_COLOR_2,
                         self.ACCENT_COLOR_3,
                         self.ACCENT_COLOR_4,
                         self.ACCENT_COLOR_5,
                     ]
                 )
                 t.add(
                     Shape(
                         LineArtFactory.n_pointed_star(
                             bounding_box=Rectangle(
                                 Decimal(0), Decimal(0), Decimal(16), Decimal(16)
                             ),
                             n=random.choice([3, 5, 7, 12]),
                         ),
                         fill_color=c,
                         stroke_color=c,
                         line_width=Decimal(1),
                     )
                 )
             else:
                 t.add(Paragraph(" ", respect_spaces_in_text=True))
     t.no_borders()
     t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5), Decimal(5))
     layout.add(t)
コード例 #29
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()

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

        padding = Decimal(5)
        layout_rect = Paragraph(
            "Once upon a midnight dreary,\nwhile I pondered weak and weary,\nover many a quaint and curious\nvolume of forgotten lore",
            font_size=Decimal(20),
            horizontal_alignment=Alignment.CENTERED,
            text_alignment=Alignment.CENTERED,
            respect_newlines_in_text=True,
            padding_top=padding,
            padding_right=padding,
            padding_bottom=padding,
            padding_left=padding,
            border_right=True,
            border_top=True,
            border_color=X11Color("Green"),
            font_color=X11Color("Salmon"),
        ).layout(
            page,
            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)
コード例 #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 empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()

        # add page to document
        pdf.append_page(page)

        # add Image
        layout = MultiColumnLayout(page)

        # add image
        layout.add(
            Image(
                "https://images.unsplash.com/photo-1550155864-3033f844da36?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80",
                width=Decimal(256),
            )
        )
        layout.switch_to_next_column()

        # add title
        layout.add(
            Paragraph(
                "Love you more",
                font_color=X11Color("Crimson"),
                font="Helvetica-Bold",
                font_size=Decimal(20),
            )
        )
        layout.add(
            Paragraph(
                """When I say I love you more,
                                I don't just mean I love you more
                                than you love me. I mean I love
                                you more than the bad days
                                ahead of us. I love you more
                                than any fight we will ever have.
                                I love you more than the distance between us.
                                I love you more than any obstacle that
                                could ever try and come
                                between us. I love you the most.
                                """,
                respect_newlines_in_text=True,
            )
        )
        layout.add(
            Paragraph(
                """yours, most sincerely
                                JS
                             """,
                font_color=X11Color("SlateGray"),
                font="Helvetica-Bold",
                font_size=Decimal(8),
                respect_newlines_in_text=True,
            )
        )

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

        return True