repl.it
@anonymous/

AmbitiousWorthwhileExperiment

Python

No description

fork
loading
Files
  • main.py
  • Packager files
  • requirements.txt
main.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os, sys, tempfile, logging, gc
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm, inch
from reportlab.lib.pagesizes import letter, landscape
from PyPDF2 import PdfFileWriter, PdfFileReader
import objgraph, weakref

# Get pdf size
# https://stackoverflow.com/a/46252380
# Switch the size on the fly
# https://stackoverflow.com/a/5936903

def stamp_page(ipdf, wmark, opdf, x_coor, y_coor, stamp_text):
	source_pdf = PdfFileReader(open(ipdf, "rb"))
	print("There are %s pages " % (str(source_pdf.getNumPages())))

	pdf_page = source_pdf.getPage(0)
	size = get_page_size(pdf_page) # orientation might change per page
	if size[0] < size[1]: # check if portrait
		print("Page is portrait")
		c = canvas.Canvas(ofile, pagesize=size)
	else: # page is horizontal
		print("Page is landscape")
		c = canvas.Canvas(ofile, pagesize=landscape(size))
	c.drawImage(wmark, float(x_coor*cm), size[1]-float(y_coor*cm), preserveAspectRatio=True, anchor='nw')
	c.save() # ofile is now buffer w/ wmark at x,y
	z = weakref.ref(c)
	
	objgraph.show_most_common_types()
	for page in range(source_pdf.getNumPages()):
		pdf_page = source_pdf.getPage(page)
		pdf_writer = PdfFileWriter()
		wmark_page = PdfFileReader(ofile, "rb") # ofile is wmarked pdf
		pdf_page.mergePage(wmark_page.getPage(0))
		pdf_writer.addPage(pdf_page) #saves stamped pg to buffer

		with open("page-%03d.pdf" % int(page+1), "wb") as pg:
			pdf_writer.write(pg) #write buffer to file
			upload_page(pg)

		gc.collect()
		objgraph.show_most_common_types()
		objgraph.show_refs([z,c], filename="graph.png")
		objgraph.show_backrefs([z,c], filename="graph.png")

def upload_page(ipdf):
	print("I would have uploaded a page at this point.")
def get_page_size(page):
	# p = page.getPage(1)
	w = float(page.mediaBox.getWidth()) * 0.352
	h = float(page.mediaBox.getHeight()) * 0.352
	print("Page is %s by %s" % (str(w), str(h)))

	return (w, h)

# args for testing
ifile, watermark, x_coor, y_coor, ofile = sys.argv[1:]

try:
	stamp_page(ifile, watermark, ofile, float(x_coor), float(y_coor), "test")
except KeyboardInterrupt:
	print("Okay, I'll stop now")
	sys.exit()

print("All done")
sys.exit()
# Make a blank page based on the sample pdf size
# Add the stamp to the blank page
# Spit out the stamped page
# Later in a different function, merge the pages back together.
Fetching token
?