Skip to content

Commit

Permalink
Merge pull request #86 from pmaupin/pdfwriter_fname
Browse files Browse the repository at this point in the history
Allow PdfWriter() to be given a filename on instantiation
  • Loading branch information
pmaupin authored Apr 8, 2017
2 parents d49024b + dbae8bc commit 09327d6
Show file tree
Hide file tree
Showing 15 changed files with 70 additions and 28 deletions.
4 changes: 2 additions & 2 deletions examples/4up.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get4(srcpages):
inpfn, = sys.argv[1:]
outfn = '4up.' + os.path.basename(inpfn)
pages = PdfReader(inpfn).pages
writer = PdfWriter()
writer = PdfWriter(outfn)
for index in range(0, len(pages), 4):
writer.addpage(get4(pages[index:index + 4]))
writer.write(outfn)
writer.write()
4 changes: 1 addition & 3 deletions examples/alter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,4 @@

trailer = PdfReader(inpfn)
trailer.Info.Title = 'My New Title Goes Here'
writer = PdfWriter()
writer.trailer = trailer
writer.write(outfn)
PdfWriter(outfn, trailer=trailer).write()
2 changes: 1 addition & 1 deletion examples/booklet.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ def fixpage(*pages):

opages += ipages

PdfWriter().addpages(opages).write(outfn)
PdfWriter(outfn).addpages(opages).write()
4 changes: 2 additions & 2 deletions examples/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
pages = list(page_per_xobj(PdfReader(inpfn).pages, margin=0.5*72))
if not pages:
raise IndexError("No XObjects found")
writer = PdfWriter()
writer = PdfWriter(outfn)
writer.addpages(pages)
writer.write(outfn)
writer.write()
2 changes: 1 addition & 1 deletion examples/fancy_watermark.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,4 @@
PageMerge(page).add(wmark, prepend=underneath).render()

# Write out the destination file
PdfWriter().write(outfn, trailer)
PdfWriter(outfn, trailer=trailer).write()
4 changes: 2 additions & 2 deletions examples/poster.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def adjust(page, margin=36, scale=4.8):
inpfn, = sys.argv[1:]
outfn = 'poster.' + os.path.basename(inpfn)
reader = PdfReader(inpfn)
writer = PdfWriter()
writer = PdfWriter(outfn)
writer.addpage(adjust(reader.pages[0]))
writer.trailer.Info = IndirectPdfDict(reader.Info or {})
writer.write(outfn)
writer.write()
2 changes: 1 addition & 1 deletion examples/print_two.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ def fixpage(page, count=[0]):
inpfn, = sys.argv[1:]
outfn = 'print_two.' + os.path.basename(inpfn)
pages = PdfReader(inpfn).pages
PdfWriter().addpages(fixpage(x) for x in pages).write(outfn)
PdfWriter(outfn).addpages(fixpage(x) for x in pages).write()
4 changes: 2 additions & 2 deletions examples/rotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@
pages[pagenum].Rotate = (int(pages[pagenum].inheritable.Rotate or
0) + rotate) % 360

outdata = PdfWriter()
outdata = PdfWriter(outfn)
outdata.trailer = trailer
outdata.write(outfn)
outdata.write()
4 changes: 2 additions & 2 deletions examples/subset.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
ranges = ([int(y) for y in x.split('-')] for x in ranges)
outfn = 'subset.%s' % os.path.basename(inpfn)
pages = PdfReader(inpfn).pages
outdata = PdfWriter()
outdata = PdfWriter(outfn)

for onerange in ranges:
onerange = (onerange + onerange[-1:])[:2]
for pagenum in range(onerange[0], onerange[1]+1):
outdata.addpage(pages[pagenum-1])
outdata.write(outfn)
outdata.write()
2 changes: 1 addition & 1 deletion examples/subset_booklets.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,5 @@ def fixpage(*pages):
if len(ipages) >= 1:
opages.append(fixpage(ipages.pop(), ipages.pop(0)))

PdfWriter().addpages(opages).write(OUTFN)
PdfWriter(OUTFN).addpages(opages).write()
print 'It took '+ str(round(time.time()-START, 2))+' seconds to make the pdf subbooklets changes.'
4 changes: 2 additions & 2 deletions examples/unspread.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def splitpage(src):

inpfn, = sys.argv[1:]
outfn = 'unspread.' + os.path.basename(inpfn)
writer = PdfWriter()
writer = PdfWriter(outfn)
for page in PdfReader(inpfn).pages:
writer.addpages(splitpage(page))
writer.write(outfn)
writer.write()
2 changes: 1 addition & 1 deletion examples/watermark.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@
trailer = PdfReader(inpfn)
for page in trailer.pages:
PageMerge(page).add(wmark, prepend=underneath).render()
PdfWriter().write(outfn, trailer)
PdfWriter(outfn, trailer=trailer).write()
51 changes: 47 additions & 4 deletions pdfrw/pdfwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,44 @@ class PdfWriter(object):

_trailer = None
canonicalize = False
fname = None

def __init__(self, fname=None, version='1.3', compress=False, **kwargs):
"""
Parameters:
fname -- Output file name, or file-like binary object
with a write method
version -- PDF version to target. Currently only 1.3
supported.
compress -- True to do compression on output. Currently
compresses stream objects.
"""

# Legacy support: fname is new, was added in front
if fname is not None:
try:
float(fname)
except (ValueError, TypeError):
pass
else:
if version != '1.3':
assert compress == False
compress = version
version = fname
fname = None

self.fname = fname
self.version = version
self.compress = compress

if kwargs:
for name, value in iteritems(kwargs):
if name not in self.replaceable:
raise ValueError("Cannot set attribute %s "
"on PdfWriter instance" % name)
setattr(self, name, value)

def __init__(self, version='1.3', compress=False):
self.pagearray = PdfArray()
self.compress = compress
self.version = version
self.killobj = {}

def addpage(self, page):
Expand Down Expand Up @@ -301,10 +334,18 @@ def _set_trailer(self, trailer):

trailer = property(_get_trailer, _set_trailer)

def write(self, fname, trailer=None, user_fmt=user_fmt,
def write(self, fname=None, trailer=None, user_fmt=user_fmt,
disable_gc=True):

trailer = trailer or self.trailer

# Support fname for legacy applications
if (fname is not None) == (self.fname is not None):
raise PdfOutputError(
"PdfWriter fname must be specified exactly once")

fname = fname or self.fname

# Dump the data. We either have a filename or a preexisting
# file object.
preexisting = hasattr(fname, 'write')
Expand Down Expand Up @@ -340,3 +381,5 @@ def make_canonical(self):
workitems += obj
else:
workitems += obj.values()

replaceable = set(vars())
2 changes: 1 addition & 1 deletion tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def do_test(self, params, prev_results=[''], scrub=False):
os.remove(scrub)
subprocess.call(params)
if scrub:
PdfWriter().addpages(PdfReader(scrub).pages).write(dstf)
PdfWriter(dstf).addpages(PdfReader(scrub).pages).write()
with open(dstf, 'rb') as f:
data = f.read()
size = len(data)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,12 @@ def roundtrip(self, testname, basename, srcf, decompress=False,
result = 'skip -- encrypt'
hash = '------skip-encrypt-no-file------'
return self.skipTest('File encrypted')
writer = pdfrw.PdfWriter(compress=compress)
writer = pdfrw.PdfWriter(dstf, compress=compress)
if repaginate:
writer.addpages(trailer.pages)
trailer = None
writer.write(dstf, trailer)
else:
writer.trailer = trailer
writer.write()
with open(dstf, 'rb') as f:
data = f.read()
size = len(data)
Expand Down

0 comments on commit 09327d6

Please sign in to comment.