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)

        # first layer, displaying a raven
        layout = SingleColumnLayout(page)
        for _ in range(0, 12):
            layout.add(Paragraph(" ", respect_spaces_in_text=True))
        layout.add(
            Image(
                "https://cdn3.vectorstock.com/i/1000x1000/03/47/black-raven-on-white-background-vector-4780347.jpg"
            ))

        # second layer, displaying the poem
        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.'""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Ah, distinctly I remember it was in the bleak December;
                                And each separate dying ember wrought its ghost upon the floor.
                                Eagerly I wished the morrow;-vainly I had sought to borrow
                                From my books surcease of sorrow-sorrow for the lost Lenore-
                                For the rare and radiant maiden whom the angels name Lenore-
                                Nameless here for evermore.""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """And the silken, sad, uncertain rustling of each purple curtain
                                Thrilled me-filled me with fantastic terrors never felt before;
                                So that now, to still the beating of my heart, I stood repeating
                                'Tis some visitor entreating entrance at my chamber door-
                                Some late visitor entreating entrance at my chamber door;-
                                This it is and nothing more.'""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Presently my soul grew stronger; hesitating then no longer,
                                'Sir,' said I, 'or Madam, truly your forgiveness I implore;
                                But the fact is I was napping, and so gently you came rapping,
                                And so faintly you came tapping, tapping at my chamber door,
                                That I scarce was sure I heard you'-here I opened wide the door;-
                                Darkness there and nothing more.""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.switch_to_next_column()
        layout.add(
            Paragraph(
                """Deep into that darkness peering, long I stood there wondering, fearing,
                                Doubting, dreaming dreams no mortal ever dared to dream before;
                                But the silence was unbroken, and the stillness gave no token,
                                And the only word there spoken was the whispered word, 'Lenore?'
                                This I whispered, and an echo murmured back the word, 'Lenore!'-
                                Merely this and nothing more.""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Back into the chamber turning, all my soul within me burning,
                                Soon again I heard a tapping somewhat louder than before.
                                'Surely,' said I, 'surely that is something at my window lattice;
                                Let me see, then, what thereat is, and this mystery explore-
                                Let my heart be still a moment and this mystery explore;-
                                'Tis the wind and nothing more!'""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Open here I flung the shutter, when, with many a flirt and flutter,
                                In there stepped a stately Raven of the saintly days of yore;
                                Not the least obeisance made he; not a minute stopped or stayed he;
                                But, with mien of lord or lady, perched above my chamber door-
                                Perched upon a bust of Pallas just above my chamber door-
                                Perched, and sat, and nothing more.""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Then this ebony bird beguiling my sad fancy into smiling,
                                By the grave and stern decorum of the countenance it wore,
                                'Though thy crest be shorn and shaven, thou,' I said, 'art sure no craven,
                                Ghastly grim and ancient Raven wandering from the Nightly shore-
                                Tell me what thy lordly name is on the Night's Plutonian shore!'
                                Quoth the Raven 'Nevermore.'""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """Much I marvelled this ungainly fowl to hear discourse so plainly,
                                Though its answer little meaning-little relevancy bore;
                                For we cannot help agreeing that no living human being
                                Ever yet was blessed with seeing bird above his chamber door-
                                Bird or beast upon the sculptured bust above his chamber door,
                                With such name as 'Nevermore.'""",
                horizontal_alignment=Alignment.CENTERED,
                font_size=Decimal(7),
                respect_newlines_in_text=True,
            ))
        layout.add(
            Paragraph(
                """But the Raven, sitting lonely on the placid bust, spoke only
                    That one word, as if his soul in that one word he did outpour.
                    Nothing farther then he uttered-not a feather then he fluttered-
                    Till I scarcely more than muttered 'Other friends have flown before-
                    On the morrow he will leave me, as my Hopes have flown before.'
                    Then the bird said 'Nevermore.'""",
                horizontal_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)

        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
예제 #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 empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()
        pdf.append_page(page)
        layout = SingleColumnLayout(page)

        # add title
        layout.add(
            Paragraph(
                "Copy the picture",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            )
        )

        layout.add(
            Paragraph(
                """
                Copy the picture using the grid lines as a guide. 
                You might find it easier to copy one square at a time. 
                Count the squares carefully!
                """,
                respect_newlines_in_text=True,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            )
        )

        # add image
        image_a = PILImage.open(
            requests.get(
                "https://www.mozilla.org/media/protocol/img/logos/firefox/browser/logo-lg-high-res.fbc7ffbb50fd.png",
                stream=True,
            ).raw
        )
        image_a = TestWriteGridCopyPuzzle._convert_png_to_jpg(image_a)
        image_a = image_a.resize((256, 256))
        image_b = PILImage.new(size=(256, 256), color=(255, 255, 255), mode="RGB")
        pixels_a = image_a.load()
        pixels_b = image_b.load()
        for i in range(0, 256, 32):
            for j in range(0, 256):
                pixels_a[(i, j)] = (0, 0, 0)
                pixels_b[(i, j)] = (0, 0, 0)
                pixels_a[(j, i)] = (0, 0, 0)
                pixels_b[(j, i)] = (0, 0, 0)
        for j in range(0, 256):
            pixels_a[(255, j)] = (0, 0, 0)
            pixels_b[(255, j)] = (0, 0, 0)
            pixels_a[(j, 255)] = (0, 0, 0)
            pixels_b[(j, 255)] = (0, 0, 0)

        t: Table = Table(number_of_columns=2, number_of_rows=1)
        t.add(Image(image_a))
        t.add(Image(image_b))
        t.no_borders()
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5), Decimal(5))

        layout.add(t)

        # 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 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
                                x
                             """,
                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
예제 #4
0
    def test_write_document(self):

        words = [
            "COW",
            "PUPPY",
            "TURTLE",
            "PARROT",
            "SNAKE",
            "GOLDFISH",
            "HAMSTER",
            "KITTEN",
            "TURKEY",
            "DOVE",
            "HORSE",
            "BEE"
            "RABBIT",
            "DUCK",
            "SHRIMP",
            "PIG",
            "GOAT",
            "CRAB",
            "DOG",
            "DEER",
            "CAT",
            "MOUSE",
            "ELEPHANT",
            "LION",
            "PENGUIN",
            "SPARROW",
            "STORK",
            "HAWK",
        ]

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

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

        # add title
        layout.add(
            Paragraph(
                """
                Word scrambles or anagrams are an excellent way of helping children 
                with their spelling as they have to recognise letter patterns. 
                They are also a fun way of testing knowledge on a subject. 
                We have word scrambles on lots of topics ready to print for home or classroom.
                """,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        # add table
        t = Table(number_of_rows=len(words), number_of_columns=2)
        for i, w in enumerate(words):
            # shuffle word
            permuted_word = w
            while permuted_word == w:
                letters = [x for x in w]
                random.shuffle(letters)
                permuted_word = "".join([x for x in letters])
            t.add(
                TableCell(
                    Paragraph(str(i + 1) + ". " + permuted_word),
                    border_top=False,
                    border_right=False,
                    border_left=False,
                    border_bottom=False,
                ))
            # empty column
            t.add(
                TableCell(
                    Paragraph(""),
                    border_top=False,
                    border_right=False,
                    border_left=False,
                ))

        layout.add(t)

        # go to next column
        layout.switch_to_next_column()

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

        # add Image
        layout.add(
            Image(
                "https://www.how-to-draw-funny-cartoons.com/images/cartoon-tree-012.jpg"
            ))

        # 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)

        # add Image
        layout = MultiColumnLayout(page)

        layout.add(
            Paragraph(
                "Rose",
                font_color=X11Color("MistyRose"),
                font_size=Decimal(20),
                font="Helvetica-Bold",
            )
        )
        layout.add(
            Paragraph(
                "A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. "
                "There are over three hundred species and tens of thousands of cultivars. "
            )
        )
        layout.add(
            Paragraph(
                "They form a group of plants that can be erect shrubs, climbing, or trailing, with stems that are often armed with sharp prickles. "
                "Flowers vary in size and shape and are usually large and showy, "
                "in colours ranging from white through yellows and reds."
            )
        )
        layout.add(
            Paragraph(
                "Most species are native to Asia, with smaller numbers native to Europe, North America, and northwestern Africa. "
                "Species, cultivars and hybrids are all widely grown for their beauty and often are fragrant. "
            )
        )
        layout.add(
            Paragraph("Roses have acquired cultural significance in many societies. ")
        )
        layout.add(
            Paragraph(
                "Rose plants range in size from compact, miniature roses, to climbers that can reach seven meters in height. "
                "Different species hybridize easily, and this has been used in the development of the wide range of garden roses."
            )
        )

        # 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)))

        # add UnorderedList
        layout.add(Paragraph("The genus Rosa is subdivided into four subgenera:"))
        layout.add(
            UnorderedList()
            .add(Paragraph("Hulthemia", padding_bottom=Decimal(2)))
            .add(Paragraph("Hesperrhodos", padding_bottom=Decimal(2)))
            .add(Paragraph("Platyrhodon", padding_bottom=Decimal(2)))
            .add(Paragraph("Rosa", padding_bottom=Decimal(2)))
            .add(
                UnorderedList()
                .add(Paragraph("Banksianae"))
                .add(Paragraph("Bracteatae"))
                .add(Paragraph("Caninae"))
                .add(Paragraph("Carolinae"))
                .add(Paragraph("Chinensis"))
                .add(Paragraph("Gallicanae"))
                .add(Paragraph("Gymnocarpae"))
                .add(Paragraph("Laevigatae"))
                .add(Paragraph("Pimpinellifoliae"))
                .add(Paragraph("Rosa"))
                .add(Paragraph("Synstylae"))
            )
        )
        # 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)

        t = Table(number_of_rows=5, number_of_columns=3)
        t.add(Paragraph(" ", respect_spaces_in_text=True))
        t.add(
            Paragraph(
                "Close-up",
                font_color=X11Color("SteelBlue"),
                font_size=Decimal(20),
                horizontal_alignment=Alignment.CENTERED,
            ))
        t.add(
            Paragraph(
                "Panoramic",
                font_color=X11Color("SteelBlue"),
                font_size=Decimal(20),
                horizontal_alignment=Alignment.CENTERED,
            ))

        t.add(Paragraph("Nature"))
        self._add_image_to_table(
            "https://images.unsplash.com/photo-1520860560195-0f14c411476e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw",
            t,
        )
        self._add_image_to_table(
            "https://images.unsplash.com/photo-1613480123595-c5582aa551b9?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw",
            t,
        )

        t.add(Paragraph("Architecture"))
        self._add_image_to_table(
            "https://images.unsplash.com/photo-1611321569296-1305a38ebd74?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw",
            t,
        )
        self._add_image_to_table(
            "https://images.unsplash.com/photo-1613262666714-acebcc37f11e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw",
            t,
        )

        t.set_border_width_on_all_cells(Decimal(0.2))
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                   Decimal(5))

        layout = SingleColumnLayout(page)
        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)
예제 #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 empty document
        pdf: Document = Document()
        page: Page = Page()
        pdf.append_page(page)
        layout = SingleColumnLayout(page)

        # add title
        layout.add(
            Paragraph(
                "Match The Shadow",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            ))

        # add explanation
        layout.add(
            Paragraph(
                """
                These simple "match up" puzzles help children with observation skills. 
                They will also need to learn a way of marking or remembering which items they have matched, 
                so that they can identify the odd ones out. 
                If you would like to reuse puzzles you could place counters on each "pair" that your child finds, perhaps.""",
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        # add image
        imgs = [
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Orc-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/King-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Knight-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Medusa-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Monster-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Sorceress-Witch-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Centaur-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Elf-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Poison-Spider-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Unicorn-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Viking-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Villager-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Dragon-Egg-icon.png",
        ]
        N = 10
        imgs = imgs[0:N]
        random.shuffle(imgs)

        shadows = [
            TestMatchTheShadowPuzzle._make_image_shadow(x) for x in imgs
        ]
        random.shuffle(imgs)

        t = Table(number_of_columns=5, number_of_rows=N)
        for i in range(0, N):
            t.add(Image(imgs[i], width=Decimal(32), height=Decimal(32)))
            t.add(Paragraph(" ", respect_spaces_in_text=True))
            t.add(Paragraph(" ", respect_spaces_in_text=True))
            t.add(Paragraph(" ", respect_spaces_in_text=True))
            t.add(Image(shadows[i], width=Decimal(32), height=Decimal(32)))
        t.no_borders()
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                   Decimal(5))
        layout.add(t)

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

        return True
예제 #8
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)

        t = Table(number_of_rows=20, number_of_columns=20)
        colors = [
            HSVColor(Decimal(x / 360), Decimal(1), Decimal(1))
            for x in range(0, 360, int(360 / 20))
        ]
        for i in range(0, 18 * 20):
            t.add(
                TableCell(
                    Paragraph(" ", respect_spaces_in_text=True),
                    background_color=colors[i % len(colors)],
                ))
        for i in range(0, 20):
            t.add(
                TableCell(
                    Paragraph(" ", respect_spaces_in_text=True),
                    background_color=colors[i % len(colors)].darker(),
                ))
        for i in range(0, 20):
            t.add(
                TableCell(
                    Paragraph(" ", respect_spaces_in_text=True),
                    background_color=colors[i % len(colors)].darker().darker(),
                ))

        t.no_borders()
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                   Decimal(5))

        table_rect = t.layout(
            page,
            bounding_box=Rectangle(Decimal(20), Decimal(600), Decimal(500),
                                   Decimal(200)),
        )

        Paragraph(
            text="Love is love",
            font_size=Decimal(8),
            font_color=X11Color("Gray"),
            horizontal_alignment=Alignment.RIGHT,
        ).layout(
            page,
            bounding_box=Rectangle(Decimal(20), table_rect.y - 40,
                                   table_rect.width, Decimal(20)),
        )

        # 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_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("Flowchart Line Art",
                      font_size=Decimal(20),
                      font_color=X11Color("Blue")))

        # table
        fixed_bb = Rectangle(Decimal(0), Decimal(0), Decimal(100),
                             Decimal(100))
        t = Table(number_of_rows=10, number_of_columns=6)
        t.add(
            Shape(
                LineArtFactory.flowchart_process(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_decision(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_document(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_predefined_document(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_multiple_documents(fixed_bb)
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_data(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))

        # captions
        t.add(Paragraph("Process"))
        t.add(Paragraph("Decision"))
        t.add(Paragraph("Document"))
        t.add(Paragraph("Predefined Document"))
        t.add(Paragraph("Multiple Documents"))
        t.add(Paragraph("Data"))

        # second row of shapes
        t.add(
            Shape(
                LineArtFactory.flowchart_predefined_process(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_stored_data(fixed_bb),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_internal_storage(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_sequential_data(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_direct_data(fixed_bb),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_manual_input(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))

        # captions
        t.add(Paragraph("Predefined Process"))
        t.add(Paragraph("Stored Data"))
        t.add(Paragraph("Internal Storage"))
        t.add(Paragraph("Sequential Data"))
        t.add(Paragraph("Direct Data"))
        t.add(Paragraph("Manual Input"))

        # third row of shapes
        t.add(
            Shape(
                LineArtFactory.flowchart_manual_operation(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_card(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_paper_tape(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_display(fixed_bb),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_preparation(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_loop_limit(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))

        # captions
        t.add(Paragraph("Manual Operation"))
        t.add(Paragraph("Card"))
        t.add(Paragraph("Paper Tape"))
        t.add(Paragraph("Display"))
        t.add(Paragraph("Preparation"))
        t.add(Paragraph("Loop Limit"))

        # fourth row of shapes
        t.add(
            Shape(
                # LineArtFactory.flowchart_termination(fixed_bb),
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_collate(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_delay(fixed_bb),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_extract(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_merge(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_or(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))

        # captions
        t.add(Paragraph("Termination"))
        t.add(Paragraph("Collate"))
        t.add(Paragraph("Delay"))
        t.add(Paragraph("Extract"))
        t.add(Paragraph("Merge"))
        t.add(Paragraph("Or"))

        # fifth row of shapes
        t.add(
            Shape(
                LineArtFactory.flowchart_sort(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_summing_junction(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.regular_n_gon(fixed_bb, 8),
                # LineArtFactory.flowchart_database(fixed_bb),
                fill_color=X11Color("White"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_on_page_reference(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_off_page_reference(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))
        t.add(
            Shape(
                LineArtFactory.flowchart_process_iso_9000(fixed_bb),
                fill_color=X11Color("Blue"),
                stroke_color=X11Color("Black"),
                line_width=Decimal(1),
            ))

        # captions
        t.add(Paragraph("Sort"))
        t.add(Paragraph("Summing Junction"))
        t.add(Paragraph("Database"))
        t.add(Paragraph("On Page Reference"))
        t.add(Paragraph("Off Page Reference"))
        t.add(Paragraph("Process ISO 9000"))

        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)
예제 #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 document
        pdf = Document()

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

        t = Table(number_of_rows=5, number_of_columns=3)
        t.add(
            TableCell(
                Paragraph(" ", respect_spaces_in_text=True),
                border_top=False,
                border_left=False,
            )
        )
        t.add(
            Paragraph(
                "Language", font_color=X11Color("SteelBlue"), font_size=Decimal(20)
            )
        )
        t.add(
            Paragraph(
                "Nof. Questions",
                font_color=X11Color("SteelBlue"),
                font_size=Decimal(20),
            )
        )

        t.add(
            TableCell(
                Paragraph("front-end", font_color=X11Color("SteelBlue")), row_span=2
            )
        )
        t.add(Paragraph("Javascript"))
        t.add(Paragraph("2,167,178"))

        t.add(Paragraph("Php"))
        t.add(Paragraph("1,391,524"))

        t.add(
            TableCell(
                Paragraph("back-end", font_color=X11Color("SteelBlue")), row_span=2
            )
        )
        t.add(Paragraph("C++"))
        t.add(Paragraph("711,944"))

        t.add(Paragraph("Java"))
        t.add(Paragraph("1,752,877"))
        t.set_border_width_on_all_cells(Decimal(0.2))
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5), Decimal(5))

        table_rect = t.layout(
            page,
            bounding_box=Rectangle(
                Decimal(20), Decimal(600), Decimal(500), Decimal(200)
            ),
        )

        Paragraph(
            text="**Data gathered from Stackoverflow.com on 10th of february 2021",
            font_size=Decimal(8),
            font_color=X11Color("Gray"),
        ).layout(
            page,
            bounding_box=Rectangle(
                Decimal(20), table_rect.y - 40, table_rect.width, Decimal(20)
            ),
        )

        # 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_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)

        # set layout
        layout = SingleColumnLayout(page)

        my_dict = {
            " ": ["A Error", "B Error", "C Error", "D Error"],
            "lab1": [0.34, 0.23, 0.80, 0.79],
            "lab2": [0.53, 0.38, 0.96, 1.25],
            "lab3": [0.40, 0.27, 0.68, 0.93],
        }

        colors = {
            0: X11Color("Green"),
            0.25: X11Color("Yellow"),
            0.5: X11Color("Orange"),
            0.75: X11Color("Red"),
        }

        table = Table(number_of_rows=4, number_of_columns=5)
        table.add(Paragraph(" ", respect_spaces_in_text=True))
        for h in my_dict[" "]:
            table.add(
                Paragraph(text=h, font="Helvetica-Bold",
                          font_size=Decimal(12)))
        for name, row in [(k, v) for k, v in my_dict.items() if k != " "]:
            table.add(Paragraph(name))
            for v in row:
                c = X11Color("Green")
                for b, bc in colors.items():
                    if v > b:
                        c = bc
                table.add(
                    Paragraph(str(v),
                              font_color=c,
                              horizontal_alignment=Alignment.CENTERED))

        # set border
        table.set_border_width_on_all_cells(Decimal(0.2))

        # set padding
        table.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                       Decimal(5))

        # add to layout
        layout.add(
            Paragraph(
                "This table contains all measurands for 3 lab-sessions:"))
        layout.add(table)

        # 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_write_document(self):

        words = [
            "COW",
            "PUPPY",
            "TURTLE",
            "PARROT",
            "SNAKE",
            "GOLDFISH",
            "HAMSTER",
            "KITTEN",
            "TURKEY",
            "DOVE",
            "HORSE",
            "BEE"
            "RABBIT",
            "DUCK",
            "SHRIMP",
            "PIG",
            "GOAT",
            "CRAB",
            "DOG",
            "DEER",
            "CAT",
            "MOUSE",
            "ELEPHANT",
            "LION",
            "PENGUIN",
            "SPARROW",
            "STORK",
            "HAWK",
        ]
        ws = WordSearch(words)

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

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

        # add title
        layout.add(
            Paragraph(
                """
                A word search, word find, word seek, 
                word sleuth or mystery word puzzle is a word game that consists of the letters of words placed in a grid, 
                which usually has a rectangular or square shape.
                The objective of this puzzle is to find and mark all the words hidden inside the box.
                """,
                font_color=X11Color("SlateGray"),
            ))

        # add grid
        layout.add(ws)

        # go to next column
        layout.switch_to_next_column()

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

        # add list
        ul = UnorderedList()
        for w in words:
            ul.add(Paragraph(w))
        layout.add(ul)

        # 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
        import numpy as np

        # create data
        x = np.random.rand(15)
        y = x + np.random.rand(15)
        z = x + np.random.rand(15)
        z = z * z

        layout.add(
            Heading(
                "#197 Available color palettes with Matplotlib",
                font_size=Decimal(20),
                font_color=X11Color("SteelBlue"),
            ))

        # Use it with a call in cmap
        layout.add(
            Heading(
                "1.0 BuPu",
                font_size=Decimal(16),
                font_color=X11Color("DarkBlue"),
                outline_level=1,
            ))
        MatPlotLibPlot.scatter(
            x,
            y,
            s=z * 2000,
            c=x,
            cmap="BuPu",
            alpha=0.4,
            edgecolors="grey",
            linewidth=2,
        )
        layout.add(Chart(MatPlotLibPlot.gcf()))

        # You can reverse it:
        layout.add(
            Heading(
                "1.1 Inferno",
                font_size=Decimal(16),
                font_color=X11Color("DarkBlue"),
                outline_level=1,
            ))
        MatPlotLibPlot.scatter(
            x,
            y,
            s=z * 2000,
            c=x,
            cmap="inferno",
            alpha=0.4,
            edgecolors="grey",
            linewidth=2,
        )
        layout.add(Chart(MatPlotLibPlot.gcf()))

        # add explanation
        layout.switch_to_next_column()
        layout.add(
            Paragraph(
                "Post #196 describes how to pick up a single color when working with python and matplotlib. "
                "This post aims to describe a few color palette that are provided, and thus make your life easier when plotting several color. "
                "There are 3 types of color palettes: Sequential, Discrete and Diverging. Here are a few explanations for each:"
            ))

        # OTHER: viridis / inferno / plasma / magma
        layout.add(
            Heading(
                "1.2 Plasma",
                font_size=Decimal(16),
                font_color=X11Color("DarkBlue"),
                outline_level=1,
            ))
        MatPlotLibPlot.scatter(
            x,
            y,
            s=z * 2000,
            c=x,
            cmap="plasma",
            alpha=0.4,
            edgecolors="grey",
            linewidth=2,
        )
        layout.add(Chart(MatPlotLibPlot.gcf()))

        layout.add(
            Heading(
                "2.0 Acknowledgements",
                font_size=Decimal(16),
                font_color=X11Color("DarkBlue"),
            ))
        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)

        # path to font
        font_path: Path = Path(__file__).parent / "Jsfont-Regular.ttf"
        assert font_path.exists()

        # layout
        layout: PageLayout = SingleColumnLayout(page)
        layout.add(
            Paragraph(
                "Hello World,",
                font=TrueTypeFont.true_type_font_from_file(font_path),
                font_size=Decimal(40),
                font_color=HexColor("FFCC00"),
            ))

        layout.add(
            Paragraph(
                """
                pText can now write in any custom TTF font. Like this one, which is a stylized copy of my handwriting. 
                Of course, you could also pick a more sensible font. Like Comic Sans, Roboto, Open Sans, and many others.
                In fact, pText can use any TTF font. 
                """,
                font=TrueTypeFont.true_type_font_from_file(font_path),
                font_size=Decimal(20),
                font_color=HexColor("646E78"),
            ))

        layout.add(
            Paragraph(
                """
                Finally, you have the option to match your own custom style and brand.
                For more examples, check out GitHub. Don't forget to star the repo :-)
                """,
                font=TrueTypeFont.true_type_font_from_file(font_path),
                font_size=Decimal(20),
                font_color=HexColor("68C3D4"),
            ))

        layout.add(
            Barcode(
                data="https://github.com/jorisschellekens/ptext-release",
                type=BarcodeType.QR,
                width=Decimal(64),
                height=Decimal(64),
                stroke_color=HexColor("FFCC00"),
            ))

        # 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)
예제 #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)

        page_layout: PageLayout = SingleColumnLayout(page)
        page_layout.vertical_margin = page.get_page_info().get_height(
        ) * Decimal(0.02)
        page_layout.add(
            Image(
                "https://www.designevo.com/res/templates/thumb_small/green-and-white-stripe-sphere.png",
                width=Decimal(128),
                height=Decimal(128),
            ))

        # invoice information table
        page_layout.add(self._build_invoice_information())

        # empty paragraph for spacing
        page_layout.add(Paragraph(" "))

        # billing and shipping information
        page_layout.add(self._build_billing_and_shipping_information())

        # empty paragraph for spacing
        page_layout.add(Paragraph(" "))

        # itemized description
        page_layout.add(self._build_itemized_description_table())

        # outline
        pdf.add_outline("Your Invoice", 0, DestinationType.FIT, page_nr=0)

        # embed json document for machine processing
        invoice_json = {
            "items": [
                {
                    "Description": "Product1",
                    "Quantity": 2,
                    "Unit Price": 50,
                    "Amount": 100,
                },
                {
                    "Description": "Product2",
                    "Quantity": 4,
                    "Unit Price": 60,
                    "Amount": 100,
                },
                {
                    "Description": "Labor",
                    "Quantity": 14,
                    "Unit Price": 60,
                    "Amount": 100,
                },
            ],
            "Subtotal":
            1180,
            "Discounts":
            177,
            "Taxes":
            100.30,
            "Total":
            1163.30,
        }
        invoice_json_bytes = bytes(json.dumps(invoice_json, indent=4),
                                   encoding="latin1")
        pdf.append_embedded_file("invoice.json",
                                 invoice_json_bytes,
                                 apply_compression=False)

        # 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)
예제 #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)

        # add title
        layout.add(
            Paragraph(
                "Count The Pictures Puzzle",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            )
        )

        # add explanation
        layout.add(
            Paragraph(
                """
                These simple "match up" puzzles help children with observation skills. 
                They will also need to learn a way of marking or remembering which items they have matched, 
                so that they can identify the odd ones out. 
                If you would like to reuse puzzles you could place counters on each "pair" that your child finds, perhaps.""",
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            )
        )

        # random locations for each image
        imgs = [
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Orc-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/King-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Knight-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Medusa-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Monster-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Sorceress-Witch-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Centaur-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Elf-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Poison-Spider-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Unicorn-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Viking-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Villager-icon.png",
            "https://icons.iconarchive.com/icons/chanut/role-playing/128/Dragon-Egg-icon.png",
        ]

        N = 32
        w = int(sqrt(N) + 2)
        random.shuffle(imgs)
        image_positions: typing.Dict[int, str] = {}
        images_used = []
        for i in [random.randint(0, len(imgs)) for _ in range(0, N)]:
            i = (i + len(imgs)) % len(imgs)
            # place image
            p0 = random.randint(0, w ** 2)
            while p0 in image_positions:
                p0 = random.randint(0, N ** 2)
            url = imgs[i]
            if url not in images_used:
                images_used.append(url)
            image_positions[p0] = url

        t = Table(number_of_rows=w, number_of_columns=w)
        for i in range(0, w ** 2):
            if i in image_positions:
                t.add(Image(image_positions[i], width=Decimal(32), height=Decimal(32)))
            else:
                t.add(Paragraph(" ", respect_spaces_in_text=True))
        t.no_borders()
        t.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2), Decimal(2))
        layout.add(t)

        # write count table
        for _ in range(0, 5):
            layout.add(Paragraph(" ", respect_spaces_in_text=True))

        t2 = Table(number_of_rows=1, number_of_columns=len(images_used) * 2)
        for url in images_used:
            t2.add(
                TableCell(
                    Image(url, width=Decimal(16), height=Decimal(15)),
                    border_top=False,
                    border_right=False,
                    border_bottom=False,
                    border_left=False,
                )
            )
            t2.add(Paragraph(" ", respect_spaces_in_text=True))
        t2.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2), Decimal(2))
        layout.add(t2)

        # 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_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=10, number_of_columns=4)
        t.add(
            Paragraph(
                "lowercase",
                font_color=X11Color("YellowGreen"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "uppercase",
                font_color=X11Color("YellowGreen"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "lowercase acute",
                font_color=X11Color("YellowGreen"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "uppercase acute",
                font_color=X11Color("YellowGreen"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        # A
        t.add(Paragraph("a"))
        t.add(Paragraph("A"))
        t.add(Paragraph("á"))
        t.add(Paragraph("Á"))
        # B
        t.add(Paragraph("b"))
        t.add(Paragraph("B"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))
        # C
        t.add(Paragraph("c"))
        t.add(Paragraph("C"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))
        # D
        t.add(Paragraph("d"))
        t.add(Paragraph("D"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))
        # E
        t.add(Paragraph("e"))
        t.add(Paragraph("E"))
        t.add(Paragraph("é"))
        t.add(Paragraph("É"))
        # F
        t.add(Paragraph("f"))
        t.add(Paragraph("F"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))
        # G
        t.add(Paragraph("g"))
        t.add(Paragraph("G"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))
        # ..
        t.add(
            Paragraph(
                "...",
                font_color=X11Color("LightGray"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "...",
                font_color=X11Color("LightGray"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "...",
                font_color=X11Color("LightGray"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        t.add(
            Paragraph(
                "...",
                font_color=X11Color("LightGray"),
                horizontal_alignment=Alignment.CENTERED,
            )
        )
        # Z
        t.add(Paragraph("z"))
        t.add(Paragraph("Z"))
        t.add(Paragraph("-"))
        t.add(Paragraph("-"))

        t.set_border_width_on_all_cells(Decimal(0.2))
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5), Decimal(5))

        layout.add(t)

        layout.add(
            Paragraph(
                text="**These are the characters pText can currently render in a PDF",
                font_size=Decimal(8),
                font_color=X11Color("Gray"),
                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)

        # attempt to re-open PDF
        with open(out_file, "rb") as in_file_handle:
            PDF.loads(in_file_handle)
예제 #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 empty document
        pdf: Document = Document()

        # create empty page
        page: Page = Page()
        pdf.append_page(page)
        layout = SingleColumnLayout(page)

        # add title
        layout.add(
            Paragraph(
                "Complete the picture",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            ))

        layout.add(
            Paragraph(
                """
                Can you complete the picture on the right by copying the completed picture on the left?
                """,
                respect_newlines_in_text=True,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        # add image
        image_a = PILImage.open(
            requests.get(
                "https://www.mozilla.org/media/protocol/img/logos/firefox/browser/logo-lg-high-res.fbc7ffbb50fd.png",
                stream=True,
            ).raw)
        image_a = TestWriteCompleteThePictureVerticallyPuzzle._convert_png_to_jpg(
            image_a)
        image_a = image_a.resize((256, 256))
        image_b = PILImage.new(size=(256, 256),
                               color=(255, 255, 255),
                               mode="RGB")
        pixels_a = image_a.load()
        pixels_b = image_b.load()
        for i in range(0, 256):
            for j in range(0, 256):
                if i == 0 or j == 0 or i == 255 or j == 255 or j % 64 == 0:
                    pixels_b[(i, j)] = (0, 0, 0)
                    continue
                if int(j / 64) % 2 == 0:
                    pixels_b[(i, j)] = pixels_a[(i, j)]

        t: Table = Table(number_of_columns=2, number_of_rows=1)
        t.add(Image(image_a))
        t.add(Image(image_b))
        t.no_borders()
        t.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5),
                                   Decimal(5))

        layout.add(t)

        # 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()

        # fmt: off
        mazes = [
            ("https://i.pinimg.com/originals/1e/c2/a7/1ec2a73d0a45016c7d1b52ef9f11e740.png", "395E66"),
            ("https://i.pinimg.com/originals/f8/23/88/f823882e7c5fa42790e78f43ecf7e8bf.jpg", "387D7A"),
            ("https://i.pinimg.com/600x315/2d/94/33/2d94334b737efb5d3a5ef32aef9daefc.jpg", "32936F"),
            ("https://i.pinimg.com/originals/f1/c9/07/f1c907c09d65d5c86fba304fed1009ca.jpg", "26A96C"),
            ("https://cdn.pixabay.com/photo/2017/08/24/12/11/silhouette-2676573_960_720.png", "2BC016"),
            ("https://images-na.ssl-images-amazon.com/images/I/61bqYbAeUgL._AC_SL1500_.jpg", "395E66"),
            ("https://i.pinimg.com/originals/55/e8/91/55e891af7de086a8868e1a8e02fb4426.jpg","387D7A"),
            ("https://cdn.shopify.com/s/files/1/2123/8425/products/166422700-LRG_242a4c8b-cad5-476e-afd1-c8b882d48fc2_530x.jpg","32936F"),
            ("http://www.silhcdn.com/3/i/shapes/lg/7/6/d124067.jpg","26A96C"),
            ("https://cdn.pixabay.com/photo/2018/03/04/23/28/frog-3199601_1280.png","2BC016")
        ]
        # fmt: on

        # add mazes
        for (url, color) in mazes:
            for _ in range(0, 3):
                self._write_maze_page(pdf, url, color)

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

        # content of ack page
        layout.add(
            Paragraph(
                "Hi there,",
                font_color=HexColor("32936F"),
                font_size=Decimal(20),
            )
        )
        layout.add(
            Paragraph(
                "This PDF was made by pText. Check out the GitHub repository to find more fun examples of what you can do with PDF's.",
                font_color=X11Color("SlateGray"),
                font_size=Decimal(12),
            )
        )
        layout.add(
            Barcode(
                data="https://github.com/jorisschellekens/ptext-release",
                type=BarcodeType.QR,
                width=Decimal(64),
            )
        )

        # 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)
예제 #20
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()
        pdf.append_page(page)
        layout = SingleColumnLayout(page)

        # add title
        layout.add(
            Paragraph(
                "Copy the picture",
                font_size=Decimal(20),
                font_color=X11Color("YellowGreen"),
            ))

        layout.add(
            Paragraph(
                """
                Copy the picture using the grid lines as a guide. 
                You might find it easier to copy one square at a time. 
                Count the squares carefully!
                """,
                respect_newlines_in_text=True,
                font_color=X11Color("SlateGray"),
                font_size=Decimal(8),
            ))

        pics: typing.List[Image] = self._split_picture_to_grid(
            "https://icons.iconarchive.com/icons/iconka/meow-2/128/cat-sing-icon.png"
        )
        # fmt: off
        coords: typing.List[str] = [
            "1A",
            "2A",
            "3A",
            "4A",
            "1B",
            "2B",
            "3B",
            "4B",
            "1C",
            "2C",
            "3C",
            "4C",
            "1D",
            "2D",
            "3D",
            "4D",
        ]
        # fmt: on
        pics_and_coords = [x for x in zip(pics, coords)]
        random.shuffle(pics_and_coords)

        t = Table(
            number_of_rows=4,
            number_of_columns=8,
            column_widths=[
                Decimal(1),
                Decimal(3),
                Decimal(1),
                Decimal(3),
                Decimal(1),
                Decimal(3),
                Decimal(1),
                Decimal(3),
            ],
        )
        for p, c in pics_and_coords:
            t.add(Paragraph(c, font_size=Decimal(6)))
            t.add(Image(p))

        t.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2),
                                   Decimal(2))
        t.no_borders()
        layout.add(t)

        # table 2
        t2 = Table(number_of_columns=4, number_of_rows=4)
        for c in coords:
            t2.add(
                Paragraph(
                    "\n" + c + "\n",
                    respect_newlines_in_text=True,
                    font_color=X11Color("LightGray"),
                    horizontal_alignment=Alignment.CENTERED,
                ))
        t2.set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2),
                                    Decimal(2))
        layout.add(t2)

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

        return True