本文整理汇总了Python中pyPdf.PdfFileWriter类的典型用法代码示例。如果您正苦于以下问题:Python PdfFileWriter类的具体用法?Python PdfFileWriter怎么用?Python PdfFileWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PdfFileWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: into_half
def into_half(src, dst):
_src = file(src, 'rb')
_dst = file(dst, 'wb')
input = PdfFileReader(_src)
output = PdfFileWriter()
for i in range(input.getNumPages()):
p = input.getPage(i)
q = copy.copy(p)
q.mediaBox = copy.copy(p.mediaBox)
#x1, x2 = p.mediaBox.lowerLeft
#x3, x4 = p.mediaBox.upperRight
(w, h) = p.mediaBox.upperRight
print w, h
p.mediaBox.upperRight = (w/2, h)
q.mediaBox.upperLeft = (w/2, h)
output.addPage(p)
output.addPage(q)
output.write(_dst)
_src.close()
_dst.close()
示例2: buildPdf
def buildPdf(self):
to_pdffile = self._takeoff()
ap_pdffile = self._airplane()
ck_pdffile = self._checklist()
output = PdfFileWriter()
self.addAllPages(output, PdfFileReader(file(ck_pdffile, "rb")))
self.addAllPages(output, PdfFileReader(file(to_pdffile, "rb")))
self.addAllPages(output, PdfFileReader(file(ap_pdffile, "rb")))
# Add AD Info Charts
files = dict()
for pdf in self.getExternalPdf(self.eVfrPath, self.__fligthplan.performance_takeoff.aerodrome.code):
files[pdf] = file(pdf, "rb")
files["%s_" % pdf] = PdfFileReader(files[pdf])
if files["%s_" % pdf].getIsEncrypted():
pdfCracked = PdfCracker().crack(pdf)
files[pdf] = file(pdfCracked, "rb")
files["%s_" % pdf] = PdfFileReader(files[pdf])
self.addAllPages(output=output, input=files["%s_" % pdf])
# write out the merged file
outputPdf = os.path.join(self.outputdir, 'flightplan %s.pdf' % self.__fligthplan.title)
outputStream = file(outputPdf, "wb")
output.write(outputStream)
outputStream.close()
npyscreen.notify_confirm(
message="Your pretty Fligthplan has been created at\n\n%s" % outputPdf
)
示例3: rewrite
def rewrite(self, context, font={'name': 'Times-Roman', 'size': 11}):
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont(font['name'], font['size'])
for i in context:
can.drawString(i['x'], i['y'], i['value'])
can.save()
# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(self.path, "rb"))
output = PdfFileWriter()
# merge the new file with the existing
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file(self.destination, "wb")
output.write(outputStream)
outputStream.close()
return True
示例4: save
def save(self, to):
origin = self.get_origin()
if not origin:
raise RuntimeError("Please implement get_origin method or origin attribute")
try:
existing_pdf = PdfFileReader(file(origin, "rb"))
except IOError:
raise RuntimeError(u"Failed to open origin file")
output = PdfFileWriter()
for page_id, page_class in enumerate(self.pages):
new_page = page_class(self.instance).save()
base_page = existing_pdf.getPage(0)
base_page.mergePage(new_page)
output.addPage(base_page)
if isinstance(to, basestring):
outputStream = file(to, "wb")
else:
outputStream = to
output.write(outputStream)
outputStream.close()
示例5: add_omr_marks
def add_omr_marks(self, pdf_data, is_latest_document):
# Documentation
# http://meteorite.unm.edu/site_media/pdf/reportlab-userguide.pdf
# https://pythonhosted.org/PyPDF2/PdfFileReader.html
# https://stackoverflow.com/a/17538003
# https://gist.github.com/kzim44/5023021
# https://www.blog.pythonlibrary.org/2013/07/16/
# pypdf-how-to-write-a-pdf-to-memory/
self.ensure_one()
pdf_buffer = StringIO.StringIO()
pdf_buffer.write(pdf_data)
existing_pdf = PdfFileReader(pdf_buffer)
output = PdfFileWriter()
total_pages = existing_pdf.getNumPages()
# print latest omr mark on latest pair page (recto)
latest_omr_page = total_pages // 2
for page_number in range(total_pages):
page = existing_pdf.getPage(page_number)
# only print omr marks on pair pages (recto)
if page_number % 2 is 0:
is_latest_page = is_latest_document and \
page_number == latest_omr_page
marks = self._compute_marks(is_latest_page)
omr_layer = self._build_omr_layer(marks)
page.mergePage(omr_layer)
output.addPage(page)
out_buffer = StringIO.StringIO()
output.write(out_buffer)
return out_buffer.getvalue()
示例6: split_pset
def split_pset():
if (not options.pset or not options.probs):
print_err_and_die("You must enter both arguements! run with -h for help")
path = "pset%s/latex/"%options.pset
try:
filename = "%spset%s_answers.pdf"%(path, options.pset)
inp = PdfFileReader(file(filename, "rb"))
except IOError:
print_err_and_die("Error! File, %s was not found." % filename)
##loop over user input and break up pdf
questionNum = 1
probs = options.probs.split(",")
for prob in probs:
print "Processing question", questionNum
prob = prob.strip() #kill whitespace
out = PdfFileWriter()
pages = get_pages(prob, inp.getNumPages())
for page in pages:
print "page num", str(page)
out.addPage(inp.getPage(int(page)-1))
outStream = file("%spset%s-%s_answer.pdf"%(path, options.pset, questionNum), "wb")
out.write(outStream)
outStream.close()
questionNum +=1
print "Done!"
示例7: __init__
class cleanpdf:
def __init__(self,pathFile):
self.pathFile = pathFile
self.inputFile = file(self.pathFile,"rb")
self.pdfInput = PdfFileReader(self.inputFile)
self.pyPdfOutput = PdfFileWriter()
self.dataToUpdate = self.pyPdfOutput._info.getObject()
self.__modifyData()
self.__copyPDF()
def __modifyData(self):
for data in self.dataToUpdate:
self.dataToUpdate[data] = createStringObject(('<h1 onmouseover=alert(1)>').encode('ascii'))
def __copyPDF(self):
for page in range(0,self.pdfInput.getNumPages()):
self.pyPdfOutput.addPage(self.pdfInput.getPage(page))
outputFile = file(self.__changeName(),"wb")
self.pyPdfOutput.write(outputFile)
def __changeName(self):
newName = self.pathFile[0:self.pathFile.rfind(".")]+"5.pdf"
return newName
示例8: add_guides
def add_guides(self):
pdf_in = PdfFileReader(open('sig.pdf', 'rb'))
pdf_out = PdfFileWriter()
for i in xrange(pdf_in.getNumPages()):
page = pdf_in.getPage(i)
if not i:
guides = StringIO()
if self.args.longarm:
create_pdf(
guides, a4lwidth_pt, a4lheight_pt, generate_longarm())
else:
if self.args.a5:
w, h = a5width_pt, a5height_pt
else:
w, h = a4lwidth_pt, a4lheight_pt
create_pdf(guides, w, h, generate_shortarm(
self.args.a5, bool(self.args.signature)))
pdf_guides = PdfFileReader(guides)
page.mergePage(pdf_guides.getPage(0))
pdf_out.addPage(page)
pdf_out.write(open('sigs.pdf', 'wb'))
示例9: output
def output(self):
# get the output filename using the file dialog
(out_filename, filter) = \
QFileDialog.getSaveFileName(parent = self,
caption = self.tr(u'Export'),
dir = '',
filter = self.tr('pdf (*.pdf)'))
# file IO
out_file = open(out_filename, 'wb')
in_file = open(self.in_filename, 'rb')
in_reader = PdfFileReader(in_file)
out_writer = PdfFileWriter()
# extract input
pages_string = self.pages_line_edit.text()
# Get the indices of pages to extract
pages = pages_parser(in_reader.getNumPages()).parse(pages_string)
# append pages to output writer
for page_index in pages:
out_writer.addPage(in_reader.getPage(page_index))
# write to file
out_writer.write(out_file)
# close files
in_file.close()
out_file.close()
示例10: generate
def generate(donor):
os.system('mkdir -p output')
donor_url = donor.replace(' ','%20')
page1 = 'output/%s1' % (donor.replace(' ','-').lower())
page2 = 'output/%s2' % (donor.replace(' ','-').lower())
combined = 'output/%s.pdf' % (donor.replace(' ','-').lower())
if os.path.exists(combined): return
os.system('cp "%s" "%s.svg"' % (page1_svg, page1))
os.system('sed "s|/France/|/%s/|" "%s" > "%s.svg"' % (donor_url, page1_svg, page1))
os.system('inkscape --file="%s.svg" --verb=za.co.widgetlabs.update --verb=FileSave --verb=FileQuit 2> /dev/null' % (page1))
os.system('inkscape --file="%s.svg" --export-pdf="%s.pdf" 2> /dev/null' % (page1, page1))
os.system('cp "%s" "%s.svg"' % (page2_svg, page2))
os.system('sed "s|/France/|/%s/|" "%s" > "%s.svg"' % (donor_url, page2_svg, page2))
os.system('inkscape --file="%s.svg" --verb=za.co.widgetlabs.update --verb=FileSave --verb=FileQuit 2> /dev/null' % (page2))
os.system('inkscape --file="%s.svg" --export-pdf="%s.pdf" ' % (page2, page2))
# Merge pages
input1 = PdfFileReader(file('%s.pdf' % (page1), 'rb'))
input2 = PdfFileReader(file('%s.pdf' % (page2), 'rb'))
output = PdfFileWriter()
output.addPage(input1.getPage(0))
output.addPage(input2.getPage(0))
outputStream = file(combined, 'wb')
output.write(outputStream)
outputStream.close()
sleep(2)
示例11: get_chapters
def get_chapters():
for url in download_list:
output = PdfFileWriter()
errored = False
if url:
filename = url[0].split('/')[-1]
p = re.compile('(?<=kap)\d{1,3}')
chap = p.search(filename).group()
chap = chap[:-1]
print "Doing chapter", chap
for u in url:
try:
pdf = urllib2.urlopen(u).read()
mem_file = StringIO(pdf)
append_pdf(PdfFileReader(mem_file), output)
except Exception, e:
print "Error for chapter " + chap + ": " + str(e)
errored = True
pass
try:
if not errored:
output.write(file("algs-kap" + chap + ".pdf", "wb"))
print "Assembled pdf at algs-"+ chap + ".pdf"
else:
print "Couldn't get chapter, not assembled"
except Exception, e:
print "Error ocurred!"
print e
示例12: setMetadata
def setMetadata(self, metadata):
"""Returns a document with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
# TODO: date as "D:20090401124817-04'00'" ASN.1 for ModDate and CreationDate
input_pdf = PdfFileReader(open(self.document.getUrl(), "rb"))
output_pdf = PdfFileWriter()
modification_date = metadata.pop("ModificationDate", None)
if modification_date:
metadata['ModDate'] = modification_date
if type(metadata.get('Keywords', None)) is list:
metadata['Keywords'] = metadata['Keywords'].join(' ')
args = {}
for key, value in list(metadata.items()):
args[NameObject('/' + key.capitalize())] = createStringObject(value)
output_pdf._info.getObject().update(args)
for page_num in range(input_pdf.getNumPages()):
output_pdf.addPage(input_pdf.getPage(page_num))
output_stream = io.BytesIO()
output_pdf.write(output_stream)
return output_stream.getvalue()
示例13: renderToPdf
def renderToPdf(envLL, filename, sizex, sizey):
"""Renders the specified Box2d and zoom level as a PDF"""
basefilename = os.path.splitext(filename)[0]
mergedpdf = None
for mapname in MAPNIK_LAYERS:
print 'Rendering', mapname
# Render layer PDF.
localfilename = basefilename + '_' + mapname + '.pdf';
file = open(localfilename, 'wb')
surface = cairo.PDFSurface(file.name, sizex, sizey)
envMerc = LLToMerc(envLL)
map = mapnik.Map(sizex, sizey)
mapnik.load_map(map, mapname + ".xml")
map.zoom_to_box(envMerc)
mapnik.render(map, surface)
surface.finish()
file.close()
# Merge with master.
if not mergedpdf:
mergedpdf = PdfFileWriter()
localpdf = PdfFileReader(open(localfilename, "rb"))
page = localpdf.getPage(0)
mergedpdf.addPage(page)
else:
localpdf = PdfFileReader(open(localfilename, "rb"))
page.mergePage(localpdf.getPage(0))
output = open(filename, 'wb')
mergedpdf.write(output)
output.close()
示例14: join_pages
def join_pages(composites):
# latex_buf = StringIO()
page_fnames = []
for page_num, collection in enumerate(collect_pages(composites)):
fnames, transcriptions, types = [], [], []
for r in collection:
fnames.append(r['location'])
transcriptions.append(r['transcription'])
types.append(r['type'])
page_fnames.append(paint_original_segments(fnames, transcriptions, page_num))
# latex_buf.write(assemble_latex(fnames, transcriptions, types))
# latex_buf.write(LATEX_NEWPAGE_SNIPPET)
# raw_latex = LATEX_WRAP.format(raw_latex=latex_buf.getvalue(), font_size=LATEX_FONT_SIZE)
# # transcribed pdf
# latex_pdf_fname = latex_to_pdf(raw_latex)
# ---
# searchable pdf
pdf_writer = PdfFileWriter()
pdf_pages = []
for page_fname in page_fnames:
pdf_pages.append(open(page_fname, 'rb'))
pdf_reader = PdfFileReader(pdf_pages[-1])
pdf_writer.addPage(pdf_reader.getPage(0))
searchable_pdf = NamedTemporaryFile(prefix='searchable_', suffix='.pdf', dir=path.abspath('./static/images/'), delete=False)
pdf_writer.write(searchable_pdf)
searchable_pdf.close()
map(lambda f: f.close(), pdf_pages)
json.dump({
# 'transcribed': latex_pdf_fname,
'searchable': searchable_pdf.name
}, sys.stdout)
示例15: delete
def delete(filesandranges, outputfilename, verbose):
for i in range(len(filesandranges)):
if not os.path.exists(filesandranges[i]['name']):
halp()
print ("error: "+filesandranges[i]['name']+" does not exist... exiting nao")
sys.exit(2) # pdf file is no pdf file...
if os.path.exists(outputfilename):
halp()
print ("error: "+filesandranges[i]['name']+" does already exist... exiting nao")
sys.exit(2) # pdf file is no pdf file...
output = PdfFileWriter()
try:
for pdf in filesandranges:
print (pdf["name"])
fiel = PdfFileReader(file(pdf["name"], "rb"))
for pagenr in range(1,fiel.getNumPages()+1):
if (pagenr not in pdf["pages"]):
output.addPage(fiel.getPage(pagenr-1))
# else:
# print ("skipping page nr: "+str(pagenr))
except:
halp()
sys.exit(2) # pdf file is no pdf file...
if (not os.path.exists(outputfilename)):
outputStream = file(outputfilename, "wb")
output.write(outputStream)
outputStream.close()
else:
print ("file exists, discontinuing operation")