Welcome, guest | Sign In | My Account | Store | Cart

Just a little demo on how to create simple drawings with PyMuPDF.

This script simulates what you see looking into your coffee mug, early in the morning after a long night of programming ...

Python, 52 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from __future__ import print_function
import math
import fitz
"""
@created: 2017-06-18 10:00:00

@author: (c) Jorj X. McKie

Demo for creating simple graphics with method 'Page.drawLine()'.

Dependencies:
PyMuPDF, math

License:
 GNU GPL 3+

Sketching a caustic. This is the figure the early morning sun paints onto
your desperately needed cup of coffee from an angle on your left side ...

"""
def pvon(a):                 # starting point of one sun ray
    return(math.cos(a), math.sin(a))

def pbis(a):                 # end point of one sun ray
    return(math.cos(3*a - math.pi), (math.sin(3*a - math.pi)))

# create new PDF with an empty square format page
doc = fitz.open()
doc.insertPage(-1, width = 800, height = 800)
page = doc[0]                # get the page just created

# if you want a coffee background, use some picture reflecting your
# preferred amount of milk.
page.insertImage(page.rect, "coffee.jpg")

# middle of the circle of the page
mitte = fitz.Point(page.rect.width / 2, page.rect.height / 2)

# radius leaves a border of 20 pixels
radius = page.rect.width / 2 - 20

# how many sun rays we paint
count = 200
interval = math.pi / count
color = (1, 1, 0)                                # this is plain yellow
for i in range(1, count):
    a = -math.pi / 2 + i * interval
    von = fitz.Point(pvon(a))*radius + mitte     # start point adjusted
    bis = fitz.Point(pbis(a))*radius + mitte     # end point adjusted
    page.drawLine(von, bis, width = 0.5, color = color)

doc.save("caustic.pdf", garbage = 4, deflate = True)

This works on all Windows, MacOS and Linux platforms, 32bit / 64bit, where MuPDF can be generated, and any Python version 2.7 and up can run.

In the code, a file "coffee.jpg" is referenced as background. You should easily be able to create such an animal with some utility available on your platform. It can be any size (e.g. 50 x 50 pixels with a color of your liking) and in half a dozen of image file formats (png, jpg, bmp, ...). If you prefer white background, omit the statement. You may want to adjust the color tuple to something else than yellow then.

Of course, you can also give each line a different color - maybe derive it somehow from the index i.

1 comment

Jorj X. McKie (author) 6 years, 10 months ago  # | flag

Have a look at the GitHub repository of PyMuPDF, https://github.com/rk700/PyMuPDF. In the demo directory youwill find an updated version of this script,which no longer relies on external picture files to generate the coffee background.