Example #1
0
    def write_month_header_secondary(self, g, cal):
        txt_atts = {'style': str(inkex.Style(self.style_month_secondary)),
                    'x': str((self.month_w - (self.day_w / 1.5))),
                    'y': "-1.5"}
        months_info = []
        for week in cal:
            for day in week:
                if day != 0:
                    tmp = self.options.hijri_month_names[day[1] - 1]
                    if self.options.primary_calendar == "hijri":
                        tmp = self.options.month_names[day[1] - 1]
                    try:
                        months_info.index((tmp, day[0]))
                    except ValueError:
                        months_info.append((tmp, day[0]))

        try:
            g.add(TextElement(**txt_atts)).text = unicode(
                "{0} - {1}".format(
                    months_info[0][0],
                    months_info[0][1]),
                self.options.input_encode)
            if len(months_info) > 1:
                txt_atts["y"] = "1.5"
                g.add(TextElement(**txt_atts)).text = unicode(
                    "{0} - {1}".format(
                        months_info[1][0],
                        months_info[1][1]),
                    self.options.input_encode)
        except:
            raise ValueError(months_info)
Example #2
0
    def effect(self):
        # get number of digits
        prec = int(self.options.precision)
        scale = self.svg.unittouu('1px')  # convert to document units
        self.options.offset *= scale
        factor = 1.0

        if self.svg.get('viewBox'):
            factor = self.svg.scale / self.svg.unittouu('1px')
            self.options.fontsize /= factor

        factor *= scale / self.svg.unittouu('1' + self.options.unit)

        # loop over all selected paths
        for node in self.svg.selection.filter(inkex.PathElement):
            csp = node.path.transform(node.composed_transform()).to_superpath()
            if self.options.mtype == "length":
                slengths, stotal = csplength(csp)
                self.group = node.getparent().add(TextElement())
            elif self.options.mtype == "area":
                stotal = abs(csparea(csp) * factor * self.options.scale)
                self.group = node.getparent().add(TextElement())
            else:
                try:
                    xc, yc = cspcofm(csp)
                except ValueError as err:
                    raise inkex.AbortExtension(str(err))
                self.group = node.getparent().add(inkex.PathElement())
                self.group.set('id', 'MassCenter_' + node.get('id'))
                self.add_cross(self.group, xc, yc, scale)
                continue
            # Format the length as string
            val = round(stotal * factor * self.options.scale, prec)
            self.options.method(node, str(val))
Example #3
0
    def write_month_header(self, g, m):
        txt_atts = {'style': str(inkex.Style(self.style_month)),
                    'x': str(-self.day_w / 3),
                    'y': str(self.day_h / 5)}
        try:
            text = unicode(self.options.month_names[m - 1], self.options.input_encode)
            if self.options.primary_calendar == "hijri":
                text = unicode(self.options.hijri_month_names[m - 1], self.options.input_encode)
            g.add(TextElement(**txt_atts)).text = text
        except:
            raise ValueError('You must select a correct system encoding.')

        gw = g.add(inkex.Group())
        week_x = 0
        if self.options.start_day == 'sun':
            day_names = self.options.day_names[:]
        else:
            day_names = self.options.day_names[1:]
            day_names.append(self.options.day_names[0])

        if self.options.show_weeknr:
            day_names.insert(0, self.options.weeknr_name)

        for wday in day_names:
            txt_atts = {'style': str(inkex.Style(self.style_day_name)),
                        'x': str(self.day_w * week_x),
                        'y': str(self.day_h)}
            try:
                gw.add(TextElement(**txt_atts)).text = unicode(
                    wday, self.options.input_encode)
            except:
                raise ValueError('You must select a correct system encoding.')

            week_x += 1
Example #4
0
 def add_text(self, x, y, text):
     """Add a text label at the given location"""
     elem = TextElement(x=str(x), y=str(y))
     elem.text = str(text)
     elem.style = {
         'font-size': self.svg.unittouu(self.options.fontsize),
         'fill-opacity': '1.0',
         'stroke': 'none',
         'font-weight': 'normal',
         'font-style': 'normal',
         'fill': '#999'
     }
     return elem
Example #5
0
 def draw_text(self, text, add_size=0, anchor='start', **kwargs):
     """Draw a textual label"""
     vtext = TextElement(**kwargs)
     vtext.style = {
         'fill': self.options.font_color,
         'font-family': self.options.font,
         'font-size': str(self.options.font_size + add_size) + 'px',
         'font-style': 'normal',
         'font-variant': 'normal',
         'font-weight': 'normal',
         'font-stretch': 'normal',
         '-inkscape-font-specification': 'Bitstream Charter',
         'text-align': anchor,
         'text-anchor': anchor,
     }
     vtext.text = str(text)
     return vtext
Example #6
0
 def test_path(self):
     """Test getting paths"""
     self.assertFalse(TextPath().get_path())
     self.assertFalse(TextElement().get_path())
     self.assertFalse(FlowRegion().get_path())
     self.assertFalse(FlowRoot().get_path())
     self.assertFalse(FlowPara().get_path())
     self.assertFalse(FlowSpan().get_path())
     self.assertFalse(Tspan().get_path())
Example #7
0
    def split_letters(self, node):
        """Returns a list of letters"""

        letters = []

        words = self.split_words(node)
        if not words:
            return letters

        for word in words:

            x = float(word.get("x"))
            y = word.get("y")

            # gets the font size. If element doesn't have a style attribute, it assumes font-size = 12px
            fontsize = word.style.get("font-size", "12px")
            fs = self.svg.unittouu(fontsize)

            # for each letter in element string
            for letter in word[0].text:
                tspan = Tspan()
                tspan.text = letter

                text = TextElement(**node.attrib)
                text.set("x", str(x))
                text.set("y", str(y))
                x += fs

                text.append(tspan)
                letters.append(text)
        return letters
def textAt( x, y, text, style, rotate=0 ):
  "Places a test-element at global-coordinates."
  
  elem = TextElement(x=str(x), y=str(y))
  elem.text = text
  elem.style = style
  if rotate != 0:
    elem.set('transform','rotate({},{},{})'.format(rotate,x,y))
  return elem
Example #9
0
    def generateText(self, text, x, y, size):
        tspan = Tspan()
        tspan.text = text

        textElement = TextElement()
        textElement.set("x", str(x))
        textElement.set("y", str(y))
        # textElement.style = "font-size:50px; font-family:Metal Lord"
        textElement.style = "font-size:{}px;".format(size)

        textElement.append(tspan)

        return textElement
Example #10
0
 def effect(self):
     self.validate_options()
     self.calculate_size_and_positions()
     parent = self.document.getroot()
     txt_atts = {'id': 'year_' + str(self.options.year)}
     self.year_g = parent.add(inkex.Group(**txt_atts))
     txt_atts = {'style': str(inkex.Style(self.style_year)),
                 'x': str(self.doc_w / 2),
                 'y': str(self.day_w * 1.5)}
     self.year_g.add(TextElement(**txt_atts)).text = str(self.options.year)
     try:
         if self.options.month == 0:
             for m in range(1, 13):
                 self.create_month(m)
         else:
             self.create_month(self.options.month)
     except ValueError as err:
         return inkex.errormsg(str(err))
Example #11
0
    def split_words(self, node):
        """Returns a list of words"""
        words = []

        # Function to recursively extract text
        def plain_str(elem):
            words = []
            if elem.text:
                words.append(elem.text)
            for n in elem:
                words.extend(plain_str(n))
                if n.tail:
                    words.append(n.tail)
            return words

        # if text has more than one line, iterates through elements
        lines = self.split_lines(node)
        if not lines:
            return words

        for line in lines:
            # gets the position of text node
            x = float(line.get("x"))
            y = line.get("y")

            # gets the font size. if element doesn't have a style attribute, it assumes font-size = 12px
            fontsize = line.style.get("font-size", "12px")
            fs = self.svg.unittouu(fontsize)

            # extract and returns a list of words
            words_list = "".join(plain_str(line)).split()
            prev_len = 0

            # creates new text nodes for each string in words_list
            for word in words_list:
                tspan = Tspan()
                tspan.text = word

                text = TextElement(**line.attrib)
                tspan.set('sodipodi:role', "line")

                # positioning new text elements
                x = x + prev_len * fs
                prev_len = len(word)
                text.set("x", str(x))
                text.set("y", str(y))

                text.append(tspan)
                words.append(text)

        return words
Example #12
0
    def effect(self):
        if len(self.svg.selected) == 0:
            inkex.errormsg("Please select some paths first.")
            exit()

        for id, node in self.svg.selected.items():
            id = node.get('id')
            self.group = node.getparent().add(TextElement())
            csp = node.path.transform(node.composed_transform()).to_superpath()
            bbox = node.bounding_box()
            tx, ty = bbox.center
            anchor = 'middle'

            node = self.group
            new = node.add(Tspan())
            new.set('sodipodi:role', 'line')
            s = {
                'text-align': 'center',
                'vertical-align': 'bottom',
                'text-anchor': 'middle',
                'font-size': str(self.options.fontsize) + 'px',
                'font-weight': self.options.fontweight,
                'font-style': 'normal',
                'font-family': self.options.font,
                'fill': str(self.options.color)
            }
            new.set('style', str(inkex.Style(s)))
            new.set('dy', '0')

            if self.options.capitals:
                id = id.upper()

            new.text = id.replace(self.options.replaced,
                                  self.options.replacewith)
            node.set('x', str(tx))
            node.set('y', str(ty))
            node.set('transform',
                     'rotate(%s, %s, %s)' % (-int(self.options.angle), tx, ty))
Example #13
0
 def create_month(self, m):
     txt_atts = {
         'transform':
         'translate(' +
         str(self.year_margin +
             (self.month_w + self.month_margin) * self.month_x_pos) + ',' +
         str((self.day_h * 4) + (self.month_h * self.month_y_pos)) + ')',
         'id':
         'month_' + str(m) + '_' + str(self.options.year)
     }
     g = self.year_g.add(inkex.Group(**txt_atts))
     self.write_month_header(g, m)
     gdays = g.add(inkex.Group())
     cal = calendar.monthcalendar(self.options.year, m)
     if m == 1:
         if self.options.year > 1:
             before_month = \
                 self.in_line_month(calendar.monthcalendar(self.options.year - 1, 12))
     else:
         before_month = \
             self.in_line_month(calendar.monthcalendar(self.options.year, m - 1))
     if m == 12:
         next_month = \
             self.in_line_month(calendar.monthcalendar(self.options.year + 1, 1))
     else:
         next_month = \
             self.in_line_month(calendar.monthcalendar(self.options.year, m + 1))
     if len(cal) < 6:
         # add a line after the last week
         cal.append([0, 0, 0, 0, 0, 0, 0])
     if len(cal) < 6:
         # add a line before the first week (Feb 2009)
         cal.reverse()
         cal.append([0, 0, 0, 0, 0, 0, 0])
         cal.reverse()
     # How mutch before month days will be showed:
     bmd = cal[0].count(0) + cal[1].count(0)
     before = True
     week_y = 0
     for week in cal:
         if (self.weeknr != 0 and
             ((self.options.start_day == 'mon' and week[0] != 0) or
              (self.options.start_day == 'sun' and week[1] != 0))) or \
                 (self.weeknr == 0 and
                  ((self.options.start_day == 'mon' and week[3] > 0) or
                   (self.options.start_day == 'sun' and week[4] > 0))):
             self.weeknr += 1
         week_x = 0
         if self.options.show_weeknr:
             # Remove leap week (starting previous year) and empty weeks
             if self.weeknr != 0 and not (week[0] == 0 and week[6] == 0):
                 style = self.style_weeknr
                 txt_atts = {
                     'style': str(inkex.Style(style)),
                     'x': str(self.day_w * week_x),
                     'y': str(self.day_h * (week_y + 2))
                 }
                 gdays.add(TextElement(**txt_atts)).text = str(self.weeknr)
                 week_x += 1
             else:
                 week_x += 1
         for day in week:
             style = self.style_day
             if self.is_weekend(week_x - self.cols_before):
                 style = self.style_weekend
             if day == 0:
                 style = self.style_nmd
             txt_atts = {
                 'style': str(inkex.Style(style)),
                 'x': str(self.day_w * week_x),
                 'y': str(self.day_h * (week_y + 2))
             }
             text = None
             if day == 0 and not self.options.fill_edb:
                 pass  # draw nothing
             elif day == 0:
                 if before:
                     text = str(before_month[-bmd])
                     bmd -= 1
                 else:
                     text = str(next_month[bmd])
                     bmd += 1
             else:
                 text = str(day)
                 before = False
             if text:
                 gdays.add(TextElement(**txt_atts)).text = text
             week_x += 1
         week_y += 1
     self.month_x_pos += 1
     if self.month_x_pos >= self.months_per_line:
         self.month_x_pos = 0
         self.month_y_pos += 1
Example #14
0
    def generate(self):
        """Generate the actual svg from the coding"""
        string = self.encode(self.text)

        if string == 'ERROR':
            return

        name = self.get_id('barcode')

        # use an svg group element to contain the barcode
        barcode = Group()
        barcode.set('id', name)
        barcode.set('style', 'fill: black;')

        barcode.transform.add_translate(self.pos_x, self.pos_y)
        if self.scale:
            barcode.transform.add_scale(self.scale)

        bar_id = 1
        bar_offset = 0
        tops = set()

        for datum in self.graphical_array(string):
            # Datum 0 tells us what style of bar is to come next
            style = self.get_style(int(datum[0]))
            # Datum 1 tells us what width in units,
            # style tells us how wide a unit is
            width = int(datum[1]) * int(style['width'])

            if style['write']:
                tops.add(style['top'])
                rect = Rectangle()
                rect.set('x', str(bar_offset))
                rect.set('y', str(style['top']))
                if self.pos_text == TEXT_POS_TOP:
                    rect.set('y', str(style['top'] + self.font_size))
                rect.set('id', "{}_bar{:d}".format(name, bar_id))
                rect.set('width', str(width))
                rect.set('height', str(style['height']))
                barcode.append(rect)
            bar_offset += width
            bar_id += 1

        for extra in self._extra:
            if extra is not None:
                barcode.append(extra)

        bar_width = bar_offset
        # Add text at the bottom of the barcode
        text = TextElement()
        text.set('x', str(int(bar_width / 2)))
        text.set('y', str(min(tops) + self.font_size - 1))
        if self.pos_text == TEXT_POS_BOTTOM:
            text.set('y', str(self.height + max(tops) + self.font_size))
        text.set('style', TEXT_TEMPLATE % self.font_size)
        text.set('xml:space', 'preserve')
        text.set('id', '{}_text'.format(name))
        text.text = str(self.text)
        barcode.append(text)
        return barcode
Example #15
0
def writeSVG(self, unfolding, size, printNumbers):
    mesh = unfolding[0]
    isFoldingEdge = unfolding[1]
    glueNumber = unfolding[3]
    foldingDirection = unfolding[4]

    # Calculate the bounding box
    [xmin, ymin, boxSize] = findBoundingBox(unfolding[0])

    if size > 0:
        boxSize = size

    strokewidth = 0.002 * boxSize
    dashLength = 0.008 * boxSize
    spaceLength = 0.02 * boxSize
    textDistance = 0.02 * boxSize
    textStrokewidth = 0.05 * strokewidth
    textLength = 0.001 * boxSize
    fontsize = 0.015 * boxSize

    # Generate a main group
    paperfoldPageGroup = self.document.getroot().add(
        inkex.Group(id=self.svg.get_unique_id("paperfold-page-")))

    # Go over all edges of the grid
    for edge in mesh.edges():
        # The two endpoints
        he = mesh.halfedge_handle(edge, 0)
        vertex0 = mesh.point(mesh.from_vertex_handle(he))
        vertex1 = mesh.point(mesh.to_vertex_handle(he))

        # Write a straight line between the two corners
        line = paperfoldPageGroup.add(inkex.PathElement())
        #line.path = [
        #       ["M", [vertex0[0], vertex0[1]]],
        #       ["L", [vertex1[0], vertex1[1]]]
        #    ]
        line.set(
            'd', "M " + str(vertex0[0]) + "," + str(vertex0[1]) + " " +
            str(vertex1[0]) + "," + str(vertex1[1]))
        # Colour depending on folding direction
        lineStyle = {"fill": "none"}
        if foldingDirection[edge.idx()] > 0:
            lineStyle.update({"stroke": self.options.color_mountain_cut})
            line.set("id", self.svg.get_unique_id("mountain-cut-"))
        elif foldingDirection[edge.idx()] < 0:
            lineStyle.update({"stroke": self.options.color_valley_cut})
            line.set("id", self.svg.get_unique_id("valley-cut-"))

        lineStyle.update({"stroke-width": str(strokewidth)})
        lineStyle.update({"stroke-linecap": "butt"})
        lineStyle.update({"stroke-linejoin": "miter"})
        lineStyle.update({"stroke-miterlimit": "4"})

        # Dotted lines for folding edges
        if isFoldingEdge[edge.idx()]:
            lineStyle.update({
                "stroke-dasharray": (str(dashLength) + ", " + str(spaceLength))
            })
            if foldingDirection[edge.idx()] > 0:
                lineStyle.update(
                    {"stroke": self.options.color_mountain_perforate})
                line.set("id", self.svg.get_unique_id("mountain-perforate-"))
            if foldingDirection[edge.idx()] < 0:
                lineStyle.update(
                    {"stroke": self.options.color_valley_perforate})
                line.set("id", self.svg.get_unique_id("valley-perforate-"))
        else:
            lineStyle.update({"stroke-dasharray": "none"})

        lineStyle.update({"stroke-dashoffset": "0"})
        lineStyle.update({"stroke-opacity": "1"})
        line.style = lineStyle

        # The number of the edge to be glued
        if not isFoldingEdge[edge.idx()]:
            # Find halfedge in the face
            halfEdge = mesh.halfedge_handle(edge, 0)
            if mesh.face_handle(halfEdge).idx() == -1:
                halfEdge = mesh.opposite_halfedge_handle(halfEdge)
            vector = mesh.calc_edge_vector(halfEdge)
            # normalize
            vector = vector / np.linalg.norm(vector)
            midPoint = 0.5 * (mesh.point(mesh.from_vertex_handle(halfEdge)) +
                              mesh.point(mesh.to_vertex_handle(halfEdge)))
            rotatedVector = np.array([-vector[1], vector[0], 0])
            angle = np.arctan2(vector[1], vector[0])
            position = midPoint + textDistance * rotatedVector
            rotation = 180 / np.pi * angle

            if (printNumbers):
                text = paperfoldPageGroup.add(
                    TextElement(id=self.svg.get_unique_id("number-")))
                text.set("x", str(position[0]))
                text.set("y", str(position[1]))
                text.set("font-size", str(fontsize))
                text.set("style", "stroke-width:" + str(textStrokewidth))
                text.set(
                    "transform", "rotate(" + str(rotation) + "," +
                    str(position[0]) + "," + str(position[1]) + ")")

                tspan = text.add(Tspan())
                tspan.set("x", str(position[0]))
                tspan.set("y", str(position[1]))
                tspan.set("style", "stroke-width:" + str(textStrokewidth))
                tspan.text = str(glueNumber[edge.idx()])
    return paperfoldPageGroup
Example #16
0
    def effect(self):
        self.mark_size = self.svg.unittouu('1cm')
        self.min_mark_margin = self.svg.unittouu('3mm')

        if self.options.where == 'selection':
            bbox = self.svg.selection.bounding_box()
            if bbox is None:
                raise inkex.AbortExtension(_("Selection is empty"))
        else:
            bbox = self.svg.get_page_bbox()

        # Get SVG document dimensions
        # self.width must be replaced by bbox.right. same to others.
        svg = self.document.getroot()

        # Convert parameters to user unit
        offset = self.svg.unittouu(str(self.options.crop_offset) +
                                   self.options.unit)
        bt = self.svg.unittouu(str(self.options.bleed_top) + self.options.unit)
        bb = self.svg.unittouu(str(self.options.bleed_bottom) + self.options.unit)
        bl = self.svg.unittouu(str(self.options.bleed_left) + self.options.unit)
        br = self.svg.unittouu(str(self.options.bleed_right) + self.options.unit)
        # Bleed margin
        if bt < offset:
            bmt = 0
        else:
            bmt = bt - offset
        if bb < offset:
            bmb = 0
        else:
            bmb = bb - offset
        if bl < offset:
            bml = 0
        else:
            bml = bl - offset
        if br < offset:
            bmr = 0
        else:
            bmr = br - offset

        # Define the new document limits
        offset_left = bbox.left - offset
        offset_right = bbox.right + offset
        offset_top = bbox.top - offset
        offset_bottom = bbox.bottom + offset

        # Get middle positions
        middle_vertical = bbox.top + (bbox.height / 2)
        middle_horizontal = bbox.left + (bbox.width / 2)

        # Test if printing-marks layer existis
        layer = self.svg.xpath('//*[@id="printing-marks" and @inkscape:groupmode="layer"]')
        if layer:
            svg.remove(layer[0])  # remove if it existis
        # Create a new layer
        layer = svg.add(inkex.Layer.new("Printing Marks"))
        layer.set('id', 'printing-marks')
        layer.set('sodipodi:insensitive', 'true')

        # Crop Mark
        if self.options.crop_marks:
            # Create a group for Crop Mark
            g_crops = layer.add(inkex.Group(id='CropMarks'))
            g_crops.label = 'CropMarks'

            # Top left Mark
            self.draw_crop_line(bbox.left, offset_top,
                                bbox.left, offset_top - self.mark_size,
                                'cropTL1', g_crops)
            self.draw_crop_line(offset_left, bbox.top,
                                offset_left - self.mark_size, bbox.top,
                                'cropTL2', g_crops)

            # Top right Mark
            self.draw_crop_line(bbox.right, offset_top,
                                bbox.right, offset_top - self.mark_size,
                                'cropTR1', g_crops)
            self.draw_crop_line(offset_right, bbox.top,
                                offset_right + self.mark_size, bbox.top,
                                'cropTR2', g_crops)

            # Bottom left Mark
            self.draw_crop_line(bbox.left, offset_bottom,
                                bbox.left, offset_bottom + self.mark_size,
                                'cropBL1', g_crops)
            self.draw_crop_line(offset_left, bbox.bottom,
                                offset_left - self.mark_size, bbox.bottom,
                                'cropBL2', g_crops)

            # Bottom right Mark
            self.draw_crop_line(bbox.right, offset_bottom,
                                bbox.right, offset_bottom + self.mark_size,
                                'cropBR1', g_crops)
            self.draw_crop_line(offset_right, bbox.bottom,
                                offset_right + self.mark_size, bbox.bottom,
                                'cropBR2', g_crops)

        # Bleed Mark
        if self.options.bleed_marks:
            # Create a group for Bleed Mark
            g_bleed = layer.add(inkex.Group())
            g_bleed.label = 'BleedMarks'
            g_bleed.set('id', 'BleedMarks')

            # Top left Mark
            self.draw_bleed_line(bbox.left - bl, offset_top - bmt,
                                 bbox.left - bl, offset_top - bmt - self.mark_size,
                                 'bleedTL1', g_bleed)
            self.draw_bleed_line(offset_left - bml, bbox.top - bt,
                                 offset_left - bml - self.mark_size, bbox.top - bt,
                                 'bleedTL2', g_bleed)

            # Top right Mark
            self.draw_bleed_line(bbox.right + br, offset_top - bmt,
                                 bbox.right + br, offset_top - bmt - self.mark_size,
                                 'bleedTR1', g_bleed)
            self.draw_bleed_line(offset_right + bmr, bbox.top - bt,
                                 offset_right + bmr + self.mark_size, bbox.top - bt,
                                 'bleedTR2', g_bleed)

            # Bottom left Mark
            self.draw_bleed_line(bbox.left - bl, offset_bottom + bmb,
                                 bbox.left - bl, offset_bottom + bmb + self.mark_size,
                                 'bleedBL1', g_bleed)
            self.draw_bleed_line(offset_left - bml, bbox.bottom + bb,
                                 offset_left - bml - self.mark_size, bbox.bottom + bb,
                                 'bleedBL2', g_bleed)

            # Bottom right Mark
            self.draw_bleed_line(bbox.right + br, offset_bottom + bmb,
                                 bbox.right + br, offset_bottom + bmb + self.mark_size,
                                 'bleedBR1', g_bleed)
            self.draw_bleed_line(offset_right + bmr, bbox.bottom + bb,
                                 offset_right + bmr + self.mark_size, bbox.bottom + bb,
                                 'bleedBR2', g_bleed)

        # Registration Mark
        if self.options.reg_marks:
            # Create a group for Registration Mark
            g_center = layer.add(inkex.Group())
            g_center.label = 'RegistrationMarks'
            g_center.set('id', 'RegistrationMarks')
            # Left Mark
            cx = max(bml + offset, self.min_mark_margin)
            self.draw_reg_marks(bbox.left - cx - (self.mark_size / 2),
                                middle_vertical - self.mark_size * 1.5,
                                '0', 'regMarkL', g_center)

            # Right Mark
            cx = max(bmr + offset, self.min_mark_margin)
            self.draw_reg_marks(bbox.right + cx + (self.mark_size / 2),
                                middle_vertical - self.mark_size * 1.5,
                                '180', 'regMarkR', g_center)

            # Top Mark
            cy = max(bmt + offset, self.min_mark_margin)
            self.draw_reg_marks(middle_horizontal,
                                bbox.top - cy - (self.mark_size / 2),
                                '90', 'regMarkT', g_center)

            # Bottom Mark
            cy = max(bmb + offset, self.min_mark_margin)
            self.draw_reg_marks(middle_horizontal,
                                bbox.bottom + cy + (self.mark_size / 2),
                                '-90', 'regMarkB', g_center)

        # Star Target
        if self.options.star_target:
            # Create a group for Star Target
            g_center = layer.add(inkex.Group())
            g_center.label = 'StarTarget'
            g_center.set('id', 'StarTarget')

            if bbox.height < bbox.width:
                # Left Star
                cx = max(bml + offset, self.min_mark_margin)
                self.draw_star_target(bbox.left - cx - (self.mark_size / 2),
                                      middle_vertical,
                                      'starTargetL', g_center)
                # Right Star
                cx = max(bmr + offset, self.min_mark_margin)
                self.draw_star_target(bbox.right + cx + (self.mark_size / 2),
                                      middle_vertical,
                                      'starTargetR', g_center)
            else:
                # Top Star
                cy = max(bmt + offset, self.min_mark_margin)
                self.draw_star_target(middle_horizontal - self.mark_size * 1.5,
                                      bbox.top - cy - (self.mark_size / 2),
                                      'starTargetT', g_center)
                # Bottom Star
                cy = max(bmb + offset, self.min_mark_margin)
                self.draw_star_target(middle_horizontal - self.mark_size * 1.5,
                                      bbox.bottom + cy + (self.mark_size / 2),
                                      'starTargetB', g_center)

        # Colour Bars
        if self.options.colour_bars:
            # Create a group for Colour Bars
            g_center = layer.add(inkex.Group())
            g_center.label = 'ColourBars'
            g_center.set('id', 'PrintingColourBars')

            if bbox.height > bbox.width:
                # Left Bars
                cx = max(bml + offset, self.min_mark_margin)
                self.draw_coluor_bars(bbox.left - cx - (self.mark_size / 2),
                                      middle_vertical + self.mark_size,
                                      90,
                                      'PrintingColourBarsL', g_center, bbox)
                # Right Bars
                cx = max(bmr + offset, self.min_mark_margin)
                self.draw_coluor_bars(bbox.right + cx + (self.mark_size / 2),
                                      middle_vertical + self.mark_size,
                                      90,
                                      'PrintingColourBarsR', g_center, bbox)
            else:
                # Top Bars
                cy = max(bmt + offset, self.min_mark_margin)
                self.draw_coluor_bars(middle_horizontal + self.mark_size,
                                      bbox.top - cy - (self.mark_size / 2),
                                      0,
                                      'PrintingColourBarsT', g_center, bbox)
                # Bottom Bars
                cy = max(bmb + offset, self.min_mark_margin)
                self.draw_coluor_bars(middle_horizontal + self.mark_size,
                                      bbox.bottom + cy + (self.mark_size / 2),
                                      0,
                                      'PrintingColourBarsB', g_center, bbox)

        # Page Information
        if self.options.page_info:
            # Create a group for Page Information
            g_pag_info = layer.add(inkex.Group())
            g_pag_info.label = 'PageInformation'
            g_pag_info.set('id', 'PageInformation')
            y_margin = max(bmb + offset, self.min_mark_margin)
            txt_attribs = {
                'style': 'font-size:12px;font-style:normal;font-weight:normal;fill:#000000;font-family:Bitstream Vera Sans,sans-serif;text-anchor:middle;text-align:center',
                'x': str(middle_horizontal),
                'y': str(bbox.bottom + y_margin + self.mark_size + 20)
            }
            txt = g_pag_info.add(TextElement(**txt_attribs))
            txt.text = 'Page size: ' + \
                       str(round(self.svg.uutounit(bbox.width, self.options.unit), 2)) + \
                       'x' + \
                       str(round(self.svg.uutounit(bbox.height, self.options.unit), 2)) + \
                       ' ' + self.options.unit
Example #17
0
    def split_lines(self, node):
        """Returns a list of lines"""
        lines = []
        count = 1

        for elem in node:
            if isinstance(elem, TextPath):
                inkex.errormsg(
                    "Text on path isn't supported. First remove text from path."
                )
                break
            elif not isinstance(elem, (FlowPara, Tspan)):
                continue

            text = TextElement(**node.attrib)

            # handling flowed text nodes
            if isinstance(node, FlowRoot):
                fontsize = node.style.get("font-size", "12px")
                fs = self.svg.unittouu(fontsize)

                # selects the flowRegion's child (svg:rect) to get @X and @Y
                flowref = node.findone('svg:flowRegion')[0]

                if isinstance(flowref, Rectangle):
                    text.set("x", flowref.get("x"))
                    text.set("y", str(float(flowref.get("y")) + fs * count))
                    count += 1
                else:
                    inkex.debug(
                        "This type of text element isn't supported. First unflow text."
                    )
                    break

                # now let's convert flowPara into tspan
                tspan = Tspan()
                tspan.set("sodipodi:role", "line")
                tspan.text = elem.text
                text.append(tspan)

            else:
                from copy import copy
                x = elem.get("x") or node.get("x")
                y = elem.get("y") or node.get("y")

                text.set("x", x)
                text.set("y", y)
                text.append(copy(elem))

            lines.append(text)

        return lines
Example #18
0
    def create_month(self, m):
        txt_atts = {
            'transform': 'translate(' +
                         str(self.year_margin +
                             (self.month_w + self.month_margin) *
                             self.month_x_pos) +
                         ',' +
                         str((self.day_h * 4) +
                             (self.month_h * self.month_y_pos)) +
                         ')',
            'id': 'month_' +
                  str(m) +
                  '_' +
                  str(self.options.year)}
        g = self.year_g.add(inkex.Group(**txt_atts))
        self.write_month_header(g, m)
        gdays = g.add(inkex.Group())
        gdays_secondary = g.add(inkex.Group())
        if self.options.primary_calendar == "hijri":
            cal = hijri_monthcalendar(self.options.year, m, self.options.adjust_hijri_date)
            cal_secondary = self.generate_gregorian(cal, self.options.year, m, self.options.adjust_hijri_date)
        else:
            cal = calendar.monthcalendar(self.options.year, m)
            cal_secondary = self.generate_hijri(cal, self.options.year, m)

        if self.options.enable_secondary_date:
            gmonths_secondary = g.add(inkex.Group())
            self.write_month_header_secondary(gmonths_secondary, cal_secondary)

        if m == 1:
            if self.options.year > 1:
                tmp_cal = calendar.monthcalendar(self.options.year - 1, 12)
                if self.options.primary_calendar == "hijri":
                    tmp_cal = hijri_monthcalendar(self.options.year - 1, 12, self.options.adjust_hijri_date)
                    before_month = self.in_line_month(tmp_cal)
                    before_month_secondary = \
                    self.in_line_month(self.generate_gregorian(tmp_cal, self.options.year - 1, 12, self.options.adjust_hijri_date))
                else:
                    before_month = self.in_line_month(tmp_cal)
                    before_month_secondary = \
                        self.in_line_month(self.generate_hijri(tmp_cal, self.options.year - 1, 12))

        else:
            if self.options.primary_calendar == "hijri":
                tmp_cal = hijri_monthcalendar(self.options.year, m - 1, self.options.adjust_hijri_date)
                before_month = self.in_line_month(tmp_cal)
                before_month_secondary = \
                    self.in_line_month(self.generate_gregorian(tmp_cal, self.options.year, m - 1, self.options.adjust_hijri_date))
            else:
                tmp_cal = calendar.monthcalendar(self.options.year, m - 1)
                before_month = self.in_line_month(tmp_cal)
                before_month_secondary = \
                    self.in_line_month(self.generate_hijri(tmp_cal, self.options.year, m - 1))
        if m == 12:
            tmp_cal = calendar.monthcalendar(self.options.year + 1, 1)
            if self.options.primary_calendar == "hijri":
                tmp_cal = hijri_monthcalendar(self.options.year + 1, 1, self.options.adjust_hijri_date)
                next_month = self.in_line_month(tmp_cal)
                next_month_secondary = \
                        self.in_line_month(self.generate_gregorian(tmp_cal, self.options.year + 1, 1, self.options.adjust_hijri_date))
            else:
                next_month = self.in_line_month(tmp_cal)
                next_month_secondary = \
                        self.in_line_month(self.generate_hijri(tmp_cal, self.options.year + 1, 1))
        else:
            tmp_cal = calendar.monthcalendar(self.options.year, m + 1)
            if self.options.primary_calendar == "hijri":
                tmp_cal = hijri_monthcalendar(self.options.year, m + 1, self.options.adjust_hijri_date)
                next_month = self.in_line_month(tmp_cal)
                next_month_secondary = \
                    self.in_line_month(self.generate_gregorian(tmp_cal, self.options.year, m + 1, self.options.adjust_hijri_date))
            else:
                next_month = self.in_line_month(tmp_cal)
                next_month_secondary = \
                    self.in_line_month(self.generate_hijri(tmp_cal, self.options.year, m + 1))
        if len(cal) < 6:
            # add a line after the last week
            cal.append([0, 0, 0, 0, 0, 0, 0])
            cal_secondary.append([0, 0, 0, 0, 0, 0, 0])
        if len(cal) < 6:
            # add a line before the first week (Feb 2009)
            cal.reverse()
            cal.append([0, 0, 0, 0, 0, 0, 0])
            cal.reverse()
            # add a line before the first week (Feb 2009)
            cal_secondary.reverse()
            cal_secondary.append([0, 0, 0, 0, 0, 0, 0])
            cal_secondary.reverse()
        # How mutch before month days will be showed:
        bmd = cal[0].count(0) + cal[1].count(0)
        bmd_secondary = cal_secondary[0].count(0) + cal_secondary[1].count(0)
        before = True
        week_y = 0

        for w_idx,week in enumerate(cal):
            if (self.weeknr != 0 and
                ((self.options.start_day == 'mon' and week[0] != 0) or
                 (self.options.start_day == 'sun' and week[1] != 0))) or \
                    (self.weeknr == 0 and
                     ((self.options.start_day == 'mon' and week[3] > 0) or
                      (self.options.start_day == 'sun' and week[4] > 0))):
                self.weeknr += 1
            week_x = 0
            if self.options.show_weeknr:
                # Remove leap week (starting previous year) and empty weeks
                if self.weeknr != 0 and not (week[0] == 0 and week[6] == 0):
                    style = self.style_weeknr
                    txt_atts = {'style': str(inkex.Style(style)),
                                'x': str(self.day_w * week_x),
                                'y': str(self.day_h * (week_y + 2))}
                    gdays.add(TextElement(**txt_atts)).text = str(self.weeknr)
                    week_x += 1
                else:
                    week_x += 1
            for d_idx,day in enumerate(week):
                style = self.style_day
                style_hijri = self.style_day_hijri
                if self.is_weekend(week_x - self.cols_before):
                    style = self.style_weekend
                    style_hijri = self.style_weekend_hijri
                if day == 0:
                    style = self.style_nmd
                txt_atts = {'style': str(inkex.Style(style)),
                            'x': str(self.day_w * (week_x)),
                            'y': str(self.day_h * (week_y + 2))}
                txt_atts_hijri = {'style': str(inkex.Style(style_hijri)),
                            'x': str((self.day_w * week_x) + 2),
                            'y': str((self.day_h * (week_y + 2)) + 2)}
                text = None
                text_secondary = None
                if day == 0 and not self.options.fill_edb:
                    pass  # draw nothing
                elif day == 0:
                    if before:
                        text = str(before_month[-bmd])
                        bmd -= 1
                        text_secondary = str(before_month_secondary[-bmd_secondary][2])
                        bmd_secondary -= 1
                    else:
                        text = str(next_month[bmd])
                        bmd += 1
                        text_secondary = str(next_month_secondary[bmd_secondary][2])
                        bmd_secondary += 1
                else:
                    text = str(day)
                    text_secondary = str(cal_secondary[w_idx][d_idx][2])
                    before = False
                if text:
                    if self.options.use_farsi_day != "second":
                        text = to_farsi(text)
                    gdays.add(TextElement(**txt_atts)).text = text
                if self.options.enable_secondary_date and text_secondary:
                    if self.options.use_farsi_day != "primer":
                        text_secondary = to_farsi(text_secondary)
                    gdays_secondary.add(TextElement(**txt_atts_hijri)).text = text_secondary
                week_x += 1
            week_y += 1
        self.month_x_pos += 1
        if self.month_x_pos >= self.months_per_line:
            self.month_x_pos = 0
            self.month_y_pos += 1
Example #19
0
    def effect(self):

        if len(self.svg.selection) != 1:
            raise AbortExtension(_("Debe seleccionar un objeto"))

        scale = self.svg.unittouu('1mm')  # convert to document units

        patternSize = self.options.patternSize
        fromSize = self.options.fromSize
        toSize = self.options.toSize

        if not (fromSize <= patternSize <= toSize):
            raise AbortExtension(
                _("La talla del patrĂ³n debe estar dentro de desde y hasta"))

        downerSizesCount = patternSize - fromSize
        upperSizesCount = toSize - patternSize

        pattern = self.svg.selection.first()
        parent = pattern.getparent()

        bbox = pattern.shape_box()
        scaleX = 10 * scale  # scale width 10mm
        scaleY = 23.21 * scale  # scale height 23.21mm
        width = bbox.width * scale
        height = bbox.height * scale

        for i, size in enumerate(
                range(patternSize + upperSizesCount, patternSize, -1)):
            copy = pattern.duplicate()
            size_text = TextElement()

            proportionX = 1 + (1 - ((width - (scaleX *
                                              (upperSizesCount - i))) / width))
            proportionY = 1 + (1 - ((height -
                                     (scaleY *
                                      (upperSizesCount - i))) / height))

            transform = Transform()
            transform.add_scale(proportionX, proportionY)
            copy.transform = transform

            size_text.text = str(size)
            size_text.set(
                'style',
                "font-size:8px;shape-inside:url(#{});".format(copy.get('id')))

            group = Group()
            group.append(copy)
            group.append(size_text)
            parent.append(group)

            group.set(
                'transform',
                "translate(-{},-{})".format(copy.shape_box().left,
                                            copy.shape_box().top))

        for i, size in enumerate(
                range(patternSize - 1, patternSize - downerSizesCount - 1, -1),
                1):
            copy = pattern.duplicate()
            size_text = TextElement()

            proportionX = (width - (scaleX * i)) / width
            proportionY = (height - (scaleY * i)) / height

            transform = Transform()
            transform.add_scale(proportionX, proportionY)
            copy.transform = transform

            size_text.text = str(size)
            size_text.set(
                'style',
                "font-size:8px;shape-inside:url(#{});".format(copy.get('id')))

            group = Group()
            group.append(copy)
            group.append(size_text)
            parent.append(group)

            group.set(
                'transform',
                "translate(-{},-{})".format(copy.shape_box().left,
                                            copy.shape_box().top))

        patternGroup = Group()
        pattern_size_text = TextElement()
        pattern_size_text.text = str(patternSize)
        pattern_size_text.set(
            'style',
            "font-size:8px;shape-inside:url(#{});".format(pattern.get('id')))
        patternGroup.append(pattern)
        patternGroup.append(pattern_size_text)
        parent.append(patternGroup)