本文整理汇总了Python中reportlab.pdfgen.canvas.Canvas.setPageCompression方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.setPageCompression方法的具体用法?Python Canvas.setPageCompression怎么用?Python Canvas.setPageCompression使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reportlab.pdfgen.canvas.Canvas
的用法示例。
在下文中一共展示了Canvas.setPageCompression方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testVisible
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def testVisible(self):
"Makes a document with extra text - should export and distill"
c = Canvas(outputfile('test_pdfbase_postscript_visible.pdf'))
c.setPageCompression(0)
c.setFont('Helvetica-Bold', 18)
c.drawString(100,700, 'Hello World. This is page 1 of a 2 page document.')
c.showPage()
c.setFont('Helvetica-Bold', 16)
c.drawString(100,700, 'Page 2. This has some postscript drawing code.')
c.drawString(100,680, 'If you print it using a PS device and Acrobat 4/5,')
c.drawString(100,660, 'or export to Postscript, you should see the word')
c.drawString(100,640, '"Hello PostScript" below. In ordinary Acrobat Reader')
c.drawString(100,620, 'we expect to see nothing.')
c.addPostScriptCommand('/Helvetica findfont 48 scalefont setfont 100 400 moveto (Hello PostScript) show')
c.drawString(100,500, 'This document also inserts two postscript')
c.drawString(100,480, ' comments at beginning and endof the stream;')
c.drawString(100,460, 'search files for "%PS_BEFORE" and "%PS_AFTER".')
c.addPostScriptCommand('%PS_BEFORE', position=0)
c.addPostScriptCommand('%PS_AFTER', position=2)
c.save()
示例2: overlay_hocr_page
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [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)
示例3: overlay_hocr
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [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)
示例4: start_pdf
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [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
示例5: testTray
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def testTray(self):
"Makes a document with tray command - only works on printers supporting it"
c = Canvas(outputfile("test_pdfbase_postscript_tray.pdf"))
c.setPageCompression(0)
c.setFont("Helvetica-Bold", 18)
c.drawString(100, 700, "Hello World. This is page 1 of a 2 page document.")
c.drawString(100, 680, 'This also has a tray command ("5 setpapertray").')
c.addPostScriptCommand("5 setpapertray")
c.showPage()
c.setFont("Helvetica-Bold", 16)
c.drawString(100, 700, "Page 2. This should come from a different tray.")
c.drawString(100, 680, "Also, if you print it using a PS device and Acrobat 4/5,")
c.drawString(100, 660, "or export to Postscript, you should see the word")
c.drawString(100, 640, '"Hello PostScript" below. In ordinary Acrobat Reader')
c.drawString(100, 620, "we expect to see nothing.")
c.addPostScriptCommand("/Helvetica findfont 48 scalefont setfont 100 400 moveto (Hello PostScript) show")
c.save()
示例6: makeDocument
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def makeDocument(filename, pageCallBack=None):
#the extra arg is a hack added later, so other
#tests can get hold of the canvas just before it is
#saved
global titlelist, closeit
titlelist = []
closeit = 0
c = Canvas(filename)
c.setPageCompression(0)
c.setPageCallBack(pageCallBack)
framePageForm(c) # define the frame form
framePage(c, 'PDFgen graphics API test script')
makesubsection(c, "PDFgen", 10 * inch)
story = []
#add some flowables
story.append(box(Paragraph("Champions", styleT)))
story.append(Paragraph("Philosophizing", styleH))
story.append(Paragraph("""
This is a paragraph in <i>Normal</i> style. We do understand exactly why
the system hates me. I really really hate the autocorrect. I really do
not mind the tab-complete function, but the rest of this is shit.""",
styleN))
data = [[query("cid"), query("total_price"), query("gross_margin"), '03',
'04'],
['10', '11', '12', '13', '14'],
['20', '21', '22', '23', '24'],
['30', '31', '32', '33', '34']]
t = Table(data)
t.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))
story.append(t)
f = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0)
f.addFromList(story, c)
c.showPage()
# END OF PAGE 1
framePage(c, 'Line Drawing Styles')
st = []
st.append(Spacer(0, 0.5 * inch))
g = Drawing(3, 4)
f2 = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0)
#St.append(g.add(star(c, title="Title", aka="comments", xcenter=2 * inch,
# ycenter=3 * inch, nvertices=5)))
chart = VerticalBarChart()
# Set the starting point to be (0, 0). Changing this value changes
# the position that the chart is rendered at within it's 'Drawing'
# space, which we create below.
chart.x = 0
chart.y = 0
# This determines the width, in centimeters (you could use 'inch'
# as well) of the chart on the paper, as well as the height.
chart_width = 5 * inch
chart_height = 4 * inch
chart.height = chart_height
chart.width = chart_width
# The vertical ticks will be labeled from 0 with a value every
# 15 units, spaced so that the maximum value is 60.
chart.valueAxis.valueMin = 0
chart.valueAxis.valueMax = 60
chart.valueAxis.valueStep = 15
# Put the labels at the bottom with an interval of 8 units,
# -2 units below the axis, rotated 30 degrees from horizontal
chart.categoryAxis.labels.dx = 8
chart.categoryAxis.labels.dy = -2
chart.categoryAxis.labels.angle = 30
# The text box's NE corner (top right) is located at the above
# coordinate
chart.categoryAxis.labels.boxAnchor = 'ne'
# Our various horizontal axis labels
catNames = ['Jan-06', 'Feb-06', 'Mar-06', 'Apr-06', 'May-06',
'Jun-06', 'Jul-06', 'Aug-06']
chart.categoryAxis.categoryNames = catNames
# Some random data to populate the chart with.
chart.data = [(8, 5, 20, 22, 37, 28, 30, 47)]
# Since the 'Chart' class itself isn't a 'Flowable', we need to
# create a 'Drawing' flowable to contain it. We want the basic
# area to be the same size as the chart itself, so we will
# initialize it with the chart's size.
g = Drawing(chart_width, chart_height)
g.add(chart)
# Add the Chart containing Drawing to our elements list
st.append(box(g))
g.add(star(c, title="Right", aka="comments", xcenter=7 * inch,
ycenter=7 * inch, nvertices=5))
g.add(star(c, title="Left", aka="comments", xcenter=3 * inch,
ycenter=7 * inch, nvertices=6))
st.append(Spacer(1, 1 * inch))
st.append(box(Paragraph("""
Well, its now hard to argue that this is working pretty well. Possibly
make some nice output charts, and import an image.""", styleH)))
f2.addFromList(st, c)
c.showPage()
c.save()
return c
示例7: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def test0(self):
"""Make documents with embedded fonts.
Just vam Rossum has kindly donated a font which we may use
for testing purposes. You need to contact him at [email protected]
if you want to use it for real."""
#LettError fonts should always be there. The others are voluntary.
ok = 1
c = Canvas(outputfile('test_pdfbase_fontembed.pdf'))
c.setPageCompression(0)
c.setFont('Helvetica', 12)
c.drawString(100, 700, 'This is Helvetica. The text below should be different fonts...')
if os.path.isfile('GDB_____.AFM') and os.path.isfile('GDB_____.PFB'):
# a normal text font
garaFace = pdfmetrics.EmbeddedType1Face('GDB_____.AFM','GDB_____.PFB')
faceName = 'AGaramond-Bold' # pulled from AFM file
pdfmetrics.registerTypeFace(garaFace)
garaFont = pdfmetrics.Font('MyGaramondBold', faceName, 'WinAnsiEncoding')
pdfmetrics.registerFont(garaFont)
c.setFont('AGaramond-Bold', 12)
c.drawString(100, 650, 'This should be in AGaramond-Bold')
if os.path.isfile('CR______.AFM') and os.path.isfile('CR______.PFB'):
# one with a custom encoding
cartaFace = pdfmetrics.EmbeddedType1Face('CR______.AFM','CR______.PFB')
faceName = 'Carta' # pulled from AFM file
pdfmetrics.registerTypeFace(cartaFace)
cartaFont = pdfmetrics.Font('Carta', 'Carta', 'CartaEncoding')
pdfmetrics.registerFont(cartaFont)
text = 'This should be in Carta, a map symbol font:'
c.setFont('Helvetica', 12)
c.drawString(100, 600, text)
w = c.stringWidth(text, 'Helvetica', 12)
c.setFont('Carta', 12)
c.drawString(100+w, 600, ' Hello World')
# LettError sample - creates on demand, we hope
y = 550
## justFace = pdfmetrics.EmbeddedType1Face('LeERC___.AFM','LeERC___.PFB')
##
## faceName = 'LettErrorRobot-Chrome' # pulled from AFM file
## pdfmetrics.registerTypeFace(justFace)
##
## justFont = pdfmetrics.Font('LettErrorRobot-Chrome', faceName, 'WinAnsiEncoding')
## pdfmetrics.registerFont(justFont)
c.setFont('LettErrorRobot-Chrome', 12)
c.drawString(100, y, 'This should be in LettErrorRobot-Chrome')
def testNamedFont(canv, fontName):
canv.showPage()
makeWidthTestForAllGlyphs(canv, fontName, outlining=0)
testNamedFont(c, 'LettErrorRobot-Chrome')
c.save()
示例8: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def test0(self):
"Make custom encodings of standard fonts"
# make a custom encoded font.
c = Canvas(outputfile('test_pdfbase_encodings.pdf'))
c.setPageCompression(0)
c.setFont('Helvetica', 12)
c.drawString(100, 700, 'The text below should be in a custom encoding in which all vowels become "z"')
# invent a new language where vowels are replaced with letter 'z'
zenc = pdfmetrics.Encoding('EncodingWithoutVowels', 'WinAnsiEncoding')
for ch in 'aeiou':
zenc[ord(ch)] = 'z'
for ch in 'AEIOU':
zenc[ord(ch)] = 'Z'
pdfmetrics.registerEncoding(zenc)
# now we can make a font based on this encoding
# AR hack/workaround: the name of the encoding must be a Python codec!
f = pdfmetrics.Font('FontWithoutVowels', 'Helvetica-Oblique', 'EncodingWithoutVowels')
pdfmetrics.registerFont(f)
c.setFont('FontWithoutVowels', 12)
c.drawString(125, 675, "The magic word is squamish ossifrage")
# now demonstrate adding a Euro to MacRoman, which lacks one
c.setFont('Helvetica', 12)
c.drawString(100, 650, "MacRoman encoding lacks a Euro. We'll make a Mac font with the Euro at #219:")
# WinAnsi Helvetica
pdfmetrics.registerFont(pdfmetrics.Font('Helvetica-WinAnsi', 'Helvetica-Oblique', 'WinAnsiEncoding'))
c.setFont('Helvetica-WinAnsi', 12)
c.drawString(125, 625, 'WinAnsi with Euro: character 128 = "\200"')
pdfmetrics.registerFont(pdfmetrics.Font('MacHelvNoEuro', 'Helvetica-Oblique', 'MacRomanEncoding'))
c.setFont('MacHelvNoEuro', 12)
c.drawString(125, 600, 'Standard MacRoman, no Euro: Character 219 = "\333"') # oct(219)=0333
# now make our hacked encoding
euroMac = pdfmetrics.Encoding('MacWithEuro', 'MacRomanEncoding')
euroMac[219] = 'Euro'
pdfmetrics.registerEncoding(euroMac)
pdfmetrics.registerFont(pdfmetrics.Font('MacHelvWithEuro', 'Helvetica-Oblique', 'MacWithEuro'))
c.setFont('MacHelvWithEuro', 12)
c.drawString(125, 575, 'Hacked MacRoman with Euro: Character 219 = "\333"') # oct(219)=0333
# now test width setting with and without _rl_accel - harder
# make an encoding where 'm' becomes 'i'
c.setFont('Helvetica', 12)
c.drawString(100, 500, "Recode 'm' to 'i' and check we can measure widths. Boxes should surround letters.")
sample = 'Mmmmm. ' * 6 + 'Mmmm'
c.setFont('Helvetica-Oblique',12)
c.drawString(125, 475, sample)
w = c.stringWidth(sample, 'Helvetica-Oblique', 12)
c.rect(125, 475, w, 12)
narrowEnc = pdfmetrics.Encoding('m-to-i')
narrowEnc[ord('m')] = 'i'
narrowEnc[ord('M')] = 'I'
pdfmetrics.registerEncoding(narrowEnc)
pdfmetrics.registerFont(pdfmetrics.Font('narrow', 'Helvetica-Oblique', 'm-to-i'))
c.setFont('narrow', 12)
c.drawString(125, 450, sample)
w = c.stringWidth(sample, 'narrow', 12)
c.rect(125, 450, w, 12)
c.setFont('Helvetica', 12)
c.drawString(100, 400, "Symbol & Dingbats fonts - check we still get valid PDF in StandardEncoding")
c.setFont('Symbol', 12)
c.drawString(100, 375, 'abcdefghijklmn')
c.setFont('ZapfDingbats', 12)
c.drawString(300, 375, 'abcdefghijklmn')
c.save()
示例9: test0
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def test0(self):
"""Make documents with embedded fonts.
Just vam Rossum has kindly donated a font which we may use
for testing purposes. You need to contact him at [email protected]
if you want to use it for real."""
# LettError fonts should always be there. The others are voluntary.
ok = 1
c = Canvas(outputfile("test_pdfbase_fontembed.pdf"))
c.setPageCompression(0)
c.setFont("Helvetica", 12)
c.drawString(100, 700, "This is Helvetica. The text below should be different fonts...")
if os.path.isfile("GDB_____.AFM") and os.path.isfile("GDB_____.PFB"):
# a normal text font
garaFace = pdfmetrics.EmbeddedType1Face("GDB_____.AFM", "GDB_____.PFB")
faceName = "AGaramond-Bold" # pulled from AFM file
pdfmetrics.registerTypeFace(garaFace)
garaFont = pdfmetrics.Font("MyGaramondBold", faceName, "WinAnsiEncoding")
pdfmetrics.registerFont(garaFont)
c.setFont("AGaramond-Bold", 12)
c.drawString(100, 650, "This should be in AGaramond-Bold")
if os.path.isfile("CR______.AFM") and os.path.isfile("CR______.PFB"):
# one with a custom encoding
cartaFace = pdfmetrics.EmbeddedType1Face("CR______.AFM", "CR______.PFB")
faceName = "Carta" # pulled from AFM file
pdfmetrics.registerTypeFace(cartaFace)
cartaFont = pdfmetrics.Font("Carta", "Carta", "CartaEncoding")
pdfmetrics.registerFont(cartaFont)
text = "This should be in Carta, a map symbol font:"
c.setFont("Helvetica", 12)
c.drawString(100, 600, text)
w = c.stringWidth(text, "Helvetica", 12)
c.setFont("Carta", 12)
c.drawString(100 + w, 600, " Hello World")
# LettError sample - creates on demand, we hope
y = 550
## dgmkFace = pdfmetrics.EmbeddedType1Face('DarkGardenMK.afm','DarkGardenMK.PFB')
##
## faceName = 'DarkGardenMK' # pulled from AFM file
## pdfmetrics.registerTypeFace(dgmkFace)
##
## dgmkFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
## pdfmetrics.registerFont(dgmk)
c.setFont("DarkGardenMK", 12)
c.drawString(100, y, "This should be in DarkGardenMK")
def testNamedFont(canv, fontName):
canv.showPage()
makeWidthTestForAllGlyphs(canv, fontName, outlining=0)
testNamedFont(c, "DarkGardenMK")
c.save()
示例10: PDFGenerator
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
class PDFGenerator(object):
canvas = None
colorspace = None
use_spot = True
num_pages = 0
page_count = 0
prgs_msg = _('Saving in process...')
def __init__(self, fileptr, cms, version=PDF_VERSION_DEFAULT):
self.cms = cms
self.canvas = Canvas(fileptr, pdfVersion=version[0])
self.info = UC_PDFInfo(self.canvas._doc)
self.info.pdfxversion = version[1]
self.info.subject = '---'
self.canvas.setPageCompression(1)
#---PDF doc data
def set_creator(self, name): self.info.creator = name
def set_producer(self, name): self.info.producer = name
def set_title(self, title): self.info.title = title
def set_author(self, author): self.info.author = author
def set_subject(self, subj): self.info.subject = subj
def set_keywords(self, keywords): self.info.keywords = keywords
#---Rendering options
def set_compression(self, val=True):
self.canvas.setPageCompression(int(val))
def set_colorspace(self, cs=None):
self.colorspace = cs
def set_spot_usage(self, val=True):
self.use_spot = val
#---Page processing
def set_num_pages(self, num=1):
self.num_pages = num
def set_progress_message(self, msg):
self.prgs_msg = msg
def start_page(self, w, h, left_margin=0.0, top_margin=0.0):
self.canvas.translate(w / 2.0 - left_margin, h / 2.0 - top_margin)
self.canvas.setPageSize((w, h))
position = 0.0
if self.num_pages:
position = float(self.page_count) / float(self.num_pages)
events.emit(events.FILTER_INFO, self.prgs_msg, position)
def end_page(self):
self.canvas.showPage()
self.page_count += 1
position = 1.0
if self.num_pages:
position = float(self.page_count) / float(self.num_pages)
events.emit(events.FILTER_INFO, self.prgs_msg, position)
def save(self):
self.canvas.save()
#--- Rendering
def render(self, objs, toplevel=False):
obj_count = 0
for obj in objs:
if obj.is_pixmap():
self.draw_pixmap(obj)
elif obj.is_primitive():
curve_obj = obj.to_curve()
if curve_obj.is_primitive():
self.draw_curve(curve_obj)
else:
self.render(curve_obj.childs)
elif obj.is_container():
self.draw_container(obj)
else:
self.render(obj.childs)
#---Progress
obj_count += 1
shift = 0.0
page_size = 1.0
if self.num_pages:
shift = float(self.page_count) / float(self.num_pages)
page_size = 1.0 / float(self.num_pages)
position = shift + obj_count / len(objs) * page_size
events.emit(events.FILTER_INFO, self.prgs_msg, position)
def draw_curve(self, curve_obj):
paths = libgeom.apply_trafo_to_paths(curve_obj.paths, curve_obj.trafo)
pdfpath, closed = self.make_pdfpath(paths)
fill_style = curve_obj.style[0]
stroke_style = curve_obj.style[1]
if stroke_style and stroke_style[7]:
self.stroke_pdfpath(pdfpath, stroke_style, curve_obj.stroke_trafo)
if fill_style and fill_style[0] & sk2_const.FILL_CLOSED_ONLY and closed:
self.fill_pdfpath(curve_obj, pdfpath, fill_style, curve_obj.fill_trafo)
elif fill_style and not fill_style[0] & sk2_const.FILL_CLOSED_ONLY:
#.........这里部分代码省略.........
示例11: overlay_hocr
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [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))
# Find all the jpg files, and sort them by page number
jpg_files = []
# Make the jpg search a little bit more robust
for f in os.listdir("."):
if re.match(r"^%s_\d+\.%s$" % (basename, self.gs.img_file_ext), f):
jpg_files.append(f)
#jpg_files = glob.glob("%s*.jpg" % basename)
jpg_files.sort(key=self.natural_keys)
if len(jpg_files) == 0:
logging.warn("No jpg files found to embed in PDF. Please check this!")
# We know the following loop will iterate in page order
# because we sorted the jpg filenames
for i, jpg_file in enumerate(jpg_files):
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 = i+1
# Do a quick assert to make sure our sorted page number matches
# what's embedded in the filename
file_pg_num = int(jpg_file.split(basename+"_")[1].split('.')[0])
if file_pg_num != pg_num:
logging.warn("Page number from file (%d) does not match iteration (%d)... continuing anyway" % (file_pg_num, pg_num))
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)
示例12: overlay_hocr_old
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def overlay_hocr_old(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))
text_pdf_filename = pdf_filename + ".tmp"
# Switch to the hocr directory to make this easier
cwd = os.getcwd()
if hocr_dir != "":
os.chdir(hocr_dir)
with open(text_pdf_filename, "wb") as f:
logging.info("Overlaying hocr and creating text pdf %s" % text_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))
# Find all the jpg files, and sort them by page number
img_files = []
# Make the jpg search a little bit more robust
for f in os.listdir("."):
if re.match(r"^%s_\d+\.%s$" % (basename, self.gs.img_file_ext), f):
img_files.append(f)
img_files.sort(key=self.natural_keys)
if len(img_files) == 0:
logging.warn("No %s files found to embed in PDF. Please check this!" % self.gs.img_file_ext)
# We know the following loop will iterate in page order
# because we sorted the jpg filenames
for i, img_file in enumerate(img_files):
jpg = Image.open(img_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" % img_file)
logging.info("Page width=%f, height=%f" % (width, height))
#pdf.drawImage(img_file,0,0, width=width, height=height)
# Get the page number
pg_num = i+1
# Do a quick assert to make sure our sorted page number matches
# what's embedded in the filename
file_pg_num = int(img_file.split(basename+"_")[1].split('.')[0])
if file_pg_num != pg_num:
logging.warn("Page number from file (%d) does not match iteration (%d)... continuing anyway" % (file_pg_num, pg_num))
logging.info("Adding text to page %d" % pg_num)
self.add_text_layer(pdf, hocr_basename,pg_num,height,dpi)
pdf.showPage()
os.remove(img_file)
pdf.save()
return os.path.join(hocr_dir,pdf_filename)
示例13: Canvas
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
c = Canvas('/Users/ross/Desktop/temp.pdf', pagesize=(200,100))
c.setPageCompression(0)
y = 50
line = 'fooobasd \xb1 \xb2 \xf3'
pdfmetrics.registerFont(TTFont('Arial', '/Library/Fonts/Microsoft/Arial.ttf'))
pdfmetrics.registerFontFamily('Arial', normal='Arial')
c.setFont('Arial', 20)
c.drawString(50, y, line.strip())
c.save()
# ============ EOF =============================================
示例14: makeDocument
# 需要导入模块: from reportlab.pdfgen.canvas import Canvas [as 别名]
# 或者: from reportlab.pdfgen.canvas.Canvas import setPageCompression [as 别名]
def makeDocument(filename, pageCallBack=None):
#the extra arg is a hack added later, so other
#tests can get hold of the canvas just before it is
#saved
global titlelist, closeit
titlelist = []
closeit = 0
c = Canvas(filename)
c.setPageCompression(0)
c.setPageCallBack(pageCallBack)
framePageForm(c) # define the frame form
framePage(c, 'SBS|Charge-Demo Bid')
makesubsection(c, "Philosophizing", 10 * inch)
story = []
#add some flowables
story.append(Paragraph("Philosophizing", styleH))
story.append(Paragraph("""
This is a paragraph in <i>Normal</i> style. We do understand exactly why
the system hates me. I really really hate the autocorrect. I really do
not mind the tab-complete function, but the rest of this is shit.""",
styleN))
# let's move on to the divers table
diver_table = [['Company', 'Gross Margin', 'Total Price']]
# this is the header row
diver_table.append([query("cid"), query("gross_margin"),
query("total_price")])
# these are the other rows
#add_table(diver_table, TABLE_WIDTH)
#add_table(diver_table, TABLE_WIDTH)
data = [[query("cid"), query("total_price"), query("gross_margin"), '03',
'04'],
['10', '11', '12', '13', '14'],
['20', '21', '22', '23', '24'],
['30', '31', '32', '33', '34']]
t = Table(diver_table)
#t.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
# ('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))
table_style = [
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#C0C0C0')),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white,
colors.HexColor('#E0E0E0')])
]
t.setStyle(TableStyle(table_style))
t2 = Table(data)
t2.setStyle(TableStyle(table_style))
story.append(Paragraph("Table of imported data", styleH))
makesubsection(c, "Table", 9 * inch)
story.append(t)
story.append(t2)
t = Table([[u'Corporate Assets', 'Amount'],
['Fixed Assets', '1,234,567.89'],
['Company Vehicle', '1,234.8901'],
['Petty Cash', '42'],
[u'Intellectual Property\u00ae', query("total_price")],
['Overdraft', '(12,345)'],
['Boardroom Flat Screen', '60 inches'],
['Net Position', 'Moon Base']
],
[144, 72])
ts = TableStyle([ # first the top row
('ALIGN', (1, 1), (-1, -1), 'CENTER'),
('LINEABOVE', (0, 0), (-1, 0), 2, colors.purple),
('LINEBELOW', (0, 0), (-1, 0), 1, colors.purple),
('FONT', (0, 0), (-1, 0), 'Times-Bold'),
#bottom row has a line above, and two lines below
('LINEABOVE', (0, -1), (-1, -1), 1, colors.purple),
# last 2 are count, sep
('LINEBELOW', (0, -1), (-1, -1), 0.5, colors.purple,
1, None, None, 4, 1),
('LINEBELOW', (0, -1), (-1, -1), 1, colors.red),
('FONT', (0, -1), (-1, -1), 'Times-Bold'),
#numbers column
('ALIGN', (1, 1), (-1, -1), 'DECIMAL'),
('RIGHTPADDING', (1, 1), (-1, -1), 36),
('TEXTCOLOR', (1, 4), (1, 4), colors.red),
#red cell
]
)
t.setStyle(ts)
story.append(t)
story.append(Spacer(36, 36))
a = Image("SBSchargeLogo.jpg")
a.drawHeight = 0.5 * inch
a.drawWidth = 2 * inch
#c.translate(0.8 * inch, 9.6 * inch)
#c.rotate(90)
story.append(a)
#c.setPageRotation(0)
#instance = HandAnnotation()
#instance.wrap()
#.........这里部分代码省略.........