本文整理汇总了Python中pyPdf.PdfFileWriter.addPage方法的典型用法代码示例。如果您正苦于以下问题:Python PdfFileWriter.addPage方法的具体用法?Python PdfFileWriter.addPage怎么用?Python PdfFileWriter.addPage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyPdf.PdfFileWriter
的用法示例。
在下文中一共展示了PdfFileWriter.addPage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_source_pdf
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
def create_source_pdf(self, cr, uid, ids, data, report_xml, context=None):
flag=False
if not context:
context={}
pool = pooler.get_pool(cr.dbname)
attach = report_xml.attachment
#~
#~ Check in the new model if this report allow to reprint,
#~ Allowtoreprint should mandate over attach,
if attach:
objs = self.getObjects(cr, uid, ids, context)
results = []
for obj in objs:
aname = eval(attach, {'object':obj, 'time':time})
result = False
if report_xml.attachment_use and aname and context.get('attachment_use', True):
aids = pool.get('ir.attachment').search(cr, uid, [('datas_fname','=',aname+'.pdf'),('res_model','=',self.table),('res_id','=',obj.id)])
if aids:
brow_rec = pool.get('ir.attachment').browse(cr, uid, aids[0])
if not brow_rec.datas:
continue
d = base64.decodestring(brow_rec.datas)
results.append((d,'pdf'))
continue
result = self.create_single_pdf(cr, uid, [obj.id], data, report_xml, context)
if not result:
return False
try:
if aname:
flag=True #ya que entra solo la primera vez sin attachment
name = aname+'.'+result[1]
pool.get('ir.attachment').create(cr, uid, {
'name': aname,
'datas': base64.encodestring(result[0]),
'datas_fname': name,
'res_model': self.table,
'res_id': obj.id,
}, context=context
)
cr.commit()
except Exception,e:
import traceback, sys
tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR,str(e))
results.append(result)
if results:
if results[0][1]=='pdf':
if not context.get('allow',False):
return self.create_single_pdf(cr, uid, ids, data, report_xml, context)
else:
from pyPdf import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
for r in results:
reader = PdfFileReader(cStringIO.StringIO(r[0]))
for page in range(reader.getNumPages()):
output.addPage(reader.getPage(page))
s = cStringIO.StringIO()
output.write(s)
return s.getvalue(), results[0][1]
示例2: split_chapters
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
def split_chapters(*t_args):
"""
Split a large pdf into chunks (i.e. chapters)
"""
if len(t_args)>0:
args=t_args[0]
if len(args)<1:
print "usage: utils_pdf split_chapters configfile"
return
from pyPdf import PdfFileWriter, PdfFileReader
f = open(args[0])
P = json.loads(f.read())
f.close()
input = PdfFileReader(file(P["source"], "rb"))
i0 = P["first_chapter_index"]
ends = P["chapters_ends"]
for i in xrange(0, len(ends)):
ch_num = i0+i
fmt = P["chapter_fmt"] % (ch_num, )
output = PdfFileWriter()
if not os.path.exists(P["outputdir"]):
os.mkdir( P["outputdir"])
fn_out = "%s/%s%s" % (P["outputdir"], P["chapter_prefix"], fmt)
j0 = P["firstpage"] if i==0 else ends[i-1]
for j in xrange(j0, ends[i]):
output.addPage(input.getPage(j))
outputStream = file(fn_out, "wb")
output.write(outputStream)
outputStream.close()
print "wrote %s" % (fn_out,)
示例3: rewrite
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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: parse_file
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
def parse_file(pdfFile,nameFile):
pdfReader = PdfFileReader(file(pdfFile,"rb"))
# read the names and emails from csv file
names = get_names(nameFile)
# create an instance in SMTP server
smtp = smtplib.SMTP('localhost')
# loop through the pages of the pdf
# when a name is found, write pages to a new pdf until next name is found
# then write the file and email as attachment
i = 0
prevName = ""
while i<pdfReader.getNumPages():
page = pdfReader.getPage(i)
pageStr = page.extractText() # extract the pdf text
for name in names.keys():
if pageStr.lower().find(name.lower())!=-1:
if 'pdfWriter' in locals(): # send the current pdf
send_email(smtp,pdfWriter,prevName,names)
pdfWriter = PdfFileWriter() # create new pdfWriter file and add current page
prevName = name # save off previous name
break
if 'pdfWriter' in locals():
pdfWriter.addPage(page)
i+=1
# send the last file
if 'pdfWriter' in locals():
send_email(smtp,pdfWriter,prevName,names)
# quit the smtp server
smtp.quit()
示例5: cat
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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")
示例6: __call__
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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
示例7: generate
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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)
示例8: add_guides
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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: setMetadata
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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()
示例10: concatenate_pdf
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
def concatenate_pdf(self,book_title):
fileList = os.listdir(os.getcwd())
num_chapters=0
for i in range(1,40):
if not fileList.__contains__(book_title+str(i)+".pdf"):
num_chapters= i-1
print "numero capitulos"+str(num_chapters)
break
print"Uniendo pfs..."
output = PdfFileWriter()
for i in range (1,num_chapters):
f=open(book_title+str(i)+".pdf", "rb")
num_pages=PdfFileReader(f).getNumPages()
if num_pages==0:
pdfOne = PdfFileReader(f).getPage(0)
output.addPage(pdfOne)
else:
for a in range (0,num_pages):
pdfOne = PdfFileReader(f).getPage(a)
output.addPage(pdfOne)
outputStream = file(r""+book_title+".pdf", "wb")
output.write(outputStream)
outputStream.close()
print"Union finalizada"
for i in range(1,num_chapters+1):
print "borrando... capitulo: "+str(i)
os.remove(book_title+str(i)+".pdf")
示例11: renderToPdf
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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()
示例12: join_pages
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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)
示例13: into_half
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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()
示例14: select
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
def select(filesandranges, outputfilename, verbose):
if verbose: print (str(filesandranges)+"\noutput: "+str(outputfilename))
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:
fiel = PdfFileReader(file(pdf["name"], "rb"))
for pagenr in pdf["pages"]:
if (not (pagenr > fiel.getNumPages()) and not(pagenr < 1)):
output.addPage(fiel.getPage(pagenr-1))
else:
print("one or more pages are not in the chosen PDF")
halp()
sys.exit(3) #wrong pages or ranges
except:
halp()
sys.exit(2) # pdf file is no pdf file...h
if (not os.path.exists(outputfilename)):
outputStream = file(outputfilename, "wb")
output.write(outputStream)
outputStream.close()
else:
print ("file exists, discontinuing operation")
示例15: output
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import addPage [as 别名]
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()