本文整理匯總了Python中cairo.PDFSurface方法的典型用法代碼示例。如果您正苦於以下問題:Python cairo.PDFSurface方法的具體用法?Python cairo.PDFSurface怎麽用?Python cairo.PDFSurface使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cairo
的用法示例。
在下文中一共展示了cairo.PDFSurface方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: barCoord
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def barCoord(n):
'''
returns ((x-left-top, y-left-top),
(x-left-buttom, y-right-buttom),
(x-right-top, y-right-top),
(x-right-buttom, y-right-buttom))
coordinate of a bar area
'''
return ((100 + (n % 6) * 380, 430 + (n // 6) * 331), # left x-axis 100pt for margin blank
(100 + (n % 6) * 380, 430 + (n // 6) * 331 + 252), # top y-axis 430pt for title
(100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331), # 252 is 1.5em for chord 1em * 3 for melody 56pt per em
(100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331 + 252))
# ctx = cairo.Context(cairo.PDFSurface("haha.pdf", 2480.0, 3508.0))
# ctx.set_font_size(30)
# ctx.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
# cairo.FONT_WEIGHT_NORMAL)
示例2: main
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def main():
ps = cairo.PDFSurface("pdffile.pdf", 504, 648)
cr = cairo.Context(ps)
cr.set_source_rgb(0, 0, 0)
cr.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(40)
cr.move_to(10, 50)
cr.show_text(chr(119046) +'1 2 3 4 5' + chr(119047) )
cr.set_line_width(11)
cr.move_to(100, 100)
cr.line_to(20, 300)
cr.show_page()
示例3: create_cairo_surface
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def create_cairo_surface(self, fobj, width_in_points, height_in_points):
return cairo.PDFSurface(fobj, width_in_points, height_in_points)
#------------------------------------------------------------------------
#
# PsDoc class
#
#------------------------------------------------------------------------
示例4: start
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def start(self, fn, w, h,):
self.fn = fn
if OUTPUT_FMT == 'PNG' or not fn:
self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
int(w + 1), int(h + 1))
elif OUTPUT_FMT == 'SVG':
self.surface = cairo.SVGSurface(self.fn, int(w + 1), int(h + 1))
elif OUTPUT_FMT == 'PDF':
self.surface = cairo.PDFSurface(self.fn, int(w + 1), int(h + 1))
elif OUTPUT_FMT == 'PS':
self.surface = cairo.PSSurface(self.fn, int(w + 1), int(h + 1))
else:
raise AttributeError("no such output format: '%s'" % OUTPUT_FMT)
return self.surface
示例5: draw
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def draw(self):
'''
main function of this class
'''
self.srf = cairo.PDFSurface(self.outf, self.width, self.height)
self.ctx = cairo.Context(self.srf)
self.draw_table()
self.colnames()
self.rownames()
self.draw_circles()
self.srf.finish()
self.srf.flush()
示例6: init_pdf
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def init_pdf(self):
import cairo
self.surface = cairo.PDFSurface(self.fname, self.width, self.height)
self.bbox = igraph.drawing.utils.BoundingBox(self.margin, self.margin,
self.width - self.margin,
self.height - self.margin)
示例7: __save
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def __save(self, target_path, pages, progress_cb=dummy_export_progress_cb):
# XXX(Jflesch): This is a problem. It will fails if someone tries
# to export to a non-local directory. We should use
# cairo_pdf_surface_create_for_stream()
target_path = self.doc.fs.unsafe(target_path)
pdf_surface = cairo.PDFSurface(target_path,
self.__page_format[0],
self.__page_format[1])
pdf_context = cairo.Context(pdf_surface)
pages = [self.doc.pages[x] for x in range(pages[0], pages[1])]
for page_idx, page in enumerate(pages):
progress_cb(page_idx, len(pages))
img = page.img
if (img.size[0] < img.size[1]):
(x, y) = (min(self.__page_format[0], self.__page_format[1]),
max(self.__page_format[0], self.__page_format[1]))
else:
(x, y) = (max(self.__page_format[0], self.__page_format[1]),
min(self.__page_format[0], self.__page_format[1]))
pdf_surface.set_size(x, y)
logger.info("Adding text to PDF page {} ...".format(page))
self.__paint_txt(pdf_surface, (x, y), pdf_context, page)
logger.info("Adding image to PDF page {} ...".format(page))
self.__paint_img(pdf_surface, (x, y), pdf_context, page)
pdf_context.show_page()
logger.info("Page {} ready".format(page))
progress_cb(len(pages), len(pages))
return self.doc.fs.safe(target_path)
示例8: gen_calendar
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def gen_calendar(start_date, title, filename):
if len(title) > MAX_TITLE_SIZE:
raise ValueError("Title can't be longer than %d characters"
% MAX_TITLE_SIZE)
# Fill background with white
surface = cairo.PDFSurface (filename, DOC_WIDTH, DOC_HEIGHT)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.rectangle(0, 0, DOC_WIDTH, DOC_HEIGHT)
ctx.fill()
ctx.select_font_face(FONT, cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_BOLD)
ctx.set_source_rgb(0, 0, 0)
ctx.set_font_size(BIGFONT_SIZE)
w, h = text_size(ctx, title)
ctx.move_to((DOC_WIDTH / 2) - (w / 2), (Y_MARGIN / 2) - (h / 2))
ctx.show_text(title)
# Back up to the last monday
date = start_date
while date.weekday() != 0:
date -= datetime.timedelta(days=1)
# Draw 52x90 grid of squares
draw_grid(ctx, date)
ctx.show_page()
示例9: render
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def render(self, canvas, transparent=False):
x0,y0,x1,y1 = canvas.bbox('all')
self.markers = canvas.markers
W = int((x1 - x0 + 2*self.padding) * self.scale)
H = int((y1 - y0 + 2*self.padding) * self.scale)
ext = os.path.splitext(self.fname)[1].lower()
if ext == '.svg':
surf = cairo.SVGSurface(self.fname, W, H)
elif ext == '.pdf':
surf = cairo.PDFSurface(self.fname, W, H)
elif ext in ('.ps', '.eps'):
surf = cairo.PSSurface(self.fname, W, H)
if ext == '.eps':
surf.set_eps(True)
else: # Bitmap
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H)
self.ctx = cairo.Context(surf)
ctx = self.ctx
if not transparent:
# Fill background
ctx.rectangle(0,0, W,H)
ctx.set_source_rgba(1.0,1.0,1.0)
ctx.fill()
ctx.scale(self.scale, self.scale)
ctx.translate(-x0 + self.padding, -y0 + self.padding)
if self.draw_bbox:
last = len(canvas.shapes)
for s in canvas.shapes[:last]:
bbox = s.bbox
r = canvas.create_rectangle(*bbox, line_color=(255,0,0, 127), fill=(0,255,0,90))
for s in canvas.shapes:
self.draw_shape(s)
if ext in ('.svg', '.pdf', '.ps', '.eps'):
surf.show_page()
else:
surf.write_to_png(self.fname)
示例10: _take_screenshot
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def _take_screenshot(self, dummy_button):
#print "Cheese!"
file_name = self._get_export_file_name()
if file_name is None:
return
# figure out the correct bounding box for what is visible on screen
x1 = self._scrolled_window.get_hadjustment().value
y1 = self._scrolled_window.get_vadjustment().value
x2 = x1 + self._scrolled_window.get_hadjustment().page_size
y2 = y1 + self._scrolled_window.get_vadjustment().page_size
bounds = goocanvas.Bounds()
bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
dest_width = bounds.x2 - bounds.x1
dest_height = bounds.y2 - bounds.y1
#print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2
dummy, extension = os.path.splitext(file_name)
extension = extension.lower()
if extension == '.eps':
surface = cairo.PSSurface(file_name, dest_width, dest_height)
elif extension == '.pdf':
surface = cairo.PDFSurface(file_name, dest_width, dest_height)
elif extension == '.svg':
surface = cairo.SVGSurface(file_name, dest_width, dest_height)
else:
dialog = gtk.MessageDialog(parent = self.canvas.get_toplevel(),
flags = gtk.DIALOG_DESTROY_WITH_PARENT,
type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK,
message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
% (extension,))
dialog.run()
dialog.destroy()
return
# draw the canvas to a printing context
cr = cairo.Context(surface)
cr.translate(-bounds.x1, -bounds.y1)
self.canvas.render(cr, bounds, self.zoom.value)
cr.show_page()
surface.finish()
示例11: _save
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def _save(self, fo, fmt, **kwargs):
# save PDF/PS/SVG
orientation = kwargs.get('orientation', 'portrait')
dpi = 72
self.figure.dpi = dpi
w_in, h_in = self.figure.get_size_inches()
width_in_points, height_in_points = w_in * dpi, h_in * dpi
if orientation == 'landscape':
width_in_points, height_in_points = (
height_in_points, width_in_points)
if fmt == 'ps':
if not hasattr(cairo, 'PSSurface'):
raise RuntimeError('cairo has not been compiled with PS '
'support enabled')
surface = cairo.PSSurface(fo, width_in_points, height_in_points)
elif fmt == 'pdf':
if not hasattr(cairo, 'PDFSurface'):
raise RuntimeError('cairo has not been compiled with PDF '
'support enabled')
surface = cairo.PDFSurface(fo, width_in_points, height_in_points)
elif fmt in ('svg', 'svgz'):
if not hasattr(cairo, 'SVGSurface'):
raise RuntimeError('cairo has not been compiled with SVG '
'support enabled')
if fmt == 'svgz':
if isinstance(fo, str):
fo = gzip.GzipFile(fo, 'wb')
else:
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
surface = cairo.SVGSurface(fo, width_in_points, height_in_points)
else:
raise ValueError("Unknown format: {!r}".format(fmt))
# surface.set_dpi() can be used
renderer = RendererCairo(self.figure.dpi)
renderer.set_width_height(width_in_points, height_in_points)
renderer.set_ctx_from_surface(surface)
ctx = renderer.gc.ctx
if orientation == 'landscape':
ctx.rotate(np.pi / 2)
ctx.translate(0, -height_in_points)
# Perhaps add an '%%Orientation: Landscape' comment?
self.figure.draw(renderer)
ctx.show_page()
surface.finish()
if fmt == 'svgz':
fo.close()
示例12: _save
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def _save(self, fo, fmt, **kwargs):
# save PDF/PS/SVG
orientation = kwargs.get('orientation', 'portrait')
dpi = 72
self.figure.dpi = dpi
w_in, h_in = self.figure.get_size_inches()
width_in_points, height_in_points = w_in * dpi, h_in * dpi
if orientation == 'landscape':
width_in_points, height_in_points = (
height_in_points, width_in_points)
if fmt == 'ps':
if not hasattr(cairo, 'PSSurface'):
raise RuntimeError('cairo has not been compiled with PS '
'support enabled')
surface = cairo.PSSurface(fo, width_in_points, height_in_points)
elif fmt == 'pdf':
if not hasattr(cairo, 'PDFSurface'):
raise RuntimeError('cairo has not been compiled with PDF '
'support enabled')
surface = cairo.PDFSurface(fo, width_in_points, height_in_points)
elif fmt in ('svg', 'svgz'):
if not hasattr(cairo, 'SVGSurface'):
raise RuntimeError('cairo has not been compiled with SVG '
'support enabled')
if fmt == 'svgz':
if isinstance(fo, str):
fo = gzip.GzipFile(fo, 'wb')
else:
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
surface = cairo.SVGSurface(fo, width_in_points, height_in_points)
else:
warnings.warn("unknown format: %s" % fmt, stacklevel=2)
return
# surface.set_dpi() can be used
renderer = RendererCairo(self.figure.dpi)
renderer.set_width_height(width_in_points, height_in_points)
renderer.set_ctx_from_surface(surface)
ctx = renderer.gc.ctx
if orientation == 'landscape':
ctx.rotate(np.pi / 2)
ctx.translate(0, -height_in_points)
# Perhaps add an '%%Orientation: Landscape' comment?
self.figure.draw(renderer)
ctx.show_page()
surface.finish()
if fmt == 'svgz':
fo.close()
示例13: main
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def main():
args = get_args()
bom = BOM(args.xmlpath, include=args.include, exclude=args.exclude)
with open(args.xmlpath[:-3] + "kicad_pcb") as f:
pcb = PCB(sexp.parse(f.read()))
mm_to_pt = 2.835
ps = cairo.PDFSurface(args.pdfpath,
args.page_width*mm_to_pt,
args.page_height*mm_to_pt)
cr = cairo.Context(ps)
# Scale user units to millimetres
cr.scale(mm_to_pt, mm_to_pt)
labels = sheet_positions(cr,
args.label_width, args.label_height,
args.labels_x, args.labels_y,
args.margin_top, args.margin_left,
args.spacing_x, args.spacing_y)
suppliers = [name.strip() for name in args.suppliers.split(",")]
for line in bom.lines:
if line.supplier not in suppliers:
continue
if not line.footprint and not args.include_parts_without_footprint:
continue
label = next(labels)
line.render(cr,
(label[0]+1, label[1]),
args.label_width-2, 14)
sides = pcb.get_mod_sides(line.refs)
if "F.Cu" in sides and "B.Cu" in sides:
# if both sides present, split area and draw both
pcb.render(cr, (label[0]+1, label[1]+14),
(args.label_width-4)/2.0, args.label_height-14,
["F.Fab"], ["F.Cu", "*.Cu", "F.SilkS"], sides["F.Cu"])
pcb.render(cr, (label[0]+3+(args.label_width-3)/2.0, label[1]+14),
(args.label_width-4)/2.0, args.label_height-14,
["B.Fab"], ["B.Cu", "*.Cu", "B.SilkS"], sides["B.Cu"],
args.flip_vert)
elif "F.Cu" in sides:
pcb.render(cr, (label[0]+1, label[1]+14),
args.label_width-2, args.label_height-14,
["F.Fab"], ["F.Cu", "*.Cu", "F.SilkS"], sides["F.Cu"])
elif "B.Cu" in sides:
pcb.render(cr, (label[0]+1, label[1]+14),
args.label_width-2, args.label_height-14,
["B.Fab"], ["B.Cu", "*.Cu", "B.SilkS"], sides["B.Cu"],
args.flip_vert)
cr.show_page()
示例14: remove_all
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def remove_all(self):
""" Opening the PDF with poppler, then doing a render
on a cairo pdfsurface for each pages.
http://cairographics.org/documentation/pycairo/2/
The use of an intermediate tempfile is necessary because
python-cairo segfaults on unicode.
See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=699457
"""
document = Poppler.Document.new_from_file(self.uri, self.password)
try:
output = tempfile.mkstemp()[1]
# Size doesn't matter (pun intended),
# since the surface will be resized before
# being rendered
surface = cairo.PDFSurface(output, 10, 10)
context = cairo.Context(surface) # context draws on the surface
logging.debug('PDF rendering of %s' % self.filename)
for pagenum in range(document.get_n_pages()):
page = document.get_page(pagenum)
page_width, page_height = page.get_size()
surface.set_size(page_width, page_height)
context.save()
if self.pdf_quality: # this may reduce the produced PDF size
page.render(context)
else:
page.render_for_printing(context)
context.restore()
context.show_page() # draw context on surface
surface.finish()
shutil.move(output, self.output)
except:
logging.error('Something went wrong when cleaning %s.' % self.filename)
return False
try:
import pdfrw # For now, poppler cannot write meta, so we must use pdfrw
logging.debug('Removing %s\'s superficial metadata' % self.filename)
trailer = pdfrw.PdfReader(self.output)
trailer.Info.Producer = None
trailer.Info.Creator = None
writer = pdfrw.PdfWriter()
writer.trailer = trailer
writer.write(self.output)
self.do_backup()
except:
logging.error('Unable to remove all metadata from %s, please install pdfrw' % self.output)
return False
return True
示例15: _save
# 需要導入模塊: import cairo [as 別名]
# 或者: from cairo import PDFSurface [as 別名]
def _save(self, fo, fmt, **kwargs):
# save PDF/PS/SVG
orientation = kwargs.get('orientation', 'portrait')
dpi = 72
self.figure.dpi = dpi
w_in, h_in = self.figure.get_size_inches()
width_in_points, height_in_points = w_in * dpi, h_in * dpi
if orientation == 'landscape':
width_in_points, height_in_points = (
height_in_points, width_in_points)
if fmt == 'ps':
if not hasattr(cairo, 'PSSurface'):
raise RuntimeError('cairo has not been compiled with PS '
'support enabled')
surface = cairo.PSSurface(fo, width_in_points, height_in_points)
elif fmt == 'pdf':
if not hasattr(cairo, 'PDFSurface'):
raise RuntimeError('cairo has not been compiled with PDF '
'support enabled')
surface = cairo.PDFSurface(fo, width_in_points, height_in_points)
elif fmt in ('svg', 'svgz'):
if not hasattr(cairo, 'SVGSurface'):
raise RuntimeError('cairo has not been compiled with SVG '
'support enabled')
if fmt == 'svgz':
if isinstance(fo, six.string_types):
fo = gzip.GzipFile(fo, 'wb')
else:
fo = gzip.GzipFile(None, 'wb', fileobj=fo)
surface = cairo.SVGSurface(fo, width_in_points, height_in_points)
else:
warnings.warn("unknown format: %s" % fmt)
return
# surface.set_dpi() can be used
renderer = RendererCairo(self.figure.dpi)
renderer.set_width_height(width_in_points, height_in_points)
renderer.set_ctx_from_surface(surface)
ctx = renderer.gc.ctx
if orientation == 'landscape':
ctx.rotate(np.pi / 2)
ctx.translate(0, -height_in_points)
# Perhaps add an '%%Orientation: Landscape' comment?
self.figure.draw(renderer)
ctx.show_page()
surface.finish()
if fmt == 'svgz':
fo.close()