本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setPageSize方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setPageSize方法的具体用法?Python Canvas.setPageSize怎么用?Python Canvas.setPageSize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.setPageSize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: buildPDFx6
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def buildPDFx6(marginmm, urls):
width = 6 * inch
height = 4 * inch
square = 2 * inch
margin = marginmm * mm
card_width = square-(margin * 2)
buffer = StringIO()
pdf = Canvas(buffer)
pdf.setPageSize((width,height))
def create_image(url):
for i in [1,2]:
try:
return ImageReader(url)
except IOError:
pass
return ImageReader(url)
def put_image(x,y,url):
if url != "":
img = create_image(url)
pdf.drawImage(img,(square*x)+margin,(square*y)+margin,
width=card_width, height=card_width)
put_image(0,1,urls[0])
put_image(0,0,urls[1])
put_image(1,1,urls[2])
put_image(1,0,urls[3])
put_image(2,1,urls[4])
put_image(2,0,urls[5])
pdf.save()
data = buffer.getvalue()
buffer.close()
return data
示例2: make_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def make_pdf(outfn, xobjpairs):
canvas = Canvas(outfn)
for xobjlist in xobjpairs:
x = y = 0
for xobj in xobjlist:
x += xobj.BBox[2]
y = max(y, xobj.BBox[3])
canvas.setPageSize((x,y))
# Handle blank back page
if len(xobjlist) > 1 and xobjlist[0] == xobjlist[-1]:
xobjlist = xobjlist[:1]
x = xobjlist[0].BBox[2]
else:
x = 0
y = 0
for xobj in xobjlist:
canvas.saveState()
canvas.translate(x, y)
canvas.doForm(makerl(canvas, xobj))
canvas.restoreState()
x += xobj.BBox[2]
canvas.showPage()
canvas.save()
示例3: overlay_hocr_page
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def overlay_hocr_page(self, dpi, hocr_filename, img_filename):
hocr_dir, hocr_basename = os.path.split(hocr_filename)
img_dir, img_basename = os.path.split(img_filename)
logging.debug("hocr_filename:%s, hocr_dir:%s, hocr_basename:%s" % (hocr_filename, hocr_dir, hocr_basename))
assert(img_dir == hocr_dir)
#basename = hocr_basename.split('.')[0]
basename = os.path.splitext(hocr_basename)[0]
pdf_filename = os.path.join("text_%s_ocr.pdf" % (basename))
# Switch to the hocr directory to make this easier
cwd = os.getcwd()
if hocr_dir != "":
os.chdir(hocr_dir)
with open(pdf_filename, "wb") as f:
logging.info("Overlaying hocr and creating text pdf %s" % pdf_filename)
pdf = Canvas(f, pageCompression=1)
pdf.setCreator('pypdfocr')
pdf.setTitle(os.path.basename(hocr_filename))
pdf.setPageCompression(1)
width, height, dpi_jpg = self._get_img_dims(img_basename)
pdf.setPageSize((width,height))
logging.info("Page width=%f, height=%f" % (width, height))
pg_num = 1
logging.info("Adding text to page %s" % pdf_filename)
self.add_text_layer(pdf,hocr_basename,pg_num,height,dpi)
pdf.showPage()
pdf.save()
os.chdir(cwd)
return os.path.join(hocr_dir, pdf_filename)
示例4: drawToFile
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1):
"""Makes a one-page PDF with just the drawing.
If autoSize=1, the PDF will be the same size as
the drawing; if 0, it will place the drawing on
an A4 page with a title above it - possibly overflowing
if too big."""
d = renderScaledDrawing(d)
c = Canvas(fn)
if msg:
c.setFont(rl_config.defaultGraphicsFontName, 36)
c.drawString(80, 750, msg)
c.setTitle(msg)
if autoSize:
c.setPageSize((d.width, d.height))
draw(d, c, 0, 0, showBoundary=showBoundary)
else:
#show with a title
c.setFont(rl_config.defaultGraphicsFontName, 12)
y = 740
i = 1
y = y - d.height
draw(d, c, 80, y, showBoundary=showBoundary)
c.showPage()
c.save()
if sys.platform=='mac' and not hasattr(fn, "write"):
try:
import macfs, macostools
macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ")
macostools.touched(fn)
except:
pass
示例5: process_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def process_pdf(self, image_data, hocr_data, pdf_filename):
"""Utility function if you'd rather get the PDF data back instead of save it automatically."""
pdf = Canvas(pdf_filename, pageCompression=1)
pdf.setCreator('hocr-tools')
pdf.setPageSize((self.width, self.height))
pdf.drawImage(image_data, 0, 0, width=self.width, height=self.height)
pdf = self.add_text_layer(pdf, hocr_data)
pdf_data = pdf.getpdfdata()
return pdf_data
示例6: overlay_hocr
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def overlay_hocr(self, dpi, hocr_filename):
hocr_dir, hocr_basename = os.path.split(hocr_filename)
logging.debug("hocr_filename:%s, hocr_dir:%s, hocr_basename:%s" % (hocr_filename, hocr_dir, hocr_basename))
basename = hocr_basename.split('.')[0]
pdf_filename = os.path.join("%s_ocr.pdf" % (basename))
# Switch to the hocr directory to make this easier
cwd = os.getcwd()
if hocr_dir != "":
os.chdir(hocr_dir)
with open(pdf_filename, "wb") as f:
logging.info("Overlaying hocr and creating final %s" % pdf_filename)
pdf = Canvas(f, pageCompression=1)
pdf.setCreator('pyocr')
pdf.setTitle(os.path.basename(hocr_filename))
logging.info("Analyzing OCR and applying text to PDF...")
pdf.setPageCompression(1)
logging.info("Searching for %s" % ("%s*.jpg" % basename))
for jpg_file in glob.glob("%s*.jpg" % basename):
jpg = Image.open(jpg_file)
w,h = jpg.size
dpi_jpg = jpg.info['dpi']
width = w*72.0/dpi_jpg[0]
height = h*72.0/dpi_jpg[1]
del jpg
pdf.setPageSize((width,height))
logging.info("Adding page image %s" % jpg_file)
logging.info("Page width=%f, height=%f" % (width, height))
pdf.drawImage(jpg_file,0,0, width=width, height=height)
# Get the page number
pg_num = int(jpg_file.split(basename)[1].split('.')[0])
logging.info("Adding text to page %d" % pg_num)
self.add_text_layer(pdf, hocr_basename,pg_num,height,dpi)
pdf.showPage()
os.remove(jpg_file)
pdf.save()
logging.info("Created OCR'ed pdf as %s" % (pdf_filename))
# Now we have to fix up stuff on windows because of reportlab
# adding \r\r\n on each line (instead of \r\n)
f = open(pdf_filename, "rb")
s = str(f.read())
f.close()
#s = s.replace('\r\r\n', '\r\n')
#s = re.sub("\r\r\n", "\r\n", s)
#f = open(pdf_filename, "wb")
#f.write(s)
#f.close()
os.chdir(cwd)
return os.path.join(hocr_dir,pdf_filename)
示例7: render_card_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def render_card_pdf(card, filename):
# set up styles
regular = ParagraphStyle('default')
regular.fontName = 'Helvetica'
regular.fontSize = 9
regular.leading = 11
small = ParagraphStyle('default')
small.fontName = 'Helvetica'
small.fontSize = 7
small.leading = 9
large = ParagraphStyle('default')
large.fontName = 'Helvetica'
large.fontSize = 11
large.leading = 13
text = []
# generate content
address_template = Template(address_format)
# return address
text.extend([Paragraph(address_template.render(Context({
'name': card.sender_name,
'address1': card.sender_address1,
'address2': card.sender_address2,
'city': card.sender_city,
'state': card.sender_state,
'zip': card.sender_zip,
})), small), Spacer(10, 10)])
text.append(Paragraph(strip_tags(card.message).replace('\n', '<br />'), regular))
text.extend([Spacer(10, 10), HR(0.5), Spacer(10, 10)])
text.append(Paragraph('The Sunlight Foundation is a non-partisan non-profit that uses cutting-edge technology and ideas to make government transparent and accountable. Visit SunlightFoundation.com to learn more.', small))
canv = Canvas(filename)
canv.setPageSize((6.25 * inch, 4.5 * inch))
f = Frame(0.375 * inch, 0.75 * inch, 3.125 * inch, 3.375 * inch, showBoundary=0)
f.addFromList(text, canv)
address = Frame(3.75 * inch, 1 * inch, 2 * inch, 1.5 * inch, showBoundary=0)
address.addFromList([Paragraph(address_template.render(Context({
'name': card.recipient_name,
'address1': card.recipient_address1,
'address2': card.recipient_address2,
'city': card.recipient_city,
'state': card.recipient_state,
'zip': card.recipient_zip,
})), large)], canv)
canv.save()
示例8: _save_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def _save_pdf(self):
"""
Output the current document to a PDF file using ReportLab.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
document_model = self.application.get_document_model()
# TODO: seperate saving code into its own thread?
# Setup output pdf
pdf = PdfCanvas(save_model.filename)
pdf.setTitle(save_model.title)
pdf.setAuthor(save_model.author)
pdf.setKeywords(save_model.keywords)
# Generate pages
page_iter = document_model.get_iter_first()
while page_iter:
current_page = document_model.get_value(page_iter, 0)
# Write transformed image
temp_file_path = ''.join([tempfile.mktemp(), '.bmp'])
current_page.pil_image.save(temp_file_path)
assert os.path.exists(temp_file_path), \
'Temporary bitmap file was not created by PIL.'
size = constants.PAGESIZES_INCHES[current_page.page_size]
pdf_width = size[0] * points_per_inch
pdf_height = size[1] * points_per_inch
# Swizzle width and height if the page has been rotated on its side
if abs(current_page.rotation) % 180 == 90:
pdf_width, pdf_height = pdf_height, pdf_width
pdf.setPageSize((pdf_width, pdf_height))
pdf.drawImage(
temp_file_path,
0, 0, width=pdf_width, height=pdf_height,
preserveAspectRatio=True)
pdf.showPage()
os.remove(temp_file_path)
page_iter = document_model.iter_next(page_iter)
# Save complete PDF
pdf.save()
assert os.path.exists(save_model.filename), \
'Final PDF file was not created by ReportLab.'
document_model.clear()
示例9: pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def pdf(files, outfile, useportrait=True):
print("Creating PDF...")
pdf = Canvas(outfile)
pagesize = portrait(A4) if useportrait else landscape(A4)
for i in files:
print("Creating PDF page for %s..." % i)
pdf.setPageSize(pagesize)
pdf.drawImage(i, 0, 0, *pagesize)
pdf.showPage()
print("Done!")
print("Saving PDF...")
pdf.save()
print("Done!")
示例10: go
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def go(inpfn, firstpage, lastpage):
firstpage, lastpage = int(firstpage), int(lastpage)
outfn = 'subset_%s_to_%s.%s' % (firstpage, lastpage, os.path.basename(inpfn))
pages = PdfReader(inpfn).pages
pages = [pagexobj(x) for x in pages[firstpage-1:lastpage]]
canvas = Canvas(outfn)
for page in pages:
canvas.setPageSize(tuple(page.BBox[2:]))
canvas.doForm(makerl(canvas, page))
canvas.showPage()
canvas.save()
示例11: create_prod_labels
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def create_prod_labels(self):
"""
These values should be measured from the printed page.
In all the following calculations, the bottom left corner of
the page is considered to be at the origin of the x-y plane.
All the coordinates should be provided w.r.t. the this origin.
"""
# page size
page_H = 297*mm # A4
page_W = 210*mm # A4
# coordinates of lower left corner of single label w.r.t. origin
box_X = 16.5*mm
box_Y = 9.6*mm
# distance between rows and columns of labels
box_X_shift = 46.2*mm
box_Y_shift = 36.0*mm
pdfmetrics.registerFont(TTFont('Arial', 'ARIALN.TTF'))
c = Canvas(self.outFile)
c.setLineWidth(0.1)
# horizontal lines
for i in range(7):
c.line(42*mm + i*box_Y_shift, 10*mm,
42*mm + i*box_Y_shift, page_W-10*mm)
# vertical lines
for i in range(3):
c.line(2*mm, 58*mm + i*box_X_shift,
page_H-2*mm, 58*mm + i*box_X_shift)
for i in range(4):
dx = box_X + i*box_X_shift
for j in range(8):
dy = box_Y + j*box_Y_shift
self.draw_single_label(dy, dx, c)
c.setPageRotation(90)
c.setPageSize((page_W, page_H))
c.save()
self.message.setText(
"Creating " + self.outFile.replace(self.cdir, "Documents/"))
示例12: run
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def run(self):
try:
filename = self.filename + '.pdf'
if os.path.exists(filename):
raise Exception('File already exists')
canvas = Canvas(filename, pageCompression=1)
canvas.setCreator('Scanvark')
canvas.setTitle('Scanned document')
i = 0
count = len(self.pages)
for i, page in enumerate(self.pages):
self._progress_callback(self, i, count)
w, h = [a * 72 / page.resolution for a in page.size]
canvas.setPageSize((w, h))
reader = ImageReader(page.open_jpeg())
canvas.drawImage(reader, 0, 0, width=w, height=h)
canvas.showPage()
self._progress_callback(self, i, count)
canvas.save()
except Exception, e:
self._error_callback(self, str(e))
示例13: encryptPdfInMemory
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def encryptPdfInMemory(inputPDF,
userPassword, ownerPassword=None,
canPrint=1, canModify=1, canCopy=1, canAnnotate=1,
strength=40):
"""accepts a PDF file 'as a byte array in memory'; return encrypted one.
This is a high level convenience and does not touch the hard disk in any way.
If you are encrypting the same file over and over again, it's better to use
pageCatcher and cache the results."""
try:
from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory
except ImportError:
raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported.
See https://www.reportlab.com/downloads''')
(bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1)
names = list(bboxInfo.keys())
firstPageSize = bboxInfo['PageForms0'][2:]
#now make a new PDF document
buf = getBytesIO()
canv = Canvas(buf, pagesize=firstPageSize)
# set a standard ID while debugging
if CLOBBERID:
canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]"
encryptCanvas(canv,
userPassword, ownerPassword,
canPrint, canModify, canCopy, canAnnotate,
strength=strength)
formNames = restoreFormsInMemory(pickledForms, canv)
for formName in formNames:
canv.setPageSize(bboxInfo[formName][2:])
canv.doForm(formName)
canv.showPage()
canv.save()
return buf.getvalue()
示例14: drawmaze
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def drawmaze(file, w = 8.5 * 72, h = 11.0 * 72, m = 36,
cell = 24, tube = 0.7, wall = 0.3, curve = 1, cross = 1,
count = 1):
cellw, cellh = [int((x - 2 * m) / cell) for x in (w, h)]
mx, my = (w - cellw * cell) / 2.0, (h - cellh * cell) / 2.0
if cellw <= 0 or cellh <= 0: raise RuntimeError('Bad maze dimensions')
c = Canvas(file)
c.setTitle('Maze')
c.setSubject('%s by %s %s crossings' %
(cellw, cellh, ('without', 'with')[cross]))
c.setAuthor("Dave's Maze Maker")
c.setPageSize((w, h))
for n in xrange(count):
maze = [0] * cellw * cellh
fillmaze(maze, cellw, cellh, cross)
maze[0] |= 4
maze[cellw * cellh - 1] |= 1
for x in xrange(cellw):
for y in xrange(cellh):
drawcell(c, maze[x + cellw * y],
x * cell + mx, y * cell + my, cell, tube, wall, curve)
c.showPage()
c.save()
示例15: compile_PDF
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageSize [as 别名]
def compile_PDF(request, book, PDF_file, size=None):
print "The selected size pre is:"
print size
if size is None:
size = request.REQUEST.get('size',None)
limit = request.REQUEST.get('limit',None)
if limit:
limit = int(limit)
print "The selected size post is:"
print size
canvas = Canvas(PDF_file, pagesize=letter)
canvas.setAuthor(book.creator)
canvas.setTitle(book.title)
djatokaArgs = {'svc.scale':'612,792'}
imageArgs = {'x': 0, 'y': 0, 'height': letter[1], 'width': letter[0],
'preserveAspectRatio': False, 'anchor': 'c'}
try:
page = book.pages.get(internal=False,title='front',jp2__isnull=False)
set_image_params(page.jp2, djatokaArgs, imageArgs, size)
canvas.drawImage(get_djatoka_url(page.jp2, **djatokaArgs), **imageArgs)
canvas.showPage()
except Page.DoesNotExist:
pass
pages = book.pages.filter(internal=True).order_by('sequence')
if limit and len(pages) > limit:
pages = pages[:limit]
start = None
length = 1
count = 0
for page in pages:
if page.jp2:
if start is not None:
add_blank_page_range(canvas, book, start, length)
start = None
'''
print "In pdf.py, here are the djatokaArgs:"
for x in djatokaArgs.items():
print x
print "In pdf.py, here are the imageArgs:"
for x in imageArgs.items():
print x
'''
count += 1
print count
'''print page.jp2
print get_djatoka_url(page.jp2, **djatokaArgs)
metadata = get_djatoka_metadata(page.jp2)
height = int(metadata['height'])
width = int(metadata['width'])'''
set_image_params(page.jp2, djatokaArgs, imageArgs, size)
#height_prime = int(djatokaArgs['svc.scale'].split(',')[1])
print "width:height prime is:"
print imageArgs['width']
print imageArgs['height']
#imageArgs['width'] = int((width * height_prime) / height)
#imageArgs['height'] = height_prime
canvas.setPageSize((imageArgs['width'], imageArgs['height']))
canvas.drawImage(get_djatoka_url(page.jp2, **djatokaArgs),
**imageArgs)
for annotation in book.annotations.filter(offset=page.sequence):
canvas.bookmarkPage(str(annotation.pk))
canvas.showPage()
else:
if start is None:
start = page.sequence
length = 1
else:
length += 1
if start is not None:
add_blank_page_range(canvas, book, start, length)
if limit:
for annotation in book.annotations.filter(offset__gt=limit):
canvas.bookmarkPage(str(annotation.pk))
for external in ('back', 'top', 'bottom', 'side', 'spine', ):
try:
page = book.pages.get(internal=False,
#.........这里部分代码省略.........