本文整理汇总了Python中pyPdf.PdfFileWriter类的典型用法代码示例。如果您正苦于以下问题:Python PdfFileWriter类的具体用法?Python PdfFileWriter怎么用?Python PdfFileWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PdfFileWriter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:kaali-python,项目名称:Pdf-converter,代码行数:31,代码来源:into_half_vertical.py
示例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
)
开发者ID:tspycher,项目名称:pyaeromanager,代码行数:33,代码来源:flightplanbuilder.py
示例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
开发者ID:diegoloredo,项目名称:pyPdfFinder,代码行数:26,代码来源:writer.py
示例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()
开发者ID:wpjunior,项目名称:pdforms,代码行数:27,代码来源:document.py
示例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()
开发者ID:maxime-beck,项目名称:compassion-modules,代码行数:35,代码来源:communication_job.py
示例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!"
开发者ID:joshblum,项目名称:6.046-templating,代码行数:32,代码来源:split_pset.py
示例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
开发者ID:overxfl0w,项目名称:Grampus-Forensic-Utils,代码行数:28,代码来源:cleanpdf.py
示例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'))
开发者ID:pb-,项目名称:mkbooklet,代码行数:25,代码来源:main.py
示例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()
开发者ID:lokcon,项目名称:py-pdfsplit,代码行数:30,代码来源:pdf-split.py
示例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)
开发者ID:adieyal,项目名称:who-scorecards,代码行数:27,代码来源:generate.py
示例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
开发者ID:disturbedfood,项目名称:utilities,代码行数:29,代码来源:alg_getpdf.py
示例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()
开发者ID:Nexedi,项目名称:cloudooo,代码行数:26,代码来源:handler.py
示例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()
开发者ID:calvinmetcalf,项目名称:TopOSM,代码行数:29,代码来源:toposm.py
示例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)
开发者ID:zahanm,项目名称:transcrowdify,代码行数:31,代码来源:join.py
示例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")
开发者ID:kylewhite,项目名称:stapler,代码行数:32,代码来源:stapler.py
示例16: showpdf
def showpdf(request):
sign = os.path.join(settings.MEDIA_ROOT, "signature.png")
mimetypes.init()
response = None
if 'f' in request.GET:
fr = open(os.path.join(settings.MEDIA_ROOT,'pdffiles','extracted','%s' % request.GET['f']), "rb")
imgTemp = StringIO()
imgDoc = canvas.Canvas(imgTemp)
if request.GET['o'] == 'l':
imgDoc.drawImage(sign, 529, 40, 290/2, 154/2)
else:
imgDoc.drawImage(sign, 70, 40, 290/2, 154/2)
imgDoc.save()
overlay = PdfFileReader(StringIO(imgTemp.getvalue())).getPage(0)
page = PdfFileReader(fr).getPage(0)
page.mergePage(overlay)
pdf_out = PdfFileWriter()
pdf_out.addPage(page)
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % request.GET['f']
pdf_out.write(response)
return response
开发者ID:nisiotis,项目名称:dideman,代码行数:27,代码来源:views.py
示例17: cat
def cat(infilenames, outputfilename, verbose):
inputs = []
for infilename in infilenames:
print infilename
if not os.path.exists(infilename):
halp()
print ("error: "+infilename+" does not exist... exiting nao")
sys.exit(2) # pdf file is no pdf file...
if os.path.exists(outputfilename):
halp()
print ("error: "+outputfilename+" does already exist... exiting nao")
sys.exit(2) # pdf file is no pdf file...
try:
for i in infilenames:
inputs.append(PdfFileReader(file(i, "rb")))
except:
halp()
sys.exit(2) # pdf file is no pdf file...
i = 0
output = PdfFileWriter()
for pdf in inputs:
for pagenr in range(pdf.getNumPages()):
output.addPage(pdf.getPage(pagenr))
i=i+1
outputStream = file(outputfilename, "wb")
output.write(outputStream)
outputStream.close()
if verbose: print (str(i)+" pages processed")
开发者ID:kylewhite,项目名称:stapler,代码行数:30,代码来源:stapler.py
示例18: pdf
def pdf(coursesid,examsid):
''' Creates a blank PDF of this exam '''
# TODO: Obviously fix this up to generate actual PDFs; this is just a proof of concept
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from pyPdf import PdfFileWriter, PdfFileReader
from io import BytesIO
output = BytesIO()
p = canvas.Canvas(output, pagesize=letter)
p.drawString(100, 100, 'Hello')
p.save()
output.seek(0)
new_pdf = PdfFileReader(output)
existing_pdf = PdfFileReader(open('/home/treece/src/web/bubbleck/res/Template.pdf', 'rb'))
out = PdfFileWriter()
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
out.addPage(page)
a = BytesIO()
pdf_out = out.write(a)
response = make_response(pdf_out)
response.headers['Content-Disposition'] = "filename='sakulaci.pdf"
response.mimetype = 'application/pdf'
return response
开发者ID:taylorreece,项目名称:bubbleck,代码行数:29,代码来源:routes_exam.py
示例19: __call__
def __call__(self, data, attachments=[], pages=None):
self.rendered = {}
for field, ctx in self.fields.items():
if "template" not in ctx:
continue
self.context = ctx
kwargs = self.template_args(data)
template = self.context["template"]
try:
rendered_field = template.render(**kwargs)
except Exception as err:
logger.error("%s: %s %s", field, template, err)
else:
# Skip the field if it is already rendered by filter
if field not in self.rendered:
self.rendered[field] = rendered_field
filled = PdfFileReader(self.exec_pdftk(self.rendered))
for pagenumber, watermark in self.watermarks:
page = filled.getPage(pagenumber)
page.mergePage(watermark)
output = PdfFileWriter()
pages = pages or xrange(filled.getNumPages())
for p in pages:
output.addPage(filled.getPage(p))
for attachment in attachments:
output.addBlankPage().mergePage(attachment.pdf())
return output
开发者ID:Jenselme,项目名称:pdfjinja,代码行数:33,代码来源:pdfjinja.py
示例20: main
def main():
"""
"""
# Parse command line
pdf_files = sys.argv[1:]
if len(pdf_files) == 0:
print __usage__
sys.exit()
# Make sure there is more than one pdf file
if len(pdf_files) == 1:
print "In the spirit of gnu tar, this script cowardly refuses to"
print "combine one pdf file!"
sys.exit()
# Create unique name for output file
localtime = time.localtime()
localtime = [str(x) for x in localtime]
localtime = [x.zfill(2) for x in localtime]
localtime[0] = localtime[0].zfill(4)
output_file = "%s-%s-%s_%s-%s-%s.pdf" % tuple(localtime[:6])
# Combine pdf files in order
output = PdfFileWriter()
for pdf in pdf_files:
input = PdfFileReader(file(pdf,"rb"))
num_pages = input.getNumPages()
for i in range(num_pages):
output.addPage(input.getPage(i))
# Write final pdf
stream = file(output_file,"wb")
output.write(stream)
stream.close()
开发者ID:harmsm,项目名称:linux-utilities,代码行数:35,代码来源:combinePdf.py
注:本文中的pyPdf.PdfFileWriter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论