"""Build five original field-note pages with independently oriented pixels and selectable text.""" from contextlib import closing from io import BytesIO from pathlib import Path from pypdf import PdfWriter from pypdf.generic import DictionaryObject, NameObject, NumberObject, DecodedStreamObject import pypdfium2 as pdfium DEST = Path(__file__).resolve().parent size = 360 font = DictionaryObject({NameObject("/Type"):NameObject("/Font"),NameObject("/Subtype"):NameObject("/Type1"), NameObject("/BaseFont"):NameObject("/Helvetica")}) def content(writer, page, commands): obj = DecodedStreamObject() obj.set_data(commands.encode("ascii")) page[NameObject("/Contents")] = writer._add_object(obj) def words(title, hidden=False): mode = 3 if hidden else 0 return (f"BT /F 21 Tf {mode} Tr 1 0 0 1 30 280 Tm ({title}) Tj /F 12 Tf 0 -44 Td " "(Stream gauge at North Bridge) Tj 0 -21 Td (Morning reading 1.24 metres) Tj " "0 -21 Td (Afternoon reading 1.30 metres) Tj ET") def make_image(title): source = PdfWriter() p = source.add_blank_page(size,size) p[NameObject("/Resources")] = DictionaryObject({NameObject("/Font"):DictionaryObject({NameObject("/F"):font})}) content(source, p, "0.85 g 30 310 300 4 re f 0 g " + words(title)) buf = BytesIO() source.write(buf) with pdfium.PdfDocument(buf.getvalue()) as doc, closing(doc[0]) as p, closing(p.render(scale=1.5)) as bitmap: return bitmap.to_pil().convert("L") def make(): writer = PdfWriter() sideways = "0 1 -1 0 360 0 cm " titles = ["North Bridge I","North Bridge II","North Bridge III","North Bridge IV","North Bridge V"] for n,title in enumerate(titles,1): image = make_image(title) p = writer.add_blank_page(size,size) obj = DecodedStreamObject() obj.set_data(image.tobytes()) obj = obj.flate_encode() for key,value in (("Type","XObject"),("Subtype","Image"),("ColorSpace","DeviceGray")): obj[NameObject("/"+key)] = NameObject("/"+value) for key,value in (("Width",image.width),("Height",image.height),("BitsPerComponent",8)): obj[NameObject("/"+key)] = NumberObject(value) p[NameObject("/Resources")] = DictionaryObject({ NameObject("/XObject"):DictionaryObject({NameObject("/Scan"):writer._add_object(obj)}), NameObject("/Font"):DictionaryObject({NameObject("/F"):font})}) scan_transform = sideways if n==2 else "" text_transform = sideways if n in (2,4) else "" commands = "q "+scan_transform+"360 0 0 360 0 0 cm /Scan Do Q" if n != 3: commands += " q "+text_transform+words(title,True)+" Q" content(writer,p,commands) if n==5: p.rotate(270) writer.write(DEST / "field-notes.pdf") if __name__ == "__main__": make()