本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setSubject方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setSubject方法的具体用法?Python Canvas.setSubject怎么用?Python Canvas.setSubject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.setSubject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_pages
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def generate_pages(card_sizes,cards, filename="placecards.pdf", custom_font = None):
pagesize = pagesizes.portrait( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch))
pdf = Canvas(filename, pagesize=pagesize,pdfVersion=(1,4))
pdf.setAuthor('placecardboardgenerate.py')
pdf.setSubject('wedding placecards')
pdf.setTitle('Placecards for Wedding Reception')
pdf.setKeywords(('wedding', 'placecards'))
if custom_font is not None:
pdf.setFont(custom_font,14)#FIXME don't hardcode font size
adjusted_card_sizes = (card_sizes[0] * pagesizes.inch, card_sizes[1] * pagesizes.inch)
card_printer = CardPrinter(pagesize,adjusted_card_sizes)
(cardsPerRow,rowsPerPage) = (card_printer.cards_per_row, card_printer.cards_per_column)
(page_width, page_height) = pagesize
groupedCards = group_cards(cards, cardsPerRow, rowsPerPage)
for (page_index,pageOfCards) in enumerate(groupedCards):
if custom_font is not None:
pdf.setFont(custom_font,14)#FIXME don't hardcode font size
for (row_index,rowOfCards) in enumerate(pageOfCards):
for (column_index,card) in enumerate(rowOfCards):
card_printer.print_on_front_page(pdf,card,row_index, column_index)
pdf.drawCentredString(page_width/2.0,20,"front of page %i" % (page_index + 1))
pdf.showPage()
if custom_font is not None:
pdf.setFont(custom_font,14)#FIXME don't hardcode font size
for (row_index,rowOfCards) in enumerate(pageOfCards):
for (column_index,card) in enumerate(rowOfCards):
card_printer.print_on_back_page(pdf,card,row_index, column_index)
pdf.drawCentredString(page_width/2.0,20,"back of page %i" % (page_index + 1))
pdf.showPage()
pdf.save()
示例2: test
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def test(self):
c = Canvas(outputfile('test_hello.pdf'))
#Author with Japanese text
c.setAuthor('\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88')
#Subject with Arabic magic
c.setSubject(u'\u0643\u0644\u0627\u0645 \u0639\u0631\u0628\u064a')
c.setFont('Helvetica-Bold', 36)
c.drawString(100,700, 'Hello World')
c.save()
示例3: render
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def render(self, path):
canvas = Canvas(path, pagesize=A4, pageCompression=1)
canvas.setTitle(self.title)
canvas.setSubject(self.subject)
canvas.setAuthor(self.author)
canvas.setCreator(self.creator)
canvas._doc.info.producer = self.creator
self.canvas = canvas
self.render_pages()
self.canvas.save()
示例4: test
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def test(self):
c = Canvas(outputfile("test_hello.pdf"))
# Author with Japanese text
c.setAuthor(
"\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88"
)
# Subject with Arabic magic
c.setSubject(u"\u0643\u0644\u0627\u0645 \u0639\u0631\u0628\u064a")
c.setFont("Helvetica-Bold", 36)
c.drawString(100, 700, "Hello World")
c.save()
示例5: generateCollage
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def generateCollage(self,session):
file_name = 'collage.pdf' #TODO image should be created in a temp directory
pdf = Canvas(file_name,pagesize=self._pagesize)
# add metadata
pdf.setAuthor('photobooth') #TODO add app version to author
pdf.setSubject('wedding photos')
pdf.setTitle('pictures for session %s' % session.get_name())
pdf.setKeywords(('wedding', 'pictures','photobooth'))
# add pictures
#TODO add padding
(total_width, total_height) = self._pagesize
(image_width, image_height) = (total_width, total_height / len(session.get_photos()))
for (i,photo) in enumerate(session.get_photos()):
pdf.drawInlineImage(photo,0,i * image_height, image_width, image_height, preserveAspectRatio=True, anchor='n')
pdf.showPage()
pdf.save()
return file_name
示例6: start_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def start_pdf(filename, author=None, keywords=None, subject=None, title=None):
""" Starts a new pdf document
@param filename the name of the PDF generated in output.
@param author the author name.
@param subject the subject of the document.
@param title the title of the document.
"""
canvas = Canvas(filename)
if author:
canvas.setAuthor(author)
if keywords:
canvas.setKeywords(keywords)
if title:
canvas.setTitle(title)
if subject:
canvas.setSubject(subject)
canvas.setPageCompression(1)
return canvas
示例7: generate_key
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def generate_key(verticalCardsCount,horizontalCardsCount,cards, filename="key.pdf", page_margins = 4 * (0.5 * pagesizes.inch, )):
(page_margin_top, page_margin_left, page_margin_bottom, page_margin_right) = page_margins
padding = 0.0625 * pagesizes.inch
spaces = (verticalCardsCount * horizontalCardsCount) * [None,]
for card in cards:
spaces[card.position] = card
pagesize = pagesizes.landscape( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch))
pdf = Canvas(filename, pagesize=pagesize, pdfVersion=(1,4))
pdf.setAuthor('placecardboardgenerate.py')
pdf.setSubject('wedding placecards key')
pdf.setTitle('Key for Placecards for Wedding Reception')
pdf.setKeywords(('wedding', 'placecards'))
(page_width, page_height) = pagesize
pdf.drawCentredString(page_width/2.0,20,"key of place cards")
thumbnail_width = ((page_width - page_margin_left - page_margin_right) - (padding * (horizontalCardsCount - 1))) / horizontalCardsCount
thumbnail_height = ((page_height - page_margin_top - page_margin_bottom) - (padding * (verticalCardsCount - 1))) / verticalCardsCount
x_margin = page_margin_left
x_offset = thumbnail_width + padding
y_margin = page_margin_top
y_offset = thumbnail_height + padding
for row_index in range(verticalCardsCount):
for column_index in range(horizontalCardsCount):
position = (row_index * horizontalCardsCount) + column_index
card = spaces[position]
(card_x, card_y) = \
(x_margin + (x_offset * column_index),\
(page_height - thumbnail_height) - (y_margin + (y_offset * row_index)))
if card is not None:
pdf.drawImage(card.image, card_x, card_y, width = thumbnail_width, height = thumbnail_height)
pdf.drawCentredString(card_x + thumbnail_width/2.0,card_y + thumbnail_height/2.0, str(card.position))
pdf.showPage()
pdf.save()
示例8: drawmaze
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [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()
示例9: PDFCreator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
class PDFCreator(object):
appName = "txt2pdf (version 1.0)"
def __init__(self, args, margins):
pageWidth, pageHeight = reportlab.lib.pagesizes.__dict__[args.media]
if args.landscape:
pageWidth, pageHeight = reportlab.lib.pagesizes.landscape(
(pageWidth, pageHeight))
self.author = args.author
self.title = args.title
self.keywords = args.keywords
self.subject = args.subject
self.canvas = Canvas(args.output, pagesize=(pageWidth, pageHeight))
self.canvas.setCreator(self.appName)
if len(args.author) > 0:
self.canvas.setAuthor(args.author)
if len(args.title) > 0:
self.canvas.setTitle(args.title)
if len(args.subject) > 0:
self.canvas.setSubject(args.subject)
if len(args.keywords) > 0:
self.canvas.setKeywords(args.keywords)
self.fontSize = args.font_size
if args.font not in ('Courier'):
self.font = 'myFont'
pdfmetrics.registerFont(TTFont('myFont', args.font))
else:
self.font = args.font
self.kerning = args.kerning
self.margins = margins
self.leading = (args.extra_vertical_space + 1.2) * self.fontSize
self.linesPerPage = int(
(self.leading + pageHeight
- margins.top - margins.bottom - self.fontSize) / self.leading)
self.lppLen = len(str(self.linesPerPage))
fontWidth = self.canvas.stringWidth(
".", fontName=self.font, fontSize=self.fontSize)
self.lineNumbering = args.line_numbers
if self.lineNumbering:
margins.adjustLeft(fontWidth * (self.lppLen + 2))
contentWidth = pageWidth - margins.left - margins.right
self.charsPerLine = int(
(contentWidth + self.kerning) / (fontWidth + self.kerning))
self.top = pageHeight - margins.top - self.fontSize
self.filename = args.filename
self.verbose = not args.quiet
self.breakOnBlanks = args.break_on_blanks
self.encoding = args.encoding
self.pageNumbering = args.page_numbers
if self.pageNumbering:
self.pageNumberPlacement = \
(pageWidth / 2, margins.bottom / 2)
def _process(self, data):
flen = os.fstat(data.fileno()).st_size
lineno = 0
read = 0
for line in data:
lineno += 1
if sys.version_info.major == 2:
read += len(line)
yield flen == \
read, lineno, line.decode(self.encoding).rstrip('\r\n')
else:
read += len(line.encode(self.encoding))
yield flen == read, lineno, line.rstrip('\r\n')
def _readDocument(self):
with open(self.filename, 'r') as data:
for done, lineno, line in self._process(data):
if len(line) > self.charsPerLine:
self._scribble(
"Warning: wrapping line %d in %s" %
(lineno + 1, self.filename))
while len(line) > self.charsPerLine:
yield done, line[:self.charsPerLine]
line = line[self.charsPerLine:]
yield done, line
def _newpage(self):
textobject = self.canvas.beginText()
textobject.setFont(self.font, self.fontSize, leading=self.leading)
textobject.setTextOrigin(self.margins.left, self.top)
textobject.setCharSpace(self.kerning)
if self.pageNumbering:
self.canvas.drawString(
self.pageNumberPlacement[0],
self.pageNumberPlacement[1],
str(self.canvas.getPageNumber()))
return textobject
def _scribble(self, text):
if self.verbose:
sys.stderr.write(text + os.linesep)
def generate(self):
self._scribble(
"Writing '%s' with %d characters per "
"line and %d lines per page..." %
(self.filename, self.charsPerLine, self.linesPerPage)
#.........这里部分代码省略.........
示例10: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
#.........这里部分代码省略.........
"""Combine multiple PDF files at once when is working with multiple canvas"""
if not self.multiple_canvas or not pyPdf or not self.temp_files:
return
readers = []
def append_pdf(input, output):
for page_num in range(input.numPages):
output.addPage(input.getPage(page_num))
output = pyPdf.PdfFileWriter()
for f_name in self.temp_files:
reader = pyPdf.PdfFileReader(file(f_name, 'rb'))
readers.append(reader)
append_pdf(reader, output)
if isinstance(self.filename, basestring):
fp = file(self.filename, 'wb')
else:
fp = self.filename
output.write(fp)
# Closes and clear objects
fp.close()
for r in readers: del r
del output
def start_pdf(self):
"""Initializes the PDF document with some properties and methods"""
# Set PDF properties
self.canvas.setTitle(self.report.title)
self.canvas.setAuthor(self.report.author)
self.canvas.setSubject(self.report.subject)
self.canvas.setKeywords(self.report.keywords)
def render_page_header(self):
"""Generate the report page header band if it exists"""
if not self.report.band_page_header:
return
# Doesn't generate this band if it is not visible
if not self.report.band_page_header.visible:
return
# Call method that print the band area and its widgets
self.render_band(
self.report.band_page_header,
top_position=self.calculate_size(self.report.page_size[1]) - self.calculate_size(self.report.margin_top),
update_top=False,
)
def render_page_footer(self):
"""Generate the report page footer band if it exists"""
if not self.report.band_page_footer:
return
# Doesn't generate this band if it is not visible
if not self.report.band_page_footer.visible:
return
# Call method that print the band area and its widgets
self.render_band(
self.report.band_page_footer,
top_position=self.calculate_size(self.report.margin_bottom) +\
self.calculate_size(self.report.band_page_footer.height),
示例11: render
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def render(grid, options):
draw_with_curves = options['draw_with_curves']
filename = options['filename']
use_A4 = options['use_A4']
width = options['width']
height = options['height']
def s_shape_00(p):
p.moveTo(a, 0)
if draw_with_curves:
p.arcTo(-a, -a, a, a, 0, 90)
else:
p.lineTo(a, a)
p.lineTo(0, a)
def s_shape_01(p):
p.moveTo(0, b)
if draw_with_curves:
p.arcTo(-a, b, a, s + a, 270, 90)
else:
p.lineTo(a, b)
p.lineTo(a, s)
def s_shape_10(p):
p.moveTo(s, a)
if draw_with_curves:
p.arcTo(b, -a, s + a, a, 90, 90)
else:
p.lineTo(b, a)
p.lineTo(b, 0)
def s_shape_11(p):
p.moveTo(s, b)
if draw_with_curves:
p.arcTo(b, b, s + a, s + a, 270, -90)
else:
p.lineTo(b, b)
p.lineTo(b, s)
buffer = StringIO()
if filename:
c = Canvas(filename)
else:
c = Canvas(buffer)
c.setTitle('Maze')
c.setSubject("")
c.setAuthor("Dale O'Brien")
if use_A4:
page_width = 8.3 * 72
page_height = 11.7 * 72
else:
page_width = 8.5 * 72
page_height = 11.0 * 72
c.setPageSize((page_width, page_height))
# 0=butt,1=draw_with_curves,2=square
c.setLineCap(1)
left_margin = 15
top_margin = 15
# cells must be square, it's the math!, I'm not doing it again.
# so scale the width if the height will go over the page
org_width = width
ratio = (page_height - 2 * top_margin) / (page_width - 2 * left_margin)
if (float(height) / width > ratio):
width = ceil(height / ratio)
s = (page_width - 2 * left_margin) / width
# center the maze, looks better for mazes that don't fit the page nicely
left_margin -= (org_width - width) * s / 2.0
top_margin -= (s * height - (page_height - 2.0 * top_margin)) / 2.0
g = s * 0.2
stroke = s / 7.0
c.setLineWidth(stroke)
k = 0.5
n = -(g / k) + 0.5 * (s - sqrt((g *
(4.0 * g - 3.0 * g * k + 2 * k * s)) / k))
r = g / k
q = n + r
v = (g * (-1 + k)) / k
theta = asin((2.0 * g - 2.0 * g * k + k * s) /
(2.0 * g - g * k + k * s)) * 180 / pi
delta = theta - 90
for j, row in enumerate(grid):
# upper/lower rows
#.........这里部分代码省略.........
示例12: PDFInvoice
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
class PDFInvoice(object):
def __init__(self, recipient, invoicedate, duedate, invoicenum=None, imagedir=None, currency='€', preview=False, receipt=False, bankinfo=True):
self.pdfdata = StringIO.StringIO()
self.canvas = Canvas(self.pdfdata)
self.recipient = recipient
self.invoicenum = invoicenum
self.invoicedate = invoicedate
self.duedate = duedate
self.imagedir = imagedir or '.'
self.currency = currency or '€'
self.preview = preview
self.receipt = receipt
self.bankinfo = bankinfo
self.rows = []
if self.receipt:
# Never include bank info on receipts
self.bankinfo = False
self.canvas.setTitle("PostgreSQL Europe Invoice #%s" % self.invoicenum)
self.canvas.setSubject("PostgreSQL Europe Invoice #%s" % self.invoicenum)
self.canvas.setAuthor("PostgreSQL Europe")
self.canvas._doc.info.producer = "PostgreSQL Europe Invoicing System"
def addrow(self, title, cost, count=1):
self.rows.append((title, cost, count,))
def trimstring(self, s, maxlen, fontname, fontsize):
while len(s) > 5:
if self.canvas.stringWidth(s, fontname, fontsize) <= maxlen:
return s
s = s[:len(s)-2]
return s
def _pageheader(self):
if self.preview:
t = self.canvas.beginText()
t.setTextOrigin(6*cm, 4*cm)
t.setFont("Times-Italic", 70)
t.setFillColorRGB(0.9,0.9,0.9)
t.textLines("PREVIEW PREVIEW")
self.canvas.rotate(45)
self.canvas.drawText(t)
self.canvas.rotate(-45)
im = Image("%s/PostgreSQL_logo.1color_blue.300x300.png" % self.imagedir, width=3*cm, height=3*cm)
im.drawOn(self.canvas, 2*cm, 25*cm)
t = self.canvas.beginText()
t.setFillColorRGB(0,0,0,0)
t.setFont("Times-Roman", 10)
t.setTextOrigin(6*cm, 27.5*cm)
t.textLines("""PostgreSQL Europe
Carpeaux Diem
13, rue du Square Carpeaux
75018 PARIS
France
""")
self.canvas.drawText(t)
t = self.canvas.beginText()
t.setTextOrigin(2*cm, 23*cm)
t.setFont("Times-Roman", 10)
t.textLine("")
t.textLines("""
Your contact: Guillaume Lelarge
Function: PostgreSQL Europe Treasurer
E-mail: [email protected]
""")
self.canvas.drawText(t)
t = self.canvas.beginText()
t.setTextOrigin(11*cm, 23*cm)
t.setFont("Times-Italic", 11)
t.textLine("To:")
t.setFont("Times-Roman", 11)
t.textLines(self.recipient)
self.canvas.drawText(t)
p = self.canvas.beginPath()
p.moveTo(2*cm, 18.9*cm)
p.lineTo(19*cm, 18.9*cm)
self.canvas.drawPath(p)
def save(self):
# We can fit 15 rows on one page. We might want to do something
# cute to avoid a single row on it's own page in the future, but
# for now, just split it evenly.
for pagenum in range(0, (len(self.rows)-1)/15+1):
self._pageheader()
islastpage = (pagenum == (len(self.rows)-1)/15)
if len(self.rows) > 15:
suffix = " (page %s/%s)" % (pagenum+1, len(self.rows)/15+1)
else:
suffix = ''
# Center between 2 and 19 is 10.5
if self.invoicenum:
#.........这里部分代码省略.........
示例13: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
class PDFGenerator(ReportGenerator):
"""This is a generator to output a PDF using ReportLab library with
preference by its Platypus API"""
filename = None
canvas = None
return_canvas = False
def __init__(self, report, filename=None, canvas=None, return_canvas=False):
super(PDFGenerator, self).__init__(report)
self.filename = filename
self.canvas = canvas
self.return_canvas = return_canvas
def execute(self):
"""Generates a PDF file using ReportLab pdfgen package."""
super(PDFGenerator, self).execute()
# Initializes the temporary PDF canvas (just to be used as reference)
if not self.canvas:
self.canvas = Canvas(self.filename, pagesize=self.report.page_size)
# Render pages
self.render_bands()
# Initializes the definitive PDF canvas
self.start_pdf()
self.generate_pages()
# Returns the canvas
if self.return_canvas:
return self.canvas
# Saves the canvas - only if it didn't return it
self.canvas.save()
def start_pdf(self, filename=None): # XXX
"""Initializes the PDF document with some properties and methods"""
# Sets the PDF canvas
#self.canvas = Canvas(filename=filename, pagesize=self.report.page_size) # XXX
# Set PDF properties
self.canvas.setTitle(self.report.title)
self.canvas.setAuthor(self.report.author)
self.canvas.setSubject(self.report.subject)
self.canvas.setKeywords(self.report.keywords)
def render_page_header(self):
"""Generate the report page header band if it exists"""
if not self.report.band_page_header:
return
# Doesn't generate this band if it is not visible
if not self.report.band_page_header.visible:
return
# Call method that print the band area and its widgets
self.render_band(
self.report.band_page_header,
top_position=self.calculate_size(self.report.page_size[1]) - self.calculate_size(self.report.margin_top),
update_top=False,
)
def render_page_footer(self):
"""Generate the report page footer band if it exists"""
if not self.report.band_page_footer:
return
# Doesn't generate this band if it is not visible
if not self.report.band_page_footer.visible:
return
# Call method that print the band area and its widgets
self.render_band(
self.report.band_page_footer,
top_position=self.calculate_size(self.report.margin_bottom) +\
self.calculate_size(self.report.band_page_footer.height),
update_top=False,
)
def calculate_top(self, *args):
ret = args[0]
for i in args[1:]:
ret -= i
return ret
def get_top_pos(self):
"""Since the coordinates are bottom-left on PDF, we have to use this to get
the current top position, considering also the top margin."""
ret = self.calculate_size(self.report.page_size[1]) - self.calculate_size(self.report.margin_top) - self._current_top_position
if self.report.band_page_header:
ret -= self.calculate_size(self.report.band_page_header.height)
return ret
def make_paragraph(self, text, style=None): # XXX
#.........这里部分代码省略.........
示例14: Canvas
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
# Other parameters, should not need any modification
FONT = "Helvetica"
FONTBOLD = "Helvetica-Bold"
FONTSIZE = 35
FONTSIZE2 = 30
SMALLFONTSIZE = 8
width, height = A4
centerh = height/2 # horizontal center, used to center text strings on the page
# create the PDF --- DO NOT EDIT AFTER THIS LINE !!! ---
pdf = Canvas("lipflyer.pdf")
pdf.setPageSize([height, width]) # only trick I found to have a A4 in LANDSCAPE mode
# Busy with "header"
pdf.setTitle(TITLE)
pdf.setSubject(SUBJECT)
# pdf.setKeywords(KEYWORDS) # not working?
pdf.setAuthor(AUTHOR)
# Putting the 3 images
pdf.drawInlineImage("images/tchantchux.jpg", 40, 240, width=158, height=283)
pdf.drawImage("images/logo-lilit.png", 40, 40, width=None, height=None, mask=[255, 255, 255, 255, 226, 226])
pdf.drawInlineImage("images/penguin.png", 600, 250, width=217, height=260)
# Putting the central text
pdf.setFont(FONT, FONTSIZE) # xème journée d'installation de
pdf.setFillColorRGB(255, 0, 0)
chaine = NUMBER + " journée d'installation de"
x = pdf.stringWidth(chaine, FONTBOLD, FONTSIZE)
pdf.drawString(centerh - x/2, 530, chaine)
xx = pdf.stringWidth(NUMBER, FONTBOLD, FONTSIZE) # superscript in the previous string
pdf.setFont(FONT, FONTSIZE2)
示例15: create_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setSubject [as 别名]
def create_pdf(hocr, filename, font="Courier", author=None, keywords=None, subject=None, title=None, image_path=None, draft=False):
""" transform hOCR information into a searchable PDF.
@param hocr the hocr structure as coming from extract_hocr.
@param filename the name of the PDF generated in output.
@param font the default font (e.g. Courier, Times-Roman).
@param author the author name.
@param subject the subject of the document.
@param title the title of the document.
@param image_path the default path where images are stored. If not specified
relative image paths will be resolved to the current directory.
@param draft whether to enable debug information in the output.
"""
def adjust_image_size(width, height):
return max(width / A4[0], height / A4[1])
canvas = Canvas(filename)
if author:
canvas.setAuthor(author)
if keywords:
canvas.setKeywords(keywords)
if title:
canvas.setTitle(title)
if subject:
canvas.setSubject(subject)
for bbox, image, lines in hocr:
if not image.startswith('/') and image_path:
image = os.path.abspath(os.path.join(image_path, image))
img_width, img_height = bbox[2:]
ratio = adjust_image_size(img_width, img_height)
if draft:
canvas.drawImage(image, 0, A4[1] - img_height / ratio , img_width / ratio, img_height / ratio)
canvas.setFont(font, 12)
for bbox, line in lines:
if draft:
canvas.setFillColor(red)
x0, y0, x1, y1 = bbox
width = (x1 - x0) / ratio
height = ((y1 - y0) / ratio)
x0 = x0 / ratio
#for ch in 'gjpqy,(){}[];[email protected]':
#if ch in line:
#y0 = A4[1] - (y0 / ratio) - height
#break
#else:
y0 = A4[1] - (y0 / ratio) - height / 1.3
#canvas.setFontSize(height * 1.5)
canvas.setFontSize(height)
text_width = canvas.stringWidth(line)
if text_width:
## If text_width != 0
text_object = canvas.beginText(x0, y0)
text_object.setHorizScale(1.0 * width / text_width * 100)
text_object.textOut(line)
canvas.drawText(text_object)
else:
info('%s, %s has width 0' % (bbox, line))
if draft:
canvas.setStrokeColor(green)
canvas.rect(x0, y0, width, height)
if draft:
canvas.circle(0, 0, 10, fill=1)
canvas.circle(0, A4[1], 10, fill=1)
canvas.circle(A4[0], 0, 10, fill=1)
canvas.circle(A4[0], A4[1], 10, fill=1)
canvas.setFillColor(green)
canvas.setStrokeColor(green)
canvas.circle(0, A4[1] - img_height / ratio, 5, fill=1)
canvas.circle(img_width / ratio, img_height /ratio, 5, fill=1)
else:
canvas.drawImage(image, 0, A4[1] - img_height / ratio , img_width / ratio, img_height / ratio)
canvas.save()