Skip to content

Commit

Permalink
Initial commit of sandbox files
Browse files Browse the repository at this point in the history
  • Loading branch information
sfneal committed Aug 21, 2018
1 parent 0543e38 commit 0adcfc8
Show file tree
Hide file tree
Showing 7 changed files with 350 additions and 0 deletions.
57 changes: 57 additions & 0 deletions sandbox/img_opacity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Modify the opacity of an image file
import os
from PIL import Image, ImageEnhance


def _add_suffix(file_path, suffix, sep='_', ext=None):
"""Adds suffix to a file name seperated by an underscore and returns file path."""
# Split file_path on last '.' to separate file_name and file_extension
split = os.path.basename(file_path).rsplit('.', 1)

# Use original file_extension if None is given
ext = split[1] if not ext else ext.strip('.')

# Rebuild new file_path with suffix
return os.path.join(os.path.dirname(file_path), split[0] + sep + suffix + '.' + ext)


def img_opacity(image, opacity):
"""
Reduce the opacity of a PNG image.
Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
:param image: PNG image file
:param opacity: float representing opacity percentage
:return: Path to modified PNG
"""
# Validate parameters
assert 0 <= opacity <= 1, 'Opacity must be a float between 0 and 1'
assert os.path.isfile(image), 'Image is not a file'

# Open image in RGBA mode if not already in RGBA
im = Image.open(image)
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()

# Adjust opacity
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)

# Save modified image file
dst = _add_suffix(image, str(str(int(opacity * 100)) + '%'), ext='.png')
im.save(dst)
return dst


def main():
image = '/Users/Stephen/Desktop/test.jpg'
opacity = 0.15
img_opacity(image, opacity)


if __name__ == '__main__':
main()
11 changes: 11 additions & 0 deletions sandbox/open_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# View directories and files in a window
from pathlib import Path
from subprocess import call, Popen


def open_window(path):
"""Open path in finder or explorer window"""
try:
call(["open", "-R", str(Path(str(path)))])
except FileNotFoundError:
Popen(r'explorer /select,' + str(Path(str(path))))
45 changes: 45 additions & 0 deletions sandbox/pdfrw_rotate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Rotate a pdf file
import os
from tempfile import NamedTemporaryFile
from pdfrw import PdfReader, PdfWriter


def add_suffix(file_path, suffix, sep):
split = os.path.basename(file_path).rsplit('.', 1)
return os.path.join(os.path.dirname(file_path), split[0] + sep + suffix + '.' + split[1])


def rotate(file_name, rotate, suffix='rotated', tempdir=None):
"""Rotate PDF by increments of 90 degrees."""
# Set output file name
if tempdir:
outfn = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name
elif suffix:
outfn = os.path.join(os.path.dirname(file_name), add_suffix(file_name, suffix))
else:
outfn = NamedTemporaryFile(suffix='.pdf').name

trailer = PdfReader(file_name)
pages = trailer.pages

ranges = [[1, len(pages)]]

for onerange in ranges:
onerange = (onerange + onerange[-1:])[:2]
for pagenum in range(onerange[0] - 1, onerange[1]):
pages[pagenum].Rotate = (int(pages[pagenum].inheritable.Rotate or 0) + rotate) % 360

outdata = PdfWriter(outfn)
outdata.trailer = trailer
outdata.write()
return outfn


def main():
pdf = 'your/path/to/doc.pdf'
r = 90
rotate(pdf, r)


if __name__ == '__main__':
main()
46 changes: 46 additions & 0 deletions sandbox/pdfrw_upscale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Upscale a PDF file
import os
from tempfile import NamedTemporaryFile
from pdfrw import PdfReader, PdfWriter, PageMerge, IndirectPdfDict


def add_suffix(file_path, suffix, sep):
split = os.path.basename(file_path).rsplit('.', 1)
return os.path.join(os.path.dirname(file_path), split[0] + sep + suffix + '.' + split[1])


def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None):
"""Upscale a PDF to a large size."""
def adjust(page):
info = PageMerge().add(page)
x1, y1, x2, y2 = info.xobj_box
viewrect = (margin_x, margin_y, x2 - x1 - 2 * margin_x, y2 - y1 - 2 * margin_y)
page = PageMerge().add(page, viewrect=viewrect)
page[0].scale(scale)
return page.render()

# Set output file name
if tempdir:
output = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name
elif suffix:
output = os.path.join(os.path.dirname(file_name), add_suffix(file_name, suffix))
else:
output = NamedTemporaryFile(suffix='.pdf').name

reader = PdfReader(file_name)
writer = PdfWriter(output)
for i in list(range(0, len(reader.pages))):
writer.addpage(adjust(reader.pages[i]))
writer.trailer.Info = IndirectPdfDict(reader.Info or {})
writer.write()
return output


def main():
pdf = 'your/path/to/doc.pdf'
scale = 1.0
upscale(pdf, scale)


if __name__ == '__main__':
main()
82 changes: 82 additions & 0 deletions sandbox/pdftk_encrypt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
Encrypt a PDF file using pdftk
pdftk server must be installed on your machine
https://www.pdflabs.com/tools/pdftk-server/
"""
import os
from PyPDF2 import PdfFileReader


# Replace with your own pdftk path
PDFTK_PATH = '/opt/pdflabs/pdftk/bin/pdftk'


def get_pdftk_path():
if os.path.exists(PDFTK_PATH):
return PDFTK_PATH


def add_suffix(file_path, suffix):
"""Adds suffix to a file name seperated by an underscore and returns file path."""
split = os.path.basename(file_path).rsplit('.', 1)
ext = split[1]
name = split[0]
out = str(name + '_' + suffix + '.' + ext)
return os.path.join(os.path.dirname(file_path), out)


def secure(pdf, user_pw, owner_pw, restrict_permission=True, pdftk=get_pdftk_path(), output=None):
"""
Encrypt a PDF file and restrict permissions to print only.
Utilizes pdftk command line tool.
:param pdf: Path to PDF file
:param user_pw: Password to open and view
:param owner_pw: Password to modify permissions
:param restrict_permission: Restrict permissions to print only
:param pdftk: Path to pdftk binary
:param output: Output path
:return: Output path
"""
if pdftk:
# Check that PDF file is encrypted
with open(pdf, 'rb') as f:
reader = PdfFileReader(f)
if reader.isEncrypted:
print('PDF is already encrypted')
return pdf

# Create output filename if not already set
if not output:
output = add_suffix(pdf, 'secured')

# Replace spaces within paths with backslashes followed by a space
pdf_en = pdf.replace(' ', '\ ')
output_en = output.replace(' ', '\ ')

# Concatenate bash command
command = pdftk + ' ' + pdf_en + ' output ' + output_en + ' owner_pw ' + owner_pw + ' user_pw ' + user_pw

# Append string to command if printing is allowed
if restrict_permission:
command += ' allow printing'

# Execute command
os.system(command)
print('Secured PDF saved to...', output)
return output
else:
print('Unable to locate pdftk binary')


def main():
pdf = 'path/to/your/pdf.pdf'
u = 'userpassword'
p = 'ownerpassword'
secure(pdf, u, p)


if __name__ == '__main__':
main()
45 changes: 45 additions & 0 deletions sandbox/pypdf3_rotate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Rotate a pdf file
import os
from tempfile import NamedTemporaryFile
try:
from PyPDF3 import PdfFileReader, PdfFileWriter
except ImportError:
from PyPDF2 import PdfFileReader, PdfFileWriter


def add_suffix(file_path, suffix, sep):
split = os.path.basename(file_path).rsplit('.', 1)
return os.path.join(os.path.dirname(file_path), split[0] + sep + suffix + '.' + split[1])


def rotate(file_name, rotate, suffix='rotated', tempdir=None):
"""Rotate PDF by increments of 90 degrees."""
# Set output file name
if tempdir:
outfn = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name
elif suffix:
outfn = os.path.join(os.path.dirname(file_name), add_suffix(file_name, suffix))
else:
outfn = NamedTemporaryFile(suffix='.pdf').name

with open(file_name, 'rb') as pdf_in:
pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader(pdf_in)
for pagenum in range(pdf_reader.numPages):
page = pdf_reader.getPage(pagenum)
page.rotateClockwise(rotate)
pdf_writer.addPage(page)

with open(outfn, 'wb') as pdf_out:
pdf_writer.write(pdf_out)
return outfn


def main():
pdf = 'your/path/to/doc.pdf'
r = 90
rotate(pdf, r)


if __name__ == '__main__':
main()
64 changes: 64 additions & 0 deletions sandbox/pypdf3_upscale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Upscale a PDF file
import os
from tempfile import NamedTemporaryFile

try:
from PyPDF3 import PdfFileReader, PdfFileWriter
from PyPDF3.pdf import PageObject
except ImportError:
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import PageObject


def dimensions(path):
"""Get width and height of a PDF"""
pdf = PdfFileReader(path)
size = pdf.getPage(0).mediaBox
return {'w': float(size[2]), 'h': float(size[3])}


def add_suffix(file_path, suffix, sep):
split = os.path.basename(file_path).rsplit('.', 1)
return os.path.join(os.path.dirname(file_path), split[0] + sep + suffix + '.' + split[1])


def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None):
"""Upscale a PDF to a large size."""
# Set output file name
if tempdir:
output = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name
elif suffix:
output = os.path.join(os.path.dirname(file_name), add_suffix(file_name, suffix))
else:
output = NamedTemporaryFile(suffix='.pdf').name

reader = PdfFileReader(file_name)
writer = PdfFileWriter()
dims = dimensions(file_name)
target_w = dims['w'] * scale
target_h = dims['h'] * scale

# Number of pages in input document
page_count = reader.getNumPages()

for page_number in range(page_count):
wtrmrk = reader.getPage(page_number)

page = PageObject.createBlankPage(width=target_w, height=target_h)
page.mergeScaledTranslatedPage(wtrmrk, scale, margin_x, margin_y)
writer.addPage(page)

with open(output, "wb") as outputStream:
writer.write(outputStream)

return output


def main():
pdf = 'your/path/to/doc.pdf'
scale = 1.0
upscale(pdf, scale)


if __name__ == '__main__':
main()

0 comments on commit 0adcfc8

Please sign in to comment.