示例#1
0
def save(document, file, filename, options={}):
    if options.get('box'):
        bbox = document.BoundingRect(visible=0, printable=1)
    else:
        bbox = document.PageRect()
    bbox = tuple(bbox)
    llx, lly, urx, ury = bbox
    resolution = config.preferences.pdf_export_resolution
    compat = config.preferences.pdf_compatibility_level
    width = (urx - llx) * resolution / 72
    height = (ury - lly) * resolution / 72
    offx = -llx
    offy = -lly

    if options.get('images'):
        imfilter = "-dAutoFilterColorImages=false -sColorImageFilter=FlateEncode"
    else:
        imfilter = ''

    filename = util.sh_quote(filename)
    file = os.popen(gs_command % locals(), 'w')
    ps = PostScriptDevice(file,
                          document=document,
                          as_eps=1,
                          embed_fonts=1,
                          bounding_box=bbox,
                          Title=os.path.basename(filename),
                          For=util.get_real_username(),
                          CreationDate=util.current_date())
    document.Draw(ps)
    ps.Close()
    file.close()
示例#2
0
def main():
    import Sketch
    Sketch.init_lib()

    draw_printable = 1
    draw_visible = 0
    embed_fonts = 0
    eps_for = util.get_real_username()
    eps_date = util.current_date()
    eps_title = None
    rotate = 0

    import getopt
    opts, args = getopt.getopt(sys.argv[1:], 'hprved:f:t:', [
        'help', 'noprintable', 'rotate', 'visible', 'embed-fonts', 'for=',
        'date=', 'title='
    ])

    for optchar, value in opts:
        if optchar == '-h' or optchar == '--help':
            print_usage()
            return -1
        elif optchar == '-p' or optchar == '--noprintable':
            draw_printable = 0
        elif optchar == '-v' or optchar == '--visible':
            draw_visible = 1
        elif optchar == '-d' or optchar == '--date':
            eps_date = value
        elif optchar == '-f' or optchar == '--for':
            eps_for = value
        elif optchar == '-r' or optchar == '--rotate':
            rotate = 1
        elif optchar == '-t' or optchar == '--title':
            eps_title = value
        elif optchar == '-e' or optchar == '--embed-fonts':
            embed_fonts = 1

    if len(args) not in (1, 2):
        print_usage()
        return -1

    filename = args[0]
    if len(args) > 1:
        psfile = args[1]
    else:
        psfile = sys.stdout

    if eps_title is None:
        eps_title = os.path.basename(filename)

    sk2ps(filename,
          psfile,
          printable=draw_printable,
          visible=draw_visible,
          For=eps_for,
          CreationDate=eps_date,
          Title=eps_title,
          rotate=rotate,
          embed_fonts=embed_fonts)
示例#3
0
def save(document, file, filename, options = {}):
    bbox = tuple(document.BoundingRect(visible = 0, printable = 1))
    ps = PostScriptDevice(file, document = document, as_eps = 1,
                          bounding_box = bbox,
                          Title = os.path.basename(filename),
                          For = util.get_real_username(),
                          CreationDate = util.current_date())
    document.Draw(ps)
    ps.Close()
示例#4
0
    def do_print(self):
        app = self.main_window.application
        bbox = self.document.BoundingRect(visible=0, printable=1)
        if bbox is None:
            app.MessageBox(title=_("Save As PostScript"),
                           message=_("The document doesn't have "
                                     "any printable layers."),
                           icon="warning")
            return
        try:
            filename = ''
            file = None
            if self.print_dest.get() == 'file':
                # print to file
                filename = self.print_filename.get()
                # use filename as file just in case the user is trying
                # to save into an EPS that is referenced by the
                # document. The psdevice knows how to handle such cases.
                file = filename
                title = os.path.basename(filename)
            else:
                file = os.popen(self.print_command.get(), 'w')
                title = 'sketch'
            try:
                dev = Sketch.PostScriptDevice
                ps_dev = dev(file,
                             as_eps=1,
                             bounding_box=tuple(bbox),
                             rotate=self.var_rotate.get(),
                             embed_fonts=self.var_embfnt.get(),
                             For=util.get_real_username(),
                             CreationDate=util.current_date(),
                             Title=title,
                             document=self.document)
                self.document.Draw(ps_dev)
                ps_dev.Close()
                if filename:
                    self.document.meta.ps_filename = filename
                    self.document.meta.ps_directory = os.path.split(
                        filename)[0]
            finally:
                # close the file. Check for the close attribute first
                # because file can be either a string or a file object.
                if hasattr(file, "close"):
                    file.close()

        except IOError, value:
            app.MessageBox(title = _("Save As PostScript"),
                           message = _("Cannot save %(filename)s:\n"
                                       "%(message)s") \
                           % {'filename':`os.path.split(filename)[1]`,
                              'message':value[1]},
                           icon = 'warning')
            return
示例#5
0
文件: sk2ps.py 项目: shumik/skencil-c
def main():
    import Sketch
    Sketch.init_lib()

    draw_printable = 1
    draw_visible = 0
    embed_fonts = 0
    eps_for = util.get_real_username()
    eps_date = util.current_date()
    eps_title = None
    rotate = 0

    import getopt
    opts, args = getopt.getopt(sys.argv[1:], 'hprved:f:t:',
                               ['help', 'noprintable', 'rotate', 'visible',
                                'embed-fonts', 'for=', 'date=', 'title='])

    for optchar, value in opts:
        if optchar == '-h' or optchar == '--help':
            print_usage()
            return -1
        elif optchar == '-p' or optchar == '--noprintable':
            draw_printable = 0
        elif optchar == '-v' or optchar == '--visible':
            draw_visible = 1
        elif optchar == '-d' or optchar == '--date':
            eps_date = value
        elif optchar == '-f' or optchar == '--for':
            eps_for = value
        elif optchar == '-r' or optchar == '--rotate':
            rotate = 1
        elif optchar == '-t' or optchar == '--title':
            eps_title = value
        elif optchar == '-e' or optchar == '--embed-fonts':
            embed_fonts = 1

    if len(args) not in (1, 2):
        print_usage()
        return -1

    filename = args[0]
    if len(args) > 1:
        psfile = args[1]
    else:
        psfile = sys.stdout

    if eps_title is None:
        eps_title = os.path.basename(filename)

    sk2ps(filename, psfile, printable= draw_printable, visible = draw_visible,
          For = eps_for, CreationDate = eps_date, Title = eps_title,
          rotate = rotate, embed_fonts = embed_fonts)
示例#6
0
    def do_print(self):
        app = self.main_window.application
        bbox = self.document.BoundingRect(visible = 0, printable = 1)
        if bbox is None:
            app.MessageBox(title = _("Save As PostScript"),
                           message = _("The document doesn't have "
                                       "any printable layers."),
                           icon = "warning")
            return
        try:
            filename = ''
            file = None
            if self.print_dest.get() == 'file':
                # print to file
                filename = self.print_filename.get()
                # use filename as file just in case the user is trying
                # to save into an EPS that is referenced by the
                # document. The psdevice knows how to handle such cases.
                file = filename
                title = os.path.basename(filename)
            else:
                file = os.popen(self.print_command.get(), 'w')
                title = 'sketch'
            try:
                dev = Sketch.PostScriptDevice
                ps_dev = dev(file, as_eps = 1, bounding_box = tuple(bbox),
                             rotate = self.var_rotate.get(),
                             embed_fonts = self.var_embfnt.get(),
                             For = util.get_real_username(),
                             CreationDate = util.current_date(), Title = title,
                             document = self.document)
                self.document.Draw(ps_dev)
                ps_dev.Close()
                if filename:
                    self.document.meta.ps_filename = filename
                    self.document.meta.ps_directory =os.path.split(filename)[0]
            finally:
                # close the file. Check for the close attribute first
                # because file can be either a string or a file object.
                if hasattr(file, "close"):
                    file.close()

        except IOError, value:
            app.MessageBox(title = _("Save As PostScript"),
                           message = _("Cannot save %(filename)s:\n"
                                       "%(message)s") \
                           % {'filename':`os.path.split(filename)[1]`,
                              'message':value[1]},
                           icon = 'warning')
            return
示例#7
0
def save(document, file, filename, options = {}):
    bbox = tuple(document.PageRect())
    llx, lly, urx, ury = bbox
    resolution = config.preferences.pdf_export_resolution
    compat = config.preferences.pdf_compatibility_level
    width = (urx-llx)*resolution/72
    height = (ury-lly)*resolution/72

    filename = util.sh_quote(filename)
    file = os.popen(gs_command % locals(),'w')
    ps = PostScriptDevice(file, document = document, as_eps = 0, embed_fonts = 1,
                          bounding_box = bbox,
                          Title = os.path.basename(filename),
                          For = util.get_real_username(),
                          CreationDate = util.current_date())
    document.Draw(ps)
    ps.Close()
    file.close()
示例#8
0
def main():
	import Sketch
	global doc
	global tbase_style

	Sketch.init_lib()

	draw_printable = 1
	draw_visible = 0
	embed_fonts = 0
	eps_for = util.get_real_username()
	eps_date = util.current_date()
	eps_title = None
	rotate = 0


	#doc = load.load_drawing('')
	# from mainwindow.py: self.SetDocument(Document(create_layer = 1))
	doc = Document(create_layer = 1)

	# get font info first
	Graphics.font.read_font_dirs()

	# indicate start of coord system first
	# coord system:: + goes upward / rightward
	# from RectangleCreator: trafo = Trafo(off.x, 0, 0, off.y, end.x, end.y)
	# actually, there 'end' seems to correspond to start (llc: lower left corner of rectangle) - and 'off' to the length extended in each direction (i.e. width, height - but can be negative) ; so instead of 'end' - calling it 'start'
	start_x = 5
	start_y = 5
	off_x = -10
	off_y = -10
	trec = Rectangle(trafo = Trafo(off_x, 0, 0, off_y, start_x, start_y))
	trec.update_rects()
	doc.Insert(trec)


	# from create_text.py
	textfld = SimpleText(Translation(50, 50), "xyzzy")
	textfld.SetProperties(fill_pattern = SolidPattern(StandardColors.green),
					   font = GetFont('Courier-Bold'),#('Times-Bold'),
					   font_size = 36)

	#copy textfld
	textfld2 = textfld.Duplicate()
	textfld2.SetProperties(fill_pattern = SolidPattern(StandardColors.blue)) # change color only

	# rotate textfld
	angleDeg = 45
	angleRad = pi*(angleDeg/180.0) # ensure float op - could use math.radians instead
	textfld.Transform(Rotation(angleRad)) # Rotation(angle, center)
	textfld.update_rects() # probably a good idea

	# change textfld's text with the current width (that we see)
	# get bounding box of text
	a = textfld.properties
	llx, lly, urx, ury = a.font.TextBoundingBox(textfld.text, a.font_size)
	# calculate width - its of UNTRANSFORMED text
	twidth = urx - llx
	# insert this width as text in textbox now:
	#~ textfld.text = str(twidth)
	#~ textfld.update_rects() # probably a good idea - again

	# get textfield as bezier
	textbez = textfld.AsBezier()
	#~ print textbez # returns Sketch.Graphics.group.Group; subclass of EditableCompound
	# the bounding rectangle - from Compound (type is Rect):
	textbez_bRect = textbez.bounding_rect
	# calc width now
	t2width = textbez_bRect.right - textbez_bRect.left
	# insert this width as text in textbox now:
	textfld.text = str(t2width)
	textfld.update_rects() # probably a good idea - again

	#~ doc.Insert(textfld)

	# create a line
	# using create_spiral.py technique below (see syntax note #(A1))
	tpath = CreatePath()

	# Note - apparently, the first appended point is "moveTo";
	# .. the ubsequent ones being "LineTo"
	tp = Point(textbez_bRect.left,textbez_bRect.bottom)
	tpath.AppendLine(tp) # moveto

	tp = Point(textbez_bRect.left,textbez_bRect.top)
	tpath.AppendLine(tp) # lineto
	tp = Point(textbez_bRect.right,textbez_bRect.top)
	tpath.AppendLine(tp) # lineto
	tp = Point(textbez_bRect.right,textbez_bRect.bottom)
	tpath.AppendLine(tp) # lineto

	tline = PolyBezier((tpath,))
	tline.AddStyle(tbase_style) # of Graphics.properties (also in compound, document) - seems to add a 'layer' if dynamic; else seems to 'replace' ?!

	#~ doc.Insert(tline)

	# group tline and textfld ...
	# footprints.py has Group(foot_prints = [])
	tgrp = Group([textfld, textfld2, tline])
	tgrp.update_rects()
	doc.Insert(tgrp)

	# add a box.. around textfld2
	# use radius1, radius2 !=  0 AND 1 (logarithmic) to get RoundedRectangle (best between 0.0 and 1.0)
	tfbr = textfld2.bounding_rect
	start_x = tfbr.left
	start_y = tfbr.bottom
	off_x = tfbr.right - tfbr.left
	off_y = tfbr.top - tfbr.bottom
	twid = abs(off_x - start_x)
	thei = abs(off_y - start_y)
	radfact = 1.2*twid/thei
	tradius = 0.05 # if we want to specify a single one, then the actual look will depend on the dimesions of the rectangle - so must 'smooth' it with radfact...
	trec = Rectangle(trafo = Trafo(off_x, 0, 0, off_y, start_x, start_y), radius1 = tradius, radius2 = tradius*radfact)
	trec.update_rects()
	doc.Insert(trec)

	# add another box - any where
	start_x = 100.0
	start_y = 100.0
	off_x = 50.0
	off_y = 50.0
	trec2 = Rectangle(trafo = Trafo(off_x, 0, 0, off_y, start_x, start_y))
	trec2.update_rects()
	doc.Insert(trec2)

	# try change props post insert - OK
	trec2.SetProperties(fill_pattern = SolidPattern(StandardColors.yellow), line_width = 2.0, line_pattern = SolidPattern(CreateRGBColor(0.5, 0.5, 0.7)))

	# try move the group as a whole (Translate - syntax: spread.py)
	# say, align the right edge of tline to left edge of trec2 (x direction)
	# NOTE: group does not define own .AsBezier(self);
	# but it has tgrp.bounding_rect (although python doesn't show it in dir(tgrp))
	# also there is Rectangle.bounding_rect
	# NOTE though - it seems bounding_rect is somehow padded, with (at least) 10 units in each direction! (also, bounding rect of line will include the arrow)
	xmove = (trec2.bounding_rect.left+10)-(tline.bounding_rect.right-10)
	#~ print xmove, trec2.bounding_rect.left, tline.bounding_rect.right
	tgrp.Translate(Point(xmove, 0))
	tgrp.update_rects()

	# add temporary line to indicate bounding boxes
	# and effect of padding (may cover the very first trec)
	tmpbr = trec2.bounding_rect
	doc.Insert(
		getQuickLine(
			(0,0),
			(trec2.bounding_rect.left+10, tline.bounding_rect.top-10)
		)
	)

	# end of draw  - generate output file
	filename = ''
	psfile = 'vectorout.ps'
	sk2ps(filename, psfile, printable= draw_printable, visible = draw_visible,
		  For = eps_for, CreationDate = eps_date, Title = eps_title,
		  rotate = rotate, embed_fonts = embed_fonts)
示例#9
0
    align_distance = 6
    align_length = 12
    grow = align_length + align_distance
    llx, lly, urx, ury = doc_bbox
    ps_bbox = (llx - grow, lly - grow, urx + grow, ury + grow)
    for color in colors:
        separator = CreateSeparation(color)
        try:
            # do this in a try-finall to make sure the document colors
            # get restored even if something goes wrong
            doc.WalkHierarchy(separator.change_color)
            filename = basename + '-' + hexcolor(color)  + '.ps'
            ps_dev = PostScriptDevice(filename, as_eps = 1,
                                      bounding_box = ps_bbox,
                                      For = util.get_real_username(),
                                      CreationDate = util.current_date(),
                                      Title = os.path.basename(filename),
                                      document = doc)
            doc.Draw(ps_dev)
            draw_alignment_marks(ps_dev, doc_bbox,
                                 align_length, align_distance)
            ps_dev.Close()
        finally:
            separator.undo_changes()


import Sketch.Scripting        
Sketch.Scripting.AddFunction('simple_separation',
                             _("Simple Separation"),
                             simple_separation,
                             script_type = Sketch.Scripting.AdvancedScript)
示例#10
0
    align_length = 12
    grow = align_length + align_distance
    llx, lly, urx, ury = doc_bbox
    ps_bbox = (llx - grow, lly - grow, urx + grow, ury + grow)
    for color in colors:
        separator = CreateSeparation(color)
        try:
            # do this in a try-finall to make sure the document colors
            # get restored even if something goes wrong
            doc.WalkHierarchy(separator.change_color)
            filename = basename + '-' + hexcolor(color) + '.ps'
            ps_dev = PostScriptDevice(filename,
                                      as_eps=1,
                                      bounding_box=ps_bbox,
                                      For=util.get_real_username(),
                                      CreationDate=util.current_date(),
                                      Title=os.path.basename(filename),
                                      document=doc)
            doc.Draw(ps_dev)
            draw_alignment_marks(ps_dev, doc_bbox, align_length,
                                 align_distance)
            ps_dev.Close()
        finally:
            separator.undo_changes()


import Sketch.Scripting
Sketch.Scripting.AddFunction('simple_separation',
                             _("Simple Separation"),
                             simple_separation,
                             script_type=Sketch.Scripting.AdvancedScript)
示例#11
0
def main():
    import Sketch
    global doc, psfile
    global tbase_style, courfont

    Sketch.init_lib()

    draw_printable = 1
    draw_visible = 0
    embed_fonts = 0
    eps_for = util.get_real_username()
    eps_date = util.current_date()
    eps_title = None
    rotate = 0

    doc = Document(create_layer=1)

    ## *****************************
    # start of drawing

    # indicate start of coord system first: + goes upward / rightward
    trec = getQuickRect(5, 5, -10, -10)
    doc.Insert(trec)

    # from create_text.py
    textfld = SimpleText(Translation(0, 0), "24pt")
    textfld.SetProperties(font=courfont, font_size=24)
    doc.Insert(textfld)

    ## add struct box nodes

    structNodeA = getStructBoxnode(
        "struct1",  # title label
        ("*pnt1", "*pointer2", "*point3"),
        ("var1", "variable2", "Varib3"))
    structNodeB = getStructBoxnode(
        "str2",  # title label
        (
            "*pnt1",
            "*pnt2",
            "*pnt3",
            "*pnt4",
            "*pnt5",
            "*pnt6",
        ),
        ("var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8",
         "var9"))
    structNodeC = getStructBoxnode(
        "str3",  # title label
        ("*pnt1", ),
        ())
    snAgrp = structNodeA[0]
    snBgrp = structNodeB[0]
    snCgrp = structNodeC[0]

    ## position nodes

    # place node A
    snAgrp.Translate(Point(100, 200))
    snAgrp.update_rects()

    # place node B - 'below left' of node A
    # (i.e. find lower right corner of A group;
    #   align upper left corner of B with that)
    sabr = snAgrp.bounding_rect
    sbbr = snBgrp.bounding_rect
    xtran = sabr.right - sbbr.left
    ytran = sabr.bottom - sbbr.top
    snBgrp.Translate(Point(xtran, ytran))
    snBgrp.update_rects()
    sbbr = snBgrp.bounding_rect

    # place node C - below, left aligned to node B
    scbr = snCgrp.bounding_rect
    xtran = sbbr.left - scbr.left
    ytran = sbbr.bottom - scbr.top
    snCgrp.Translate(Point(xtran, ytran))
    snCgrp.update_rects()
    scbr = snCgrp.bounding_rect

    # show struct nodes on drawing
    doc.Insert(snAgrp)
    doc.Insert(snBgrp)
    doc.Insert(snCgrp)

    # display the bounding boxes of struct nodes
    trecA = getQuickRect(sabr.left, sabr.bottom, sabr.right - sabr.left,
                         sabr.top - sabr.bottom)
    trecA.SetProperties(line_pattern=SolidPattern(StandardColors.red))
    trecB = getQuickRect(sbbr.left, sbbr.bottom, sbbr.right - sbbr.left,
                         sbbr.top - sbbr.bottom)
    trecB.SetProperties(line_pattern=SolidPattern(StandardColors.red))
    trecC = getQuickRect(scbr.left, scbr.bottom, scbr.right - scbr.left,
                         scbr.top - scbr.bottom)
    trecC.SetProperties(line_pattern=SolidPattern(StandardColors.red))
    doc.Insert(trecA)
    doc.Insert(trecB)
    doc.Insert(trecC)

    # make a connection
    # get dicts first
    snAdct = structNodeA[1]
    snBdct = structNodeB[1]
    snCdct = structNodeC[1]

    # put a rect around snBdct['box']
    # since grown(-10) aligns to box; shows that theres 10 units padding!
    tbr = snBdct['box'].bounding_rect.grown(-10)
    trecC = getQuickRect(tbr.left, tbr.bottom, tbr.right - tbr.left,
                         tbr.top - tbr.bottom)
    trecC.SetProperties(line_pattern=SolidPattern(StandardColors.green))
    doc.Insert(trecC)

    # for easier calc after:
    yjump = abs(snAdct['ptfl_1'].bounding_rect.center().y -
                snBdct['box'].bounding_rect.center().y) / 2

    # 'standard' connection:
    # start from 2nd [1] pointer of structNodeA - end in 'input' (left) of box of structNodeB
    # so, from dict we need:: structNodeA:'ptfl_1'; and structNodeB:'box'
    tconnline = getStdConnLine(
        snAdct['ptfl_1'],  # from (startpoint - moveto)
        snBdct['box'],  # to (endpoint)
        # here optional arguments for 'in-between' points;
        # (ordered) tuple of dict, where key is command:
        # like in tikz:: '|' means along y  ,  '-' means along x
        # (last {'-':-10}, is not needed - endpoint specifies it
        ({
            '-': 30
        }, {
            '|': -yjump
        }, {
            '-': -40
        }, {
            '|': -yjump
        }))
    doc.Insert(tconnline)

    # for easier calc after -
    # we won't use the "half-the-distance" directly, so we don't divide /2 here
    yjumpAC = abs(snAdct['ptfl_2'].bounding_rect.center().y -
                  snCdct['box'].bounding_rect.center().y)

    tconnlineAC = getStdConnLine(
        snAdct['ptfl_2'],  # from (startpoint - moveto)
        snCdct['box'],  # to (endpoint)
        ({
            '-': 20
        }, {
            '|': -(yjump - 30)
        }, {
            '-': -40
        }, {
            '|': -(yjumpAC - (yjump - 30))
        }))
    doc.Insert(tconnlineAC)

    ## *****************************
    # end of drawing - generate output file

    filename = ''  # was .sk filename to convert
    sk2ps(filename,
          thisfilename,
          printable=draw_printable,
          visible=draw_visible,
          For=eps_for,
          CreationDate=eps_date,
          Title=eps_title,
          rotate=rotate,
          embed_fonts=embed_fonts)