本文整理汇总了Python中pyPdf.PdfFileWriter.write方法的典型用法代码示例。如果您正苦于以下问题:Python PdfFileWriter.write方法的具体用法?Python PdfFileWriter.write怎么用?Python PdfFileWriter.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyPdf.PdfFileWriter
的用法示例。
在下文中一共展示了PdfFileWriter.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: into_half
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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()
示例2: createPDFHttpResponse
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [as 别名]
def createPDFHttpResponse(filepath, output_filename, user, access_time):
"""
Creates a HttpResponse from a watermarked PDF file. Watermark contains the user who accessed the document
and the time of access.
:param filepath: Path to the file
:param output_filename: File name sent to the user
:param user:
:param access_time:
:return: HttpResponse with the file content, or HttpResponseNotFound
"""
#Add access watermark
buffer = StringIO()
p = canvas.Canvas(buffer)
p.drawString(0,0, "Downloaded by %s at %s" %(user, access_time.isoformat(' ')))
p.showPage()
p.save()
buffer.seek(0)
watermark = PdfFileReader(buffer)
#Read the PDF to be accessed
attachment = PdfFileReader(open(filepath, 'rb'))
output = PdfFileWriter()
#Attach watermark to each page
for page in attachment.pages:
page.mergePage(watermark.getPage(0))
output.addPage(page)
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'inline; filename=%s' % output_filename.encode('utf-8')
output.write(response)
return response
示例3: merge
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [as 别名]
def merge(fppath, bppath, outputpath, no_delete, fed_backwards):
fpfile = PdfFileReader(open(fppath))
bpfile = PdfFileReader(open(bppath))
outputfile = PdfFileWriter()
outputpages = []
for i in range(fpfile.getNumPages()):
backpages = True
try:
outputpages.append(fpfile.getPage(i))
if backpages:
if fed_backwards:
outputpages.append(bpfile.getPage(bpfile.getNumPages() - i - 1))
else:
outputpages.append(bpfile.getPage(i))
except IndexError:
backpages = False
if not no_delete:
outputpages = [page for page in outputpages if page.extractText() != '']
[outputfile.addPage(page) for page in outputpages]
outputfile.write(open(os.path.expanduser(outputpath), 'w'))
示例4: save
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [as 别名]
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: split_chapters
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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,)
示例6: cat
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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")
示例7: __init__
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [as 别名]
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: get_chapters
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [as 别名]
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
示例9: add_guides
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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'))
示例10: concatenate_pdf
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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: generate
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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)
示例12: setMetadata
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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()
示例13: renderToPdf
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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()
示例14: join_pages
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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)
示例15: select
# 需要导入模块: from pyPdf import PdfFileWriter [as 别名]
# 或者: from pyPdf.PdfFileWriter import write [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")