Skip to content

Instantly share code, notes, and snippets.

@kpmiller
Created September 11, 2018 18:58
Show Gist options
  • Save kpmiller/4662692297d253005e531d4edcfdf48c to your computer and use it in GitHub Desktop.
Save kpmiller/4662692297d253005e531d4edcfdf48c to your computer and use it in GitHub Desktop.
Example of using core graphics from quartz to make a pdf file, using Apple built in python bindings
#!/usr/bin/python
#tested on 10.12 and 10.13
import Quartz
from Quartz.CoreGraphics import *
import Cocoa
import random
random.seed()
url = Cocoa.CFURLCreateWithFileSystemPath(None,"/tmp/pdftest.pdf",kCFURLPOSIXPathStyle,False)
pr = CGRectMake(0,0,1000,1000)
page = CGPDFContextCreateWithURL(url, pr, None)
CGPDFContextBeginPage(page, None)
CGContextStrokeRect(page,pr)
for i in range(0,100):
x = random.randrange(0,900)
y = random.randrange(0,900)
w = random.randrange(0,200)
h = random.randrange(0,200)
linewidth = 3.0*random.random()
CGContextSetLineWidth(page, linewidth)
r = CGRectMake(x,y,w,h)
CGContextStrokeRect(page,r)
CGPDFContextEndPage(page)
CGPDFContextClose(page)
@kpmiller
Copy link
Author

kpmiller commented Dec 6, 2021

For my M1 running python3 on Monterery, I had to pip3 install -U pyobjc as per the instructions on https://pyobjc.readthedocs.io/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment