code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
from .drawing import DeviceGray from .enums import TextMode class GraphicsStateMixin: """Mixin class for managing a stack of graphics state variables. To the subclassing library and its users, the variables look like normal instance attributes. But by the magic of properties, we can push and pop levels as needed, and users will always see and modify just the current version. This class is mixed in by fpdf.FPDF(), and is not meant to be used directly by user code. """ DEFAULT_DRAW_COLOR = DeviceGray(0) DEFAULT_FILL_COLOR = DeviceGray(0) DEFAULT_TEXT_COLOR = DeviceGray(0) def __init__(self, *args, **kwargs): self.__statestack = [ dict( draw_color=self.DEFAULT_DRAW_COLOR, fill_color=self.DEFAULT_FILL_COLOR, text_color=self.DEFAULT_TEXT_COLOR, underline=False, font_style="", font_stretching=100, font_family="", font_size_pt=0, current_font={}, dash_pattern=dict(dash=0, gap=0, phase=0), line_width=0, text_mode=TextMode.FILL, ), ] super().__init__(*args, **kwargs) def _push_local_stack(self): self.__statestack.append(self.__statestack[-1].copy()) def _pop_local_stack(self): del self.__statestack[-1] @property def draw_color(self): return self.__statestack[-1]["draw_color"] @draw_color.setter def draw_color(self, v): self.__statestack[-1]["draw_color"] = v @property def fill_color(self): return self.__statestack[-1]["fill_color"] @fill_color.setter def fill_color(self, v): self.__statestack[-1]["fill_color"] = v @property def text_color(self): return self.__statestack[-1]["text_color"] @text_color.setter def text_color(self, v): self.__statestack[-1]["text_color"] = v @property def underline(self): return self.__statestack[-1]["underline"] @underline.setter def underline(self, v): self.__statestack[-1]["underline"] = v @property def font_style(self): return self.__statestack[-1]["font_style"] @font_style.setter def font_style(self, v): self.__statestack[-1]["font_style"] = v @property def font_stretching(self): return self.__statestack[-1]["font_stretching"] @font_stretching.setter def font_stretching(self, v): self.__statestack[-1]["font_stretching"] = v @property def font_family(self): return self.__statestack[-1]["font_family"] @font_family.setter def font_family(self, v): self.__statestack[-1]["font_family"] = v @property def font_size_pt(self): return self.__statestack[-1]["font_size_pt"] @font_size_pt.setter def font_size_pt(self, v): self.__statestack[-1]["font_size_pt"] = v @property def font_size(self): return self.__statestack[-1]["font_size_pt"] / self.k @font_size.setter def font_size(self, v): self.__statestack[-1]["font_size_pt"] = v * self.k @property def current_font(self): return self.__statestack[-1]["current_font"] @current_font.setter def current_font(self, v): self.__statestack[-1]["current_font"] = v @property def dash_pattern(self): return self.__statestack[-1]["dash_pattern"] @dash_pattern.setter def dash_pattern(self, v): self.__statestack[-1]["dash_pattern"] = v @property def line_width(self): return self.__statestack[-1]["line_width"] @line_width.setter def line_width(self, v): self.__statestack[-1]["line_width"] = v @property def text_mode(self): return self.__statestack[-1]["text_mode"] @text_mode.setter def text_mode(self, v): self.__statestack[-1]["text_mode"] = TextMode.coerce(v)
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/graphics_state.py
0.811489
0.22288
graphics_state.py
pypi
import types import warnings from copy import deepcopy from .errors import FPDFException class FPDFRecorder: """ The class is aimed to be used as wrapper around fpdf.FPDF: pdf = FPDF() recorder = FPDFRecorder(pdf) Its aim is dual: * allow to **rewind** to the state of the FPDF instance passed to its constructor, reverting all changes made to its internal state * allow to **replay** again all the methods calls performed on the recorder instance between its creation and the last call to rewind() Note that method can be called on a FPDFRecorder instance using its .pdf attribute so that they are not recorded & replayed later, on a call to .replay(). Note that using this class means to duplicate the FPDF `bytearray` buffer: when generating large PDFs, doubling memory usage may be troublesome. """ def __init__(self, pdf, accept_page_break=True): self.pdf = pdf self._initial = deepcopy(self.pdf.__dict__) self._calls = [] if not accept_page_break: self.accept_page_break = False def __getattr__(self, name): attr = getattr(self.pdf, name) if callable(attr): return CallRecorder(attr, self._calls) return attr def rewind(self): self.pdf.__dict__ = self._initial self._initial = deepcopy(self.pdf.__dict__) def replay(self): for call in self._calls: func, args, kwargs = call try: result = func(*args, **kwargs) if isinstance(result, types.GeneratorType): warnings.warn( "Detected usage of a context manager inside an unbreakable() section, which is not supported" ) # The results of other methods can also be invalidated: .pages_count, page_no(), get_x() / get_y(), will_page_break() except Exception as error: raise FPDFException( f"Failed to replay FPDF call: {func}(*{args}, **{kwargs})" ) from error self._calls = [] class CallRecorder: def __init__(self, func, calls): self._func = func self._calls = calls def __call__(self, *args, **kwargs): self._calls.append((self._func, args, kwargs)) return self._func(*args, **kwargs)
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/recorder.py
0.681515
0.23524
recorder.py
pypi
from typing import NamedTuple, Any, Union, Sequence from .errors import FPDFException SOFT_HYPHEN = "\u00ad" HYPHEN = "\u002d" SPACE = " " NEWLINE = "\n" class Fragment: def __init__(self, style: str, underlined: bool, characters: str = None): self.style = style self.underline = underlined self.characters = [] if characters is None else characters def __repr__(self): return f"Fragment(style={self.style}, underline={self.underline}, characters={self.characters})" @classmethod def from_string(cls, string: str, style: str, underlined: bool): return cls(style, underlined, list(string)) def trim(self, index: int): self.characters = self.characters[:index] @property def string(self): return "".join(self.characters) def __eq__(self, other: Any): return ( self.characters == other.characters and self.style == other.style and self.underline == other.underline ) class TextLine(NamedTuple): fragments: tuple text_width: float number_of_spaces_between_words: int justify: bool trailing_nl: bool class SpaceHint(NamedTuple): original_fragment_index: int original_character_index: int current_line_fragment_index: int current_line_character_index: int width: float number_of_spaces: int class HyphenHint(NamedTuple): original_fragment_index: int original_character_index: int current_line_fragment_index: int current_line_character_index: int width: float number_of_spaces: int character_to_append: str character_to_append_width: float character_to_append_style: str character_to_append_underline: bool class CurrentLine: def __init__(self, print_sh: bool = False): """ Per-line text fragment management for use by MultiLineBreak. Args: print_sh (bool): If true, a soft-hyphen will be rendered normally, instead of triggering a line break. Default: False """ self.print_sh = print_sh self.fragments = [] self.width = 0 self.number_of_spaces = 0 # automatic break hints # CurrentLine class remembers 3 positions # 1 - position of last inserted character. # class attributes (`width`, `fragments`) # is used for this purpose # 2 - position of last inserted space # SpaceHint is used fo this purpose. # 3 - position of last inserted soft-hyphen # HyphenHint is used fo this purpose. # The purpose of multiple positions tracking - to have an ability # to break in multiple places, depending on condition. self.space_break_hint = None self.hyphen_break_hint = None def add_character( self, character: str, character_width: float, style: str, underline: bool, original_fragment_index: int, original_character_index: int, ): assert character != NEWLINE if not self.fragments: self.fragments.append(Fragment(style, underline)) # characters are expected to be grouped into fragments by styles and # underline attributes. If the last existing fragment doesn't match # the (style, underline) of pending character -> # create a new fragment with matching (style, underline) elif ( style != self.fragments[-1].style or underline != self.fragments[-1].underline ): self.fragments.append(Fragment(style, underline)) active_fragment = self.fragments[-1] if character == SPACE: self.space_break_hint = SpaceHint( original_fragment_index, original_character_index, len(self.fragments), len(active_fragment.characters), self.width, self.number_of_spaces, ) self.number_of_spaces += 1 elif character == SOFT_HYPHEN and not self.print_sh: self.hyphen_break_hint = HyphenHint( original_fragment_index, original_character_index, len(self.fragments), len(active_fragment.characters), self.width, self.number_of_spaces, HYPHEN, character_width, style, underline, ) if character != SOFT_HYPHEN or self.print_sh: self.width += character_width active_fragment.characters.append(character) def _apply_automatic_hint(self, break_hint: Union[SpaceHint, HyphenHint]): """ This function mutates the current_line, applying one of the states observed in the past and stored in `hyphen_break_hint` or `space_break_hint` attributes. """ self.fragments = self.fragments[: break_hint.current_line_fragment_index] if self.fragments: self.fragments[-1].trim(break_hint.current_line_character_index) self.number_of_spaces = break_hint.number_of_spaces self.width = break_hint.width def manual_break(self, justify: bool = False, trailing_nl: bool = False): return TextLine( fragments=self.fragments, text_width=self.width, number_of_spaces_between_words=self.number_of_spaces, justify=(self.number_of_spaces > 0) and justify, trailing_nl=trailing_nl, ) def automatic_break_possible(self): return self.hyphen_break_hint is not None or self.space_break_hint is not None def automatic_break(self, justify: bool): assert self.automatic_break_possible() if self.hyphen_break_hint is not None and ( self.space_break_hint is None or self.hyphen_break_hint.width > self.space_break_hint.width ): self._apply_automatic_hint(self.hyphen_break_hint) self.add_character( self.hyphen_break_hint.character_to_append, self.hyphen_break_hint.character_to_append_width, self.hyphen_break_hint.character_to_append_style, self.hyphen_break_hint.character_to_append_underline, self.hyphen_break_hint.original_fragment_index, self.hyphen_break_hint.original_character_index, ) return ( self.hyphen_break_hint.original_fragment_index, self.hyphen_break_hint.original_character_index, self.manual_break(justify), ) self._apply_automatic_hint(self.space_break_hint) return ( self.space_break_hint.original_fragment_index, self.space_break_hint.original_character_index, self.manual_break(justify), ) class MultiLineBreak: def __init__( self, styled_text_fragments: Sequence, size_by_style: Sequence, justify: bool = False, print_sh: bool = False, ): self.styled_text_fragments = styled_text_fragments self.size_by_style = size_by_style self.justify = justify self.print_sh = print_sh self.fragment_index = 0 self.character_index = 0 self.char_index_for_last_forced_manual_break = None def _get_character_width(self, character: str, style: str = ""): if character == SOFT_HYPHEN and not self.print_sh: # HYPHEN is inserted instead of SOFT_HYPHEN character = HYPHEN return self.size_by_style(character, style) # pylint: disable=too-many-return-statements def get_line_of_given_width(self, maximum_width: float, wordsplit: bool = True): char_index_for_last_forced_manual_break = ( self.char_index_for_last_forced_manual_break ) self.char_index_for_last_forced_manual_break = None if self.fragment_index == len(self.styled_text_fragments): return None last_fragment_index = self.fragment_index last_character_index = self.character_index line_full = False current_line = CurrentLine(print_sh=self.print_sh) while self.fragment_index < len(self.styled_text_fragments): current_fragment = self.styled_text_fragments[self.fragment_index] if self.character_index >= len(current_fragment.characters): self.character_index = 0 self.fragment_index += 1 continue character = current_fragment.characters[self.character_index] character_width = self._get_character_width( character, current_fragment.style ) if character == NEWLINE: self.character_index += 1 return current_line.manual_break(trailing_nl=True) if current_line.width + character_width > maximum_width: if character == SPACE: self.character_index += 1 return current_line.manual_break(self.justify) if current_line.automatic_break_possible(): ( self.fragment_index, self.character_index, line, ) = current_line.automatic_break(self.justify) self.character_index += 1 return line if not wordsplit: line_full = True break if char_index_for_last_forced_manual_break == self.character_index: raise FPDFException( "Not enough horizontal space to render a single character" ) self.char_index_for_last_forced_manual_break = self.character_index return current_line.manual_break() current_line.add_character( character, character_width, current_fragment.style, current_fragment.underline, self.fragment_index, self.character_index, ) self.character_index += 1 if line_full and not wordsplit: # roll back and return empty line to trigger continuation # on the next line. self.fragment_index = last_fragment_index self.character_index = last_character_index return CurrentLine().manual_break(self.justify) if current_line.width: return current_line.manual_break()
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/line_break.py
0.919222
0.211722
line_break.py
pypi
from .enums import PageMode from .syntax import build_obj_dict, create_dictionary_string class ViewerPreferences: "Specifies the way the document shall be displayed on the screen" def __init__( self, hide_toolbar=False, hide_menubar=False, hide_window_u_i=False, fit_window=False, center_window=False, display_doc_title=False, non_full_screen_page_mode=PageMode.USE_NONE, ): self.hide_toolbar = hide_toolbar "A flag specifying whether to hide the conforming reader’s tool bars when the document is active" self.hide_menubar = hide_menubar "A flag specifying whether to hide the conforming reader’s menu bar when the document is active" self.hide_window_u_i = hide_window_u_i """ A flag specifying whether to hide user interface elements in the document’s window (such as scroll bars and navigation controls), leaving only the document’s contents displayed """ self.fit_window = fit_window "A flag specifying whether to resize the document’s window to fit the size of the first displayed page" self.center_window = center_window "A flag specifying whether to position the document’s window in the center of the screen" self.display_doc_title = display_doc_title """ A flag specifying whether the window’s title bar should display the document title taken from the Title entry of the document information dictionary. If false, the title bar should instead display the name of the PDF file containing the document. """ self.non_full_screen_page_mode = PageMode.coerce(non_full_screen_page_mode) if self.non_full_screen_page_mode in ( PageMode.FULL_SCREEN, PageMode.USE_ATTACHMENTS, ): raise ValueError( f"{self.non_full_screen_page_mode} is not a support value for NonFullScreenPageMode" ) @property def non_full_screen_page_mode(self): "(`fpdf.enums.PageMode`) The document’s page mode, specifying how to display the document on exiting full-screen mode" return self._non_full_screen_page_mode @non_full_screen_page_mode.setter def non_full_screen_page_mode(self, page_mode): self._non_full_screen_page_mode = PageMode.coerce(page_mode) def serialize(self): obj_dict = build_obj_dict({key: getattr(self, key) for key in dir(self)}) return create_dictionary_string(obj_dict)
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/prefs.py
0.812682
0.153994
prefs.py
pypi
from enum import Enum, IntEnum from sys import intern from .syntax import Name class DocumentState(IntEnum): UNINITIALIZED = 0 READY = 1 # page not started yet GENERATING_PAGE = 2 CLOSED = 3 # EOF printed class SignatureFlag(IntEnum): SIGNATURES_EXIST = 1 "If set, the document contains at least one signature field." APPEND_ONLY = 2 """ If set, the document contains signatures that may be invalidated if the file is saved (written) in a way that alters its previous contents, as opposed to an incremental update. """ class CoerciveEnum(Enum): """ An enumeration that provides a helper to coerce strings into enumeration members. """ @classmethod def coerce(cls, value): """ Attempt to coerce `value` into a member of this enumeration. If value is already a member of this enumeration it is returned unchanged. Otherwise, if it is a string, attempt to convert it as an enumeration value. If that fails, attempt to convert it (case insensitively, by upcasing) as an enumeration name. If all different conversion attempts fail, an exception is raised. Args: value (Enum, str): the value to be coerced. Raises: ValueError: if `value` is a string but neither a member by name nor value. TypeError: if `value`'s type is neither a member of the enumeration nor a string. """ if isinstance(value, cls): return value if isinstance(value, str): try: return cls(value) except ValueError: pass try: return cls[value.upper()] except KeyError: pass raise ValueError(f"{value} is not a valid {cls.__name__}") raise TypeError(f"{value} cannot convert to a {cls.__name__}") class CoerciveIntEnum(IntEnum): """ An enumeration that provides a helper to coerce strings and integers into enumeration members. """ @classmethod def coerce(cls, value): """ Attempt to coerce `value` into a member of this enumeration. If value is already a member of this enumeration it is returned unchanged. Otherwise, if it is a string, attempt to convert it (case insensitively, by upcasing) as an enumeration name. Otherwise, if it is an int, attempt to convert it as an enumeration value. Otherwise, an exception is raised. Args: value (IntEnum, str, int): the value to be coerced. Raises: ValueError: if `value` is an int but not a member of this enumeration. ValueError: if `value` is a string but not a member by name. TypeError: if `value`'s type is neither a member of the enumeration nor an int or a string. """ if isinstance(value, cls): return value if isinstance(value, str): try: return cls[value.upper()] except KeyError: raise ValueError(f"{value} is not a valid {cls.__name__}") from None if isinstance(value, int): return cls(value) raise TypeError(f"{value} cannot convert to a {cls.__name__}") class Align(CoerciveEnum): "Defines how to render text in a cell" C = intern("CENTER") "Center text horizontally" X = intern("X_CENTER") "Center text horizontally around current x position" L = intern("LEFT") "Left-align text" R = intern("RIGHT") "Right-align text" J = intern("JUSTIFY") "Justify text" @classmethod def coerce(cls, value): if value == "": return cls.L return super(cls, cls).coerce(value) class RenderStyle(CoerciveEnum): "Defines how to render shapes" D = intern("DRAW") """ Draw lines. Line color can be controlled with `fpdf.fpdf.FPDF.set_draw_color()`. Line thickness can be controlled with `fpdf.fpdf.FPDF.set_line_width()`. """ F = intern("FILL") """ Fill areas. Filling color can be controlled with `fpdf.fpdf.FPDF.set_fill_color()`. """ DF = intern("DRAW_FILL") "Draw lines and fill areas" @property def operator(self): return {self.D: "S", self.F: "f", self.DF: "B"}[self] @property def is_draw(self): return self in (self.D, self.DF) @property def is_fill(self): return self in (self.F, self.DF) @classmethod def coerce(cls, value): if not value: return cls.D if value == "FD": value = "DF" return super(cls, cls).coerce(value) class TextMode(CoerciveIntEnum): "Values described in PDF spec section 'Text Rendering Mode'" FILL = 0 STROKE = 1 FILL_STROKE = 2 INVISIBLE = 3 FILL_CLIP = 4 STROKE_CLIP = 5 FILL_STROKE_CLIP = 6 CLIP = 7 class XPos(CoerciveEnum): "Positional values in horizontal direction for use after printing text." LEFT = intern("LEFT") # self.x "left end of the cell" RIGHT = intern("RIGHT") # self.x + w "right end of the cell (default)" START = intern("START") "left start of actual text" END = intern("END") "right end of actual text" WCONT = intern("WCONT") "for write() to continue next (slightly left of END)" CENTER = intern("CENTER") "center of actual text" LMARGIN = intern("LMARGIN") # self.l_margin "left page margin (start of printable area)" RMARGIN = intern("RMARGIN") # self.w - self.r_margin "right page margin (end of printable area)" class YPos(CoerciveEnum): "Positional values in vertical direction for use after printing text" TOP = intern("TOP") # self.y "top of the first line (default)" LAST = intern("LAST") "top of the last line (same as TOP for single-line text)" NEXT = intern("NEXT") # LAST + h "top of next line (bottom of current text)" TMARGIN = intern("TMARGIN") # self.t_margin "top page margin (start of printable area)" BMARGIN = intern("BMARGIN") # self.h - self.b_margin "bottom page margin (end of printable area)" class PageLayout(CoerciveEnum): "Specify the page layout shall be used when the document is opened" SINGLE_PAGE = Name("SinglePage") "Display one page at a time" ONE_COLUMN = Name("OneColumn") "Display the pages in one column" TWO_COLUMN_LEFT = Name("TwoColumnLeft") "Display the pages in two columns, with odd-numbered pages on the left" TWO_COLUMN_RIGHT = Name("TwoColumnRight") "Display the pages in two columns, with odd-numbered pages on the right" TWO_PAGE_LEFT = Name("TwoPageLeft") "Display the pages two at a time, with odd-numbered pages on the left" TWO_PAGE_RIGHT = Name("TwoPageRight") "Display the pages two at a time, with odd-numbered pages on the right" class PageMode(CoerciveEnum): "Specifying how to display the document on exiting full-screen mode" USE_NONE = Name("UseNone") "Neither document outline nor thumbnail images visible" USE_OUTLINES = Name("UseOutlines") "Document outline visible" USE_THUMBS = Name("UseThumbs") "Thumbnail images visible" FULL_SCREEN = Name("FullScreen") "Full-screen mode, with no menu bar, window controls, or any other window visible" USE_OC = Name("UseOC") "Optional content group panel visible" USE_ATTACHMENTS = Name("UseAttachments") "Attachments panel visible" class TextMarkupType(CoerciveEnum): "Subtype of a text markup annotation" HIGHLIGHT = Name("Highlight") UNDERLINE = Name("Underline") SQUIGGLY = Name("Squiggly") STRIKE_OUT = Name("StrikeOut") class BlendMode(CoerciveEnum): """ An enumeration of the named standard named blend functions supported by PDF. """ NORMAL = Name("Normal") '''"Selects the source color, ignoring the backdrop."''' MULTIPLY = Name("Multiply") '''"Multiplies the backdrop and source color values."''' SCREEN = Name("Screen") """ "Multiplies the complements of the backdrop and source color values, then complements the result." """ OVERLAY = Name("Overlay") """ "Multiplies or screens the colors, depending on the backdrop color value. Source colors overlay the backdrop while preserving its highlights and shadows. The backdrop color is not replaced but is mixed with the source color to reflect the lightness or darkness of the backdrop." """ DARKEN = Name("Darken") '''"Selects the darker of the backdrop and source colors."''' LIGHTEN = Name("Lighten") '''"Selects the lighter of the backdrop and source colors."''' COLOR_DODGE = Name("ColorDodge") """ "Brightens the backdrop color to reflect the source color. Painting with black produces no changes." """ COLOR_BURN = Name("ColorBurn") """ "Darkens the backdrop color to reflect the source color. Painting with white produces no change." """ HARD_LIGHT = Name("HardLight") """ "Multiplies or screens the colors, depending on the source color value. The effect is similar to shining a harsh spotlight on the backdrop." """ SOFT_LIGHT = Name("SoftLight") """ "Darkens or lightens the colors, depending on the source color value. The effect is similar to shining a diffused spotlight on the backdrop." """ DIFFERENCE = Name("Difference") '''"Subtracts the darker of the two constituent colors from the lighter color."''' EXCLUSION = Name("Exclusion") """ "Produces an effect similar to that of the Difference mode but lower in contrast. Painting with white inverts the backdrop color; painting with black produces no change." """ HUE = Name("Hue") """ "Creates a color with the hue of the source color and the saturation and luminosity of the backdrop color." """ SATURATION = Name("Saturation") """ "Creates a color with the saturation of the source color and the hue and luminosity of the backdrop color. Painting with this mode in an area of the backdrop that is a pure gray (no saturation) produces no change." """ COLOR = Name("Color") """ "Creates a color with the hue and saturation of the source color and the luminosity of the backdrop color. This preserves the gray levels of the backdrop and is useful for coloring monochrome images or tinting color images." """ LUMINOSITY = Name("Luminosity") """ "Creates a color with the luminosity of the source color and the hue and saturation of the backdrop color. This produces an inverse effect to that of the Color mode." """ class AnnotationFlag(CoerciveIntEnum): INVISIBLE = 1 """ If set, do not display the annotation if it does not belong to one of the standard annotation types and no annotation handler is available. """ HIDDEN = 2 "If set, do not display or print the annotation or allow it to interact with the user" PRINT = 4 "If set, print the annotation when the page is printed." NO_ZOOM = 8 "If set, do not scale the annotation’s appearance to match the magnification of the page." NO_ROTATE = 16 "If set, do not rotate the annotation’s appearance to match the rotation of the page." NO_VIEW = 32 "If set, do not display the annotation on the screen or allow it to interact with the user" READ_ONLY = 64 """ If set, do not allow the annotation to interact with the user. The annotation may be displayed or printed but should not respond to mouse clicks. """ LOCKED = 128 """ If set, do not allow the annotation to be deleted or its properties (including position and size) to be modified by the user. """ TOGGLE_NO_VIEW = 256 "If set, invert the interpretation of the NoView flag for certain events." LOCKED_CONTENTS = 512 "If set, do not allow the contents of the annotation to be modified by the user." class AnnotationName(CoerciveEnum): "The name of an icon that shall be used in displaying the annotation" NOTE = Name("Note") COMMENT = Name("Comment") HELP = Name("Help") PARAGRAPH = Name("Paragraph") NEW_PARAGRAPH = Name("NewParagraph") INSERT = Name("Insert") class IntersectionRule(CoerciveEnum): """ An enumeration representing the two possible PDF intersection rules. The intersection rule is used by the renderer to determine which points are considered to be inside the path and which points are outside the path. This primarily affects fill rendering and clipping paths. """ NONZERO = "nonzero" """ "The nonzero winding number rule determines whether a given point is inside a path by conceptually drawing a ray from that point to infinity in any direction and then examining the places where a segment of the path crosses the ray. Starting with a count of 0, the rule adds 1 each time a path segment crosses the ray from left to right and subtracts 1 each time a segment crosses from right to left. After counting all the crossings, if the result is 0, the point is outside the path; otherwise, it is inside." """ EVENODD = "evenodd" """ "An alternative to the nonzero winding number rule is the even-odd rule. This rule determines whether a point is inside a path by drawing a ray from that point in any direction and simply counting the number of path segments that cross the ray, regardless of direction. If this number is odd, the point is inside; if even, the point is outside. This yields the same results as the nonzero winding number rule for paths with simple shapes, but produces different results for more complex shapes." """ class PathPaintRule(CoerciveEnum): """ An enumeration of the PDF drawing directives that determine how the renderer should paint a given path. """ # the auto-close paint rules are omitted here because it's easier to just emit # close operators when appropriate, programmatically STROKE = "S" '''"Stroke the path."''' FILL_NONZERO = "f" """ "Fill the path, using the nonzero winding number rule to determine the region to fill. Any subpaths that are open are implicitly closed before being filled." """ FILL_EVENODD = "f*" """ "Fill the path, using the even-odd rule to determine the region to fill. Any subpaths that are open are implicitly closed before being filled." """ STROKE_FILL_NONZERO = "B" """ "Fill and then stroke the path, using the nonzero winding number rule to determine the region to fill. This operator produces the same result as constructing two identical path objects, painting the first with `FILL_NONZERO` and the second with `STROKE`." """ STROKE_FILL_EVENODD = "B*" """ "Fill and then stroke the path, using the even-odd rule to determine the region to fill. This operator produces the same result as `STROKE_FILL_NONZERO`, except that the path is filled as if with `FILL_EVENODD` instead of `FILL_NONZERO`." """ DONT_PAINT = "n" """ "End the path object without filling or stroking it. This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path." """ AUTO = "auto" """ Automatically determine which `PathPaintRule` should be used. PaintedPath will select one of the above `PathPaintRule`s based on the resolved set/inherited values of its style property. """ class ClippingPathIntersectionRule(CoerciveEnum): """ An enumeration of the PDF drawing directives that define a path as a clipping path. """ NONZERO = "W" """ "The nonzero winding number rule determines whether a given point is inside a path by conceptually drawing a ray from that point to infinity in any direction and then examining the places where a segment of the path crosses the ray. Starting with a count of 0, the rule adds 1 each time a path segment crosses the ray from left to right and subtracts 1 each time a segment crosses from right to left. After counting all the crossings, if the result is 0, the point is outside the path; otherwise, it is inside." """ EVENODD = "W*" """ "An alternative to the nonzero winding number rule is the even-odd rule. This rule determines whether a point is inside a path by drawing a ray from that point in any direction and simply counting the number of path segments that cross the ray, regardless of direction. If this number is odd, the point is inside; if even, the point is outside. This yields the same results as the nonzero winding number rule for paths with simple shapes, but produces different results for more complex shapes.""" class StrokeCapStyle(CoerciveIntEnum): """ An enumeration of values defining how the end of a stroke should be rendered. This affects the ends of the segments of dashed strokes, as well. """ BUTT = 0 """ "The stroke is squared off at the endpoint of the path. There is no projection beyond the end of the path." """ ROUND = 1 """ "A semicircular arc with a diameter equal to the line width is drawn around the endpoint and filled in." """ SQUARE = 2 """ "The stroke continues beyond the endpoint of the path for a distance equal to half the line width and is squared off." """ class StrokeJoinStyle(CoerciveIntEnum): """ An enumeration of values defining how the corner joining two path components should be rendered. """ MITER = 0 """ "The outer edges of the strokes for the two segments are extended until they meet at an angle, as in a picture frame. If the segments meet at too sharp an angle (as defined by the miter limit parameter), a bevel join is used instead." """ ROUND = 1 """ "An arc of a circle with a diameter equal to the line width is drawn around the point where the two segments meet, connecting the outer edges of the strokes for the two segments. This pieslice-shaped figure is filled in, pro- ducing a rounded corner." """ BEVEL = 2 """ "The two segments are finished with butt caps and the resulting notch beyond the ends of the segments is filled with a triangle." """ class PDFStyleKeys(Enum): """ An enumeration of the graphics state parameter dictionary keys. """ FILL_ALPHA = Name("ca") BLEND_MODE = Name("BM") # shared between stroke and fill STROKE_ALPHA = Name("CA") STROKE_ADJUSTMENT = Name("SA") STROKE_WIDTH = Name("LW") STROKE_CAP_STYLE = Name("LC") STROKE_JOIN_STYLE = Name("LJ") STROKE_MITER_LIMIT = Name("ML") STROKE_DASH_PATTERN = Name("D") # array of array, number, e.g. [[1 1] 0] class Corner(CoerciveEnum): TOP_RIGHT = "TOP_RIGHT" TOP_LEFT = "TOP_LEFT" BOTTOM_RIGHT = "BOTTOM_RIGHT" BOTTOM_LEFT = "BOTTOM_LEFT" # This enum is only used internally: __pdoc__ = {"DocumentState": False}
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/enums.py
0.715126
0.345133
enums.py
pypi
from abc import ABC import warnings from .util import enclose_in_parens from .syntax import build_obj_dict, create_dictionary_string class Action(ABC): def __init__(self, next_action=None): """ Args: next (PDFObject | str): optional reference to another Action to trigger after this one """ self.next = next_action def dict_as_string(self, key_values=None): if key_values is None: key_values = {} if self.next: key_values["Next"] = self.next obj_dict = build_obj_dict(key_values) return create_dictionary_string(obj_dict, field_join=" ") class NamedAction(Action): def __init__(self, action_name, next_action=None): super().__init__(next) if action_name not in ("NextPage", "PrevPage", "FirstPage", "LastPage"): warnings.warn("Non-standard named action added") self.action_name = action_name def dict_as_string(self): return super().dict_as_string({"S": "/Named", "N": f"/{self.action_name}"}) class GoToAction(Action): "As of 2022, this does not seem honored by neither Adobe Acrobat nor Sumatra readers." def __init__(self, dest, next_action=None): super().__init__(next_action) self.dest = dest def dict_as_string(self): return super().dict_as_string({"S": "/GoTo", "D": self.dest}) class GoToRemoteAction(Action): def __init__(self, file, dest, next_action=None): super().__init__(next_action) self.file = file self.dest = dest def dict_as_string(self): return super().dict_as_string( {"S": "/GoToR", "F": enclose_in_parens(self.file), "D": self.dest} ) class LaunchAction(Action): "As of 2022, this does not seem honored by neither Adobe Acrobat nor Sumatra readers." def __init__(self, file, next_action=None): super().__init__(next_action) self.file = file def dict_as_string(self): return super().dict_as_string( {"S": "/Launch", "F": enclose_in_parens(self.file)} ) # Annotation & actions that we tested implementing, # but that revealed not be worth the effort: # * Popup annotation & Hide action: as of june 2021, # do not seem support neither by Adobe Acrobat nor by Sumatra. # Moreover, they both use to indirect reference annotations, # and hence implementing them would need some consequent refactoring, # as annotations are currently defined "inline", not as dedicated PDF objects.
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/actions.py
0.708616
0.198433
actions.py
pypi
from collections import defaultdict from typing import NamedTuple, List, Optional, Union from .syntax import PDFObject, PDFString, PDFArray # pylint: disable=inherit-non-class,unsubscriptable-object class MarkedContent(NamedTuple): page_object_id: int # refers to the first page displaying this marked content struct_parents_id: int struct_type: str mcid: Optional[int] = None title: Optional[str] = None alt_text: Optional[str] = None class NumberTree(PDFObject): """A number tree is similar to a name tree, except that its keys are integers instead of strings and are sorted in ascending numerical order. A name tree serves a similar purpose to a dictionary—associating keys and values—but by different means. The values associated with the keys may be objects of any type. Stream objects are required to be specified by indirect object references. It is recommended, though not required, that dictionary, array, and string objects be specified by indirect object references, and other PDF objects (nulls, numbers, booleans, and names) be specified as direct objects """ __slots__ = ("_id", "nums") def __init__(self, **kwargs): super().__init__(**kwargs) self.nums = defaultdict(list) # {struct_parent_id -> struct_elems} def serialize(self, fpdf=None, obj_dict=None): newline = "\n" serialized_nums = "\n".join( f"{struct_parent_id} [{newline.join(struct_elem.ref for struct_elem in struct_elems)}]" for struct_parent_id, struct_elems in self.nums.items() ) return super().serialize(fpdf, {"/Nums": f"[{serialized_nums}]"}) class StructTreeRoot(PDFObject): __slots__ = ("_id", "type", "parent_tree", "k") def __init__(self, **kwargs): super().__init__(**kwargs) self.type = "/StructTreeRoot" # A number tree used in finding the structure elements to which content items belong: self.parent_tree = NumberTree() # The immediate child or children of the structure tree root in the structure hierarchy: self.k = PDFArray() class StructElem(PDFObject): # The main reason to use __slots__ in PDFObject child classes is to save up some memory # when very many instances of this class are created. __slots__ = ("_id", "type", "s", "p", "k", "pg", "t", "alt") def __init__( self, struct_type: str, parent: PDFObject, kids: Union[List[int], List["StructElem"]], page: PDFObject = None, title: str = None, alt: str = None, **kwargs, ): super().__init__(**kwargs) self.type = "/StructElem" self.s = ( struct_type # a name object identifying the nature of the structure element ) self.p = parent # The structure element that is the immediate parent of this one in the structure hierarchy self.k = PDFArray(kids) # The children of this structure element self.pg = page # A page object on which some or all of the content items designated by the K entry are rendered self.t = ( None if title is None else PDFString(title) ) # a text string representing it in human-readable form self.alt = ( None if alt is None else PDFString(alt) ) # An alternate description of the structure element in human-readable form class StructureTreeBuilder: def __init__(self): """ Args: marked_contents (tuple): list of MarkedContent """ self.struct_tree_root = StructTreeRoot() self.doc_struct_elem = StructElem( struct_type="/Document", parent=self.struct_tree_root, kids=[] ) self.struct_tree_root.k.append(self.doc_struct_elem) self.struct_elem_per_mc = {} def add_marked_content(self, marked_content): page = PDFObject(marked_content.page_object_id) struct_elem = StructElem( struct_type=marked_content.struct_type, parent=self.doc_struct_elem, kids=[] if marked_content.mcid is None else [marked_content.mcid], page=page, title=marked_content.title, alt=marked_content.alt_text, ) self.struct_elem_per_mc[marked_content] = struct_elem self.doc_struct_elem.k.append(struct_elem) self.struct_tree_root.parent_tree.nums[marked_content.struct_parents_id].append( struct_elem ) def next_mcid_for_page(self, page_object_id): return sum( 1 for mc in self.struct_elem_per_mc if mc.page_object_id == page_object_id ) def empty(self): return not self.struct_elem_per_mc def serialize(self, first_object_id=1, fpdf=None): """ Assign object IDs & output the whole hierarchy tree serialized as a multi-lines string in PDF syntax, ready to be embedded. Objects ID assignement will start with the provided first ID, that will be assigned to the StructTreeRoot. Apart from that, assignement is made in an arbitrary order. All PDF objects must have assigned IDs before proceeding to output generation though, as they have many references to each others. If a FPDF instance provided, its `_newobj` & `_out` methods will be called and this method output will be meaningless. """ self.assign_ids(first_object_id) output = [] output.append(self.struct_tree_root.serialize(fpdf)) output.append(self.doc_struct_elem.serialize(fpdf)) output.append(self.struct_tree_root.parent_tree.serialize(fpdf)) for struct_elem in self.doc_struct_elem.k: output.append(struct_elem.serialize(fpdf)) return "\n".join(output) def assign_ids(self, n): self.struct_tree_root.id = n n += 1 self.doc_struct_elem.id = n n += 1 self.struct_tree_root.parent_tree.id = n n += 1 for struct_elem in self.doc_struct_elem.k: struct_elem.id = n n += 1 return n
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/structure_tree.py
0.880399
0.337599
structure_tree.py
pypi
"Document signature generation" import hashlib from datetime import timezone from unittest.mock import patch from .syntax import build_obj_dict from .syntax import create_dictionary_string class Signature: def __init__(self, contact_info=None, location=None, m=None, reason=None): self.type = "/Sig" self.filter = "/Adobe.PPKLite" self.sub_filter = "/adbe.pkcs7.detached" self.contact_info = contact_info "Information provided by the signer to enable a recipient to contact the signer to verify the signature" self.location = location "The CPU host name or physical location of the signing" self.m = m "The time of signing" self.reason = reason "The reason for the signing" self.byte_range = _SIGNATURE_BYTERANGE_PLACEHOLDER self.contents = "<" + _SIGNATURE_CONTENTS_PLACEHOLDER + ">" def serialize(self): obj_dict = build_obj_dict({key: getattr(self, key) for key in dir(self)}) return create_dictionary_string(obj_dict) def sign_content(signer, buffer, key, cert, extra_certs, hashalgo, sign_time): "Perform PDF signing based on the content of the buffer, performing substitutions on it." # We start by substituting the ByteRange, # that defines which part of the document content the signature is based on. # This is basically ALL the content EXCEPT the signature content itself. sig_placeholder = _SIGNATURE_CONTENTS_PLACEHOLDER.encode("latin1") start_index = buffer.find(sig_placeholder) end_index = start_index + len(sig_placeholder) content_range = (0, start_index - 1, end_index + 1, len(buffer) - end_index - 1) br_placeholder = _SIGNATURE_BYTERANGE_PLACEHOLDER.encode() byte_range = b"[%010d %010d %010d %010d]" % content_range # Sanity check, otherwise we will break the xref table: assert len(br_placeholder) == len(byte_range) buffer = buffer.replace(br_placeholder, byte_range, 1) # We compute the ByteRange hash, of everything before & after the placeholder: content_hash = hashlib.new(hashalgo) content_hash.update(buffer[: content_range[1]]) # before content_hash.update(buffer[content_range[2] :]) # after # This monkey-patching is needed, at the time of endesive v2.0.9, # to get control over signed_time, initialized by endesive.signer.sign() to be datetime.now(): class mock_datetime: @staticmethod def now(tz): # pylint: disable=unused-argument return sign_time.astimezone(timezone.utc) sign = patch("endesive.signer.datetime", mock_datetime)(signer.sign) contents = sign( datau=None, key=key, cert=cert, othercerts=extra_certs, hashalgo=hashalgo, attrs=True, signed_value=content_hash.digest(), ) contents = _pkcs11_aligned(contents).encode("latin1") # Sanity check, otherwise we will break the xref table: assert len(sig_placeholder) == len(contents) return buffer.replace(sig_placeholder, contents, 1) def _pkcs11_aligned(data): data = "".join(f"{i:02x}" for i in data) return data + "0" * (0x4000 - len(data)) _SIGNATURE_BYTERANGE_PLACEHOLDER = "[0000000000 0000000000 0000000000 0000000000]" _SIGNATURE_CONTENTS_PLACEHOLDER = _pkcs11_aligned((0,))
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/sign.py
0.636805
0.26236
sign.py
pypi
from abc import ABC class Transition(ABC): def dict_as_string(self): raise NotImplementedError class SplitTransition(Transition): def __init__(self, dimension, direction): if dimension not in ("H", "V"): raise ValueError( f"Unsupported dimension '{dimension}', must be H(horizontal) or V(ertical)" ) self.dimension = dimension if direction not in ("I", "O"): raise ValueError( f"Unsupported direction '{direction}', must be I(nward) or O(utward)" ) self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Split /DM /{self.dimension} /M /{self.direction}>>" class BlindsTransition(Transition): def __init__(self, dimension): if dimension not in ("H", "V"): raise ValueError( f"Unsupported dimension '{dimension}', must be H(horizontal) or V(ertical)" ) self.dimension = dimension def dict_as_string(self): return f"<</Type /Trans /S /Blinds /DM /{self.dimension}>>" class BoxTransition(Transition): def __init__(self, direction): if direction not in ("I", "O"): raise ValueError( f"Unsupported direction '{direction}', must be I(nward) or O(utward)" ) self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Blinds /M /{self.direction}>>" class WipeTransition(Transition): def __init__(self, direction): if direction not in (0, 90, 180, 270): raise ValueError( f"Unsupported direction '{direction}', must 0, 90, 180 or 270" ) self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Wipe /Di /{self.direction}>>" class DissolveTransition(Transition): def dict_as_string(self): return "<</Type /Trans /S /Dissolve>>" class GlitterTransition(Transition): def __init__(self, direction): if direction not in (0, 270, 315): raise ValueError(f"Unsupported direction '{direction}', must 0, 270 or 315") self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Glitter /Di /{self.direction}>>" class FlyTransition(Transition): def __init__(self, dimension, direction=None): if dimension not in ("H", "V"): raise ValueError( f"Unsupported dimension '{dimension}', must be H(horizontal) or V(ertical)" ) self.dimension = dimension if direction not in (0, 270, None): raise ValueError( f"Unsupported direction '{direction}', must 0, 270 or None" ) self.direction = direction def dict_as_string(self): return ( f"<</Type /Trans /S /Glitter /M /{self.dimension} /Di /{self.direction}>>" ) class PushTransition(Transition): def __init__(self, direction): if direction not in (0, 270): raise ValueError(f"Unsupported direction '{direction}', must 0 or 270") self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Push /Di /{self.direction}>>" class CoverTransition(Transition): def __init__(self, direction): if direction not in (0, 270): raise ValueError(f"Unsupported direction '{direction}', must 0 or 270") self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Cover /Di /{self.direction}>>" class UncoverTransition(Transition): def __init__(self, direction): if direction not in (0, 270): raise ValueError(f"Unsupported direction '{direction}', must 0 or 270") self.direction = direction def dict_as_string(self): return f"<</Type /Trans /S /Uncover /Di /{self.direction}>>" class FadeTransition(Transition): def dict_as_string(self): return "<</Type /Fade /S /Dissolve>>"
/reportbro-fpdf2-0.9.1.tar.gz/reportbro-fpdf2-0.9.1/fpdf/transitions.py
0.866528
0.25093
transitions.py
pypi
import json from typing import Optional from .enums import * from .errors import Error, ReportBroInternalError from .utils import get_float_value, get_int_value class Color: def __init__(self, color): self.color_code = '' if color: valid = False if isinstance(color, str) and len(color) == 7 and color[0] == '#': try: self.r = int(color[1:3], 16) self.g = int(color[3:5], 16) self.b = int(color[5:7], 16) self.transparent = False self.color_code = color valid = True except ValueError: pass if not valid: raise ReportBroInternalError(f'Invalid color value {color}', log_error=False) else: self.r = 0 self.g = 0 self.b = 0 self.transparent = True self.color_code = '' def __eq__(self, other): if isinstance(other, Color): return self.color_code == other.color_code return False def is_black(self): return self.r == 0 and self.g == 0 and self.b == 0 and not self.transparent class Parameter: def __init__(self, report, data, init_test_data=False): self.report = report self.id = int(data.get('id')) self.name = data.get('name', '<unnamed>') self.type = ParameterType[data.get('type')] if self.type == ParameterType.simple_array: self.array_item_type = ParameterType[data.get('arrayItemType')] else: self.array_item_type = ParameterType.none self.eval = bool(data.get('eval')) self.nullable = bool(data.get('nullable')) self.expression = data.get('expression', '') self.pattern = data.get('pattern', '') self.pattern_has_currency = (self.pattern.find('$') != -1) self.is_internal = self.name in ('page_count', 'page_number', 'row_number') self.test_data = None self.test_data_boolean = None self.test_data_image = None if init_test_data: self.test_data = data.get('testData') self.test_data_boolean = data.get('testDataBoolean') self.test_data_image = data.get('testDataImage') self.range_stack = [] self.children = [] self.show_only_name_type = bool(data.get('showOnlyNameType')) self.fields = dict() if self.type == ParameterType.array or self.type == ParameterType.map: for item in data.get('children'): parameter = Parameter(self.report, item) if parameter.name in self.fields: self.report.errors.append( Error('errorMsgDuplicateParameterField', object_id=parameter.id, field='name')) else: self.children.append(parameter) self.fields[parameter.name] = parameter def is_evaluated(self): """Return True if parameter data must be evaluated initially.""" return self.eval or self.is_range_function() def is_range_function(self): """Return True if parameter is a function with range input.""" return self.type in (ParameterType.average, ParameterType.sum) def set_range(self, row_start, row_end): """ Set row range which is used for parameter functions (e.g. sum/avg), if a range is set then only these rows will be used for the function, otherwise all rows are used. :param row_start: first row of group :param row_end: index after last row of group """ self.range_stack.append((row_start, row_end)) def clear_range(self): """Clear previously set row range.""" self.range_stack.pop() def get_range(self): if self.range_stack: return self.range_stack[-1] return None, None def has_range(self): return bool(self.range_stack) def get_test_data(self) -> Optional[dict]: """ Extract test data from test data value of parameters. Supports test data saved in ReportBro Designer version >= 3.0. The method is ported from the ReportBro Designer method ReportBro.getTestData This is used for ReportBro tests where data is extracted from parameter test data saved within the report template. """ test_data = None try: test_data = json.loads(self.test_data) except json.JSONDecodeError: pass if self.type == ParameterType.array or self.type == ParameterType.simple_array or\ self.type == ParameterType.map: if test_data: return self.get_parameter_test_data(self, test_data) return None @staticmethod def get_parameter_test_data(parameter, test_data): """ Get test data from parameter. The method is ported from the ReportBro Designer method Parameter.getSanitizedTestData :param parameter: parameter must be of type map, simple_array or array. :param test_data: test data for parameter, must be a dict for parameter type map and a list otherwise. :return: test data in a dict for parameter type map and list otherwise. """ if parameter.type == ParameterType.map: if not isinstance(test_data, dict): test_data = {} rv = Parameter.get_parameter_test_data_map(parameter, test_data) elif parameter.type == ParameterType.simple_array: rv = Parameter.get_parameter_test_data_simple_array(test_data) elif parameter.type == ParameterType.array: if not isinstance(test_data, list): test_data = [] rv = [] for test_data_row in test_data: if parameter.type == ParameterType.array: if not isinstance(test_data_row, dict): test_data_row = {} rv.append(Parameter.get_parameter_test_data_map(parameter, test_data_row)) else: assert False return rv @staticmethod def get_parameter_test_data_map(parameter, test_data): """ The method is ported from the ReportBro Designer method Parameter.getSanitizedTestDataMap """ rv = {} for field in parameter.children: if field.show_only_name_type: continue value = test_data[field.name] if (field.name in test_data) else None if field.type == ParameterType.array or field.type == ParameterType.map: rv[field.name] = Parameter.get_parameter_test_data(field, value) elif field.type == ParameterType.simple_array: rv[field.name] = Parameter.get_parameter_test_data_simple_array(value) elif field.type == ParameterType.image: if isinstance(value, dict) and 'data' in value: rv[field.name] = value['data'] else: rv[field.name] = '' else: rv[field.name] = value return rv @staticmethod def get_parameter_test_data_simple_array(test_data): """ The method is ported from the ReportBro Designer method Parameter.getSanitizedTestDataSimpleArray """ test_data_rows = test_data if not isinstance(test_data_rows, list): test_data_rows = [] array_values = [] for test_data_row in test_data_rows: if isinstance(test_data_row, dict) and 'data' in test_data_row: array_values.append(test_data_row['data']) return array_values class BorderStyle: def __init__(self, data, key_prefix=''): self.border_color = Color(data.get(key_prefix + 'borderColor')) self.border_width = get_float_value(data, key_prefix + 'borderWidth') self.border_all = bool(data.get(key_prefix + 'borderAll')) self.border_left = self.border_all or bool(data.get(key_prefix + 'borderLeft')) self.border_top = self.border_all or bool(data.get(key_prefix + 'borderTop')) self.border_right = self.border_all or bool(data.get(key_prefix + 'borderRight')) self.border_bottom = self.border_all or bool(data.get(key_prefix + 'borderBottom')) class TextStyle(BorderStyle): def __init__(self, data, key_prefix='', id_suffix=''): """ :param data: dict containing text style values :param key_prefix: optional prefix to access data values. this is used for conditional style values where the values are stored within an element. The conditional style value keys contain a prefix to distinguish them from the standard style values. :param id_suffix: if set then the id_suffix is appended to the id. this is used for (conditional) styles stored within an element to avoid id collision with an existing style. """ BorderStyle.__init__(self, data, key_prefix) self.key_prefix = key_prefix self.id = str(get_int_value(data, 'id')) if id_suffix: self.id += id_suffix self.bold = bool(data.get(key_prefix + 'bold')) self.italic = bool(data.get(key_prefix + 'italic')) self.underline = bool(data.get(key_prefix + 'underline')) self.strikethrough = bool(data.get(key_prefix + 'strikethrough')) self.horizontal_alignment = HorizontalAlignment[data.get(key_prefix + 'horizontalAlignment')] self.vertical_alignment = VerticalAlignment[data.get(key_prefix + 'verticalAlignment')] self.text_color = Color(data.get(key_prefix + 'textColor')) self.background_color = Color(data.get(key_prefix + 'backgroundColor')) self.font = data.get(key_prefix + 'font') self.font_size = get_int_value(data, key_prefix + 'fontSize') self.line_spacing = get_float_value(data, key_prefix + 'lineSpacing') self.padding_left = get_int_value(data, key_prefix + 'paddingLeft') self.padding_top = get_int_value(data, key_prefix + 'paddingTop') self.padding_right = get_int_value(data, key_prefix + 'paddingRight') self.padding_bottom = get_int_value(data, key_prefix + 'paddingBottom') self.font_style = '' if self.bold: self.font_style += 'B' if self.italic: self.font_style += 'I' self.text_align = '' if self.horizontal_alignment == HorizontalAlignment.left: self.text_align = 'L' elif self.horizontal_alignment == HorizontalAlignment.center: self.text_align = 'C' elif self.horizontal_alignment == HorizontalAlignment.right: self.text_align = 'R' elif self.horizontal_alignment == HorizontalAlignment.justify: self.text_align = 'J' self.add_border_padding() def set_bold(self, bold): """ Set bold style and update font_style member which is used for pdf rendering. Method is used in rich text rendering. """ self.bold = bold self.font_style = self.get_font_style(ignore_underline=True) def set_italic(self, italic): """ Set italic style and update font_style member which is used for pdf rendering. Method is used in rich text rendering. """ self.italic = italic self.font_style = self.get_font_style(ignore_underline=True) def get_font_style(self, ignore_underline=False): font_style = '' if self.bold: font_style += 'B' if self.italic: font_style += 'I' if self.underline and not ignore_underline: font_style += 'U' return font_style def add_border_padding(self): if self.border_left: self.padding_left += self.border_width if self.border_top: self.padding_top += self.border_width if self.border_right: self.padding_right += self.border_width if self.border_bottom: self.padding_bottom += self.border_width
/reportbro_lib-3.2.1.tar.gz/reportbro_lib-3.2.1/reportbro/structs.py
0.789396
0.36676
structs.py
pypi
from .enums import * from .utils import get_int_value class DocElementBase(object): """Base class for all elements defined in the report template.""" def __init__(self, report, data): self.report = report self.id = None self.y = get_int_value(data, 'y') self.render_y = 0 self.render_bottom = 0 self.bottom = self.y self.height = 0 self.print_if = None self.remove_empty_element = False self.spreadsheet_hide = True self.spreadsheet_column = None self.spreadsheet_add_empty_row = False self.first_render_element = True self.rendering_complete = False self.predecessors = [] self.successors = [] self.sort_order = 1 # sort order for elements with same 'y'-value def is_predecessor(self, elem): """Returns true if the given element is a direct predecessor of this element. An element is a direct predecessor if it ends before or on the same position as this elements starts. Further it has to end after start of a possible existing predecessor, if this is not the case then the given element is already a predecessor of the existing predecessor. The current element can only be printed after all predecessors are finished. """ return self.y >= elem.bottom and (len(self.predecessors) == 0 or elem.bottom > self.predecessors[0].y) def add_predecessor(self, predecessor): self.predecessors.append(predecessor) predecessor.successors.append(self) def has_uncompleted_predecessor(self, completed_elements): """returns True in case there is at least one predecessor which is not completely rendered yet.""" for predecessor in self.predecessors: if predecessor.id not in completed_elements or not predecessor.rendering_complete: return True return False def get_offset_y(self): """Returns offset y-coord for rendering of this element. The value is calculated as lowest bottom (i.e. highest value) of predecessors plus minimum space to any predecessor. """ max_bottom = 0 min_predecessor_dist = None for predecessor in self.predecessors: if predecessor.render_bottom > max_bottom: max_bottom = predecessor.render_bottom predecessor_dist = (self.y - predecessor.bottom) if min_predecessor_dist is None or predecessor_dist < min_predecessor_dist: min_predecessor_dist = predecessor_dist return max_bottom + (min_predecessor_dist if min_predecessor_dist else 0) def clear_predecessor(self, elem): if elem in self.predecessors: self.predecessors.remove(elem) def prepare(self, ctx, pdf_doc, only_verify): pass def is_printed(self, ctx): if self.print_if: return ctx.evaluate_expression(self.print_if, self.id, field='printIf') return True def finish_empty_element(self, offset_y): if self.remove_empty_element: self.render_bottom = offset_y else: self.render_bottom = offset_y + self.height self.rendering_complete = True def get_next_render_element(self, offset_y, container_top, container_width, container_height, ctx, pdf_doc): self.rendering_complete = True return None, True def render_pdf(self, container_offset_x, container_offset_y, pdf_doc): pass def render_spreadsheet(self, row, col, ctx, renderer): return row, col def cleanup(self): pass class DocElement(DocElementBase): def __init__(self, report, data): DocElementBase.__init__(self, report, data) self.id = get_int_value(data, 'id') self.x = get_int_value(data, 'x') self.width = get_int_value(data, 'width') self.height = get_int_value(data, 'height') self.bottom = self.y + self.height def get_next_render_element(self, offset_y, container_top, container_width, container_height, ctx, pdf_doc): if offset_y + self.height <= container_height: self.render_y = offset_y self.render_bottom = offset_y + self.height self.rendering_complete = True return self, True return None, False @staticmethod def draw_border(x, y, width, height, render_element_type, border_style, pdf_doc): pdf_doc.set_draw_color( border_style.border_color.r, border_style.border_color.g, border_style.border_color.b) pdf_doc.set_line_width(border_style.border_width) border_offset = border_style.border_width / 2 border_x = x + border_offset border_y = y + border_offset border_width = width - border_style.border_width border_height = height - border_style.border_width if border_style.border_all and render_element_type == RenderElementType.complete: pdf_doc.rect(border_x, border_y, border_width, border_height, style='D') else: if border_style.border_left: pdf_doc.line(border_x, border_y, border_x, border_y + border_height) if border_style.border_top and render_element_type in ( RenderElementType.complete, RenderElementType.first): pdf_doc.line(border_x, border_y, border_x + border_width, border_y) if border_style.border_right: pdf_doc.line( border_x + border_width, border_y, border_x + border_width, border_y + border_height) if border_style.border_bottom and render_element_type in ( RenderElementType.complete, RenderElementType.last): pdf_doc.line( border_x, border_y + border_height, border_x + border_width, border_y + border_height)
/reportbro_lib-3.2.1.tar.gz/reportbro_lib-3.2.1/reportbro/docelement.py
0.80651
0.224162
docelement.py
pypi
from __future__ import unicode_literals from __future__ import division from babel.numbers import format_decimal from babel.dates import format_datetime from collections import namedtuple from simpleeval import simple_eval, NameNotDefined, FunctionNotDefined from simpleeval import DEFAULT_NAMES as EVAL_DEFAULT_NAMES from simpleeval import DEFAULT_FUNCTIONS as EVAL_DEFAULT_FUNCTIONS import datetime import decimal import sys import logging import re logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) from .enums import * from .errors import Error, ReportBroError # parameter instance, the data map referenced by the parameter and the data map containing # the context_id (this is usually the data map but can be different for collection # parameters) ParameterRef = namedtuple('ParameterRef', ['parameter', 'data', 'data_context']) class Context: def __init__(self, report, parameters, data): self.report = report self.pattern_locale = report.document_properties.pattern_locale self.pattern_currency_symbol = report.document_properties.pattern_currency_symbol self.parameters = parameters self.data = data self.data.update(EVAL_DEFAULT_NAMES) self.eval_functions = EVAL_DEFAULT_FUNCTIONS.copy() self.eval_functions.update( len=len, decimal=decimal.Decimal, datetime=datetime ) # each new context (push_context) gets a new unique id self.id = 1 self.data['__context_id'] = self.id self.root_data = data self.root_data['page_number'] = 0 self.root_data['page_count'] = 0 def get_parameter(self, name): """Return parameter reference for given parameter name. :param name: name of the parameter to find, the parameter can be present in the current context or any of its parents. :return: parameter reference which contains a parameter instance and its data map referenced by the parameter. None if no parameter was found. """ if name.find('.') != -1: # this parameter is part of a collection, so we first get the reference to the # collection parameter and then return the parameter inside the collection name_parts = name.split('.') collection_name = name_parts[0] field_name = name_parts[1] param_ref = self._get_parameter( collection_name, parameters=self.parameters, data=self.data) if param_ref is not None and param_ref.parameter.type == ParameterType.map and\ field_name in param_ref.parameter.fields and collection_name in param_ref.data: return ParameterRef( parameter=param_ref.parameter.fields[field_name], data=param_ref.data[collection_name], data_context=param_ref.data) return None else: return self._get_parameter(name, parameters=self.parameters, data=self.data) def _get_parameter(self, name, parameters, data): if name in parameters: return ParameterRef(parameter=parameters[name], data=data, data_context=data) elif parameters.get('__parent') and data.get('__parent'): return self._get_parameter( name, parameters=parameters.get('__parent'), data=data.get('__parent')) return None @staticmethod def get_parameter_data(param_ref): """Return data for given parameter reference. :param param_ref: a parameter reference which contains a parameter instance and its data map referenced by the parameter. :return: tuple of current data value of parameter, bool if parameter data exists """ if param_ref.parameter.name in param_ref.data: return param_ref.data[param_ref.parameter.name], True return None, False @staticmethod def get_parameter_context_id(param_ref): """Return context_id for given parameter reference. This can be useful to find out if a parameter value has changed, e.g. parameter 'amount' in a list of invoice items has a different context_id in each list row (invoice item). :param param_ref: a parameter reference which contains a parameter instance and its data map referenced by the parameter. :return: unique context id or None if there is no context available. """ if '__context_id' in param_ref.data_context: return param_ref.data_context['__context_id'] return None def get_data(self, name, data=None): if data is None: data = self.data if name in data: return data[name], True elif data.get('__parent'): return self.get_data(name, data.get('__parent')) return None, False def push_context(self, parameters, data): parameters['__parent'] = self.parameters self.parameters = parameters data['__parent'] = self.data self.id += 1 data['__context_id'] = self.id self.data = data def pop_context(self): parameters = self.parameters.get('__parent') if parameters is None: raise RuntimeError('Context.pop_context failed - no parent available') del self.parameters['__parent'] self.parameters = parameters data = self.data.get('__parent') if data is None: raise RuntimeError('Context.pop_context failed - no parent available') del self.data['__parent'] self.data = data def build_data(self, parameters, object_id, field, pattern=None): ret = {} for item in parameters: parameter_name = re.search(r'\{(.*?)\}', item) if parameter_name is not None: param_ref = self.get_parameter(parameter_name.group(1)) if param_ref is not None: value, value_exists = Context.get_parameter_data(param_ref) if not value_exists: raise ReportBroError( Error("errorMsgMissingParameterData", object_id=object_id, field=field, info=parameter_name)) elif value is not None: formated_value = self.get_formatted_value(value, param_ref.parameter, object_id, pattern=pattern) ret.update({item: formated_value}) else: ret.update({item: ''}) return ret def fill_parameters(self, expr, object_id, field, pattern=None): if expr.find('${') == -1: return expr parameters = list(filter(lambda item: item.find('}') != -1 or item.find('()') != -1, expr.split(' '))) ret = self.build_data(parameters=parameters, object_id=object_id, field=field, pattern=pattern) for key in ret.keys(): val = re.findall(r'\b[A-Z\s]+\b', key) if (len(val) > 0): for action in val: ret[key] = actions[action](ret[key]) for key in ret.keys(): expr = expr.replace(key, ret[key]) return expr def evaluate_expression(self, expr, object_id, field): if expr: try: data = dict(EVAL_DEFAULT_NAMES) expr = self.replace_parameters(expr, data=data) return simple_eval(expr, names=data, functions=self.eval_functions) except NameNotDefined as ex: raise ReportBroError( Error('errorMsgInvalidExpressionNameNotDefined', object_id=object_id, field=field, info=ex.name, context=expr)) except FunctionNotDefined as ex: # avoid possible unresolved attribute reference warning by using getattr func_name = getattr(ex, 'func_name') raise ReportBroError( Error('errorMsgInvalidExpressionFuncNotDefined', object_id=object_id, field=field, info=func_name, context=expr)) except SyntaxError as ex: raise ReportBroError( Error('errorMsgInvalidExpression', object_id=object_id, field=field, info=ex.msg, context=expr)) except Exception as ex: info = ex.message if hasattr(ex, 'message') else str(ex) raise ReportBroError( Error('errorMsgInvalidExpression', object_id=object_id, field=field, info=info, context=expr)) return True @staticmethod def strip_parameter_name(expr): if expr: return expr.strip().lstrip('${').rstrip('}') return expr @staticmethod def is_parameter_name(expr): return expr and expr.lstrip().startswith('${') and expr.rstrip().endswith('}') def get_formatted_value(self, value, parameter, object_id, pattern=None, is_array_item=False): rv = '' if is_array_item and parameter.type == ParameterType.simple_array: value_type = parameter.array_item_type else: value_type = parameter.type if value_type == ParameterType.string: rv = value used_pattern = pattern if pattern else parameter.pattern if used_pattern: try: if used_pattern == FilterParams.capitalize_all.value: value = value.title() rv = value elif used_pattern == FilterParams.capitalize.value: value = value.capitalize() rv = value elif used_pattern == FilterParams.lower_case.value: value = value.lower() rv = value elif used_pattern == FilterParams.upper_case.value: value = value.upper() rv = value elif used_pattern == FilterParams.time_current.value: value = datetime.date.today() rv = value elif used_pattern == FilterParams.fixed.value: fixedNumber = parameter.number_fixed value = round(value, fixedNumber) rv = value except ValueError: error_object_id = object_id if pattern else parameter.id raise ReportBroError( Error('errorMsgInvalidPattern', object_id=error_object_id, field='pattern', context=value)) else: rv = str(value) elif value_type in (ParameterType.number, ParameterType.average, ParameterType.sum): if pattern: used_pattern = pattern pattern_has_currency = (pattern.find('$') != -1) else: used_pattern = parameter.pattern pattern_has_currency = parameter.pattern_has_currency if used_pattern: try: value = format_decimal(value, used_pattern, locale=self.pattern_locale) if pattern_has_currency: value = value.replace('$', self.pattern_currency_symbol) rv = value except ValueError: error_object_id = object_id if pattern else parameter.id raise ReportBroError( Error('errorMsgInvalidPattern', object_id=error_object_id, field='pattern', context=value)) else: rv = str(value) elif value_type == ParameterType.date: used_pattern = pattern if pattern else parameter.pattern if used_pattern: try: rv = format_datetime(value, used_pattern, locale=self.pattern_locale) except ValueError: error_object_id = object_id if pattern else parameter.id raise ReportBroError( Error('errorMsgInvalidPattern', object_id=error_object_id, field='pattern', context=value)) else: rv = str(value) return rv def replace_parameters(self, expr, data=None): pos = expr.find('${') if pos == -1: return expr ret = '' pos2 = 0 while pos != -1: if pos != 0: ret += expr[pos2:pos] pos2 = expr.find('}', pos) if pos2 != -1: parameter_name = expr[pos+2:pos2] if data is not None: if parameter_name.find('.') != -1: name_parts = parameter_name.split('.') collection_name = name_parts[0] field_name = name_parts[1] value, parameter_exists = self.get_data(collection_name) if isinstance(value, dict): value = value.get(field_name) else: value = None # use valid python identifier for parameter name parameter_name = collection_name + '_' + field_name else: value, parameter_exists = self.get_data(parameter_name) data[parameter_name] = value ret += parameter_name pos2 += 1 pos = expr.find('${', pos2) else: pos2 = pos pos = -1 ret += expr[pos2:] return ret def inc_page_number(self): self.root_data['page_number'] += 1 def get_page_number(self): return self.root_data['page_number'] def set_page_count(self, page_count): self.root_data['page_count'] = page_count
/reportbro-plus-lib-1.6.3.tar.gz/reportbro-plus-lib-1.6.3/reportbro_plus/context.py
0.602763
0.277739
context.py
pypi
from __future__ import unicode_literals from __future__ import division from .enums import * from .errors import Error from .utils import get_float_value, get_int_value class Color: def __init__(self, color): self.color_code = '' if color: assert len(color) == 7 and color[0] == '#' self.r = int(color[1:3], 16) self.g = int(color[3:5], 16) self.b = int(color[5:7], 16) self.transparent = False self.color_code = color else: self.transparent = True def is_black(self): return self.r == 0 and self.g == 0 and self.b == 0 and not self.transparent class Parameter: def __init__(self, report, data): self.report = report self.id = int(data.get('id')) self.name = data.get('name', '<unnamed>') self.type = ParameterType[data.get('type')] if self.type == ParameterType.simple_array: self.array_item_type = ParameterType[data.get('arrayItemType')] else: self.array_item_type = ParameterType.none self.eval = bool(data.get('eval')) self.nullable = bool(data.get('nullable')) self.expression = data.get('expression', '') self.pattern = data.get('pattern', '') self.pattern_has_currency = (self.pattern.find('$') != -1) self.text_filters = data.get('text_filters', '') self.number_fixed = data.get('number_fixed', '') self.is_internal = self.name in ('page_count', 'page_number', 'row_number') self.children = [] self.fields = dict() if self.type == ParameterType.array or self.type == ParameterType.map: for item in data.get('children'): parameter = Parameter(self.report, item) if parameter.name in self.fields: self.report.errors.append(Error('errorMsgDuplicateParameterField', object_id=parameter.id, field='name')) else: self.children.append(parameter) self.fields[parameter.name] = parameter def is_evaluated(self): """Return True if parameter data must be evaluated initially.""" return self.eval or self.type in (ParameterType.average, ParameterType.sum) class BorderStyle: def __init__(self, data, key_prefix=''): self.border_color = Color(data.get(key_prefix + 'borderColor')) self.border_width = get_float_value(data, key_prefix + 'borderWidth') self.border_all = bool(data.get(key_prefix + 'borderAll')) self.border_left = self.border_all or bool(data.get(key_prefix + 'borderLeft')) self.border_top = self.border_all or bool(data.get(key_prefix + 'borderTop')) self.border_right = self.border_all or bool(data.get(key_prefix + 'borderRight')) self.border_bottom = self.border_all or bool(data.get(key_prefix + 'borderBottom')) class TextStyle(BorderStyle): def __init__(self, data, key_prefix=''): BorderStyle.__init__(self, data, key_prefix) self.id = str(get_int_value(data, 'id')) self.bold = bool(data.get(key_prefix + 'bold')) self.italic = bool(data.get(key_prefix + 'italic')) self.underline = bool(data.get(key_prefix + 'underline')) self.strikethrough = bool(data.get(key_prefix + 'strikethrough')) self.horizontal_alignment = HorizontalAlignment[data.get(key_prefix + 'horizontalAlignment')] self.vertical_alignment = VerticalAlignment[data.get(key_prefix + 'verticalAlignment')] self.text_color = Color(data.get(key_prefix + 'textColor')) self.background_color = Color(data.get(key_prefix + 'backgroundColor')) self.font = data.get(key_prefix + 'font') self.font_size = get_int_value(data, key_prefix + 'fontSize') self.line_spacing = get_float_value(data, key_prefix + 'lineSpacing') self.padding_left = get_int_value(data, key_prefix + 'paddingLeft') self.padding_top = get_int_value(data, key_prefix + 'paddingTop') self.padding_right = get_int_value(data, key_prefix + 'paddingRight') self.padding_bottom = get_int_value(data, key_prefix + 'paddingBottom') self.font_style = '' if self.bold: self.font_style += 'B' if self.italic: self.font_style += 'I' self.text_align = '' if self.horizontal_alignment == HorizontalAlignment.left: self.text_align = 'L' elif self.horizontal_alignment == HorizontalAlignment.center: self.text_align = 'C' elif self.horizontal_alignment == HorizontalAlignment.right: self.text_align = 'R' elif self.horizontal_alignment == HorizontalAlignment.justify: self.text_align = 'J' self.add_border_padding() def get_font_style(self, ignore_underline=False): font_style = '' if self.bold: font_style += 'B' if self.italic: font_style += 'I' if self.underline and not ignore_underline: font_style += 'U' return font_style def add_border_padding(self): if self.border_left: self.padding_left += self.border_width if self.border_top: self.padding_top += self.border_width if self.border_right: self.padding_right += self.border_width if self.border_bottom: self.padding_bottom += self.border_width
/reportbro-plus-lib-1.6.3.tar.gz/reportbro-plus-lib-1.6.3/reportbro_plus/structs.py
0.758421
0.234713
structs.py
pypi
import datetime from enum import Enum class Border(Enum): grid = 1 frame_row = 2 frame = 3 row = 4 none = 5 class RenderElementType(Enum): none = 0 complete = 1 between = 2 first = 3 last = 4 class DocElementType(Enum): text = 1 image = 2 line = 3 page_break = 4 table_band = 5 table = 6 table_text = 7 bar_code = 8 frame = 9 section = 10 section_band = 11 qr_code = 12 # list_element = 13 class ParameterType(Enum): none = 0 string = 1 number = 2 boolean = 3 date = 4 array = 5 simple_array = 6 map = 7 sum = 8 average = 9 image = 10 class BandType(Enum): header = 1 content = 2 footer = 3 class PageFormat(Enum): a4 = 1 a5 = 2 letter = 3 user_defined = 4 class Unit(Enum): pt = 1 mm = 2 inch = 3 class Orientation(Enum): portrait = 1 landscape = 2 class BandDisplay(Enum): never = 1 always = 2 not_on_first_page = 3 class HorizontalAlignment(Enum): left = 1 center = 2 right = 3 justify = 4 class VerticalAlignment(Enum): top = 1 middle = 2 bottom = 3 class FilterParams(Enum): fixed = "FIXED" lower_case = "LOWERCASE" upper_case = "UPPERCASE" time_current = "NOW" capitalize = "CAPITALIZE" capitalize_all = "CAPITALIZEALL" formules = [ "FIXED", "UPPERCASE", "LOWERCASE", "NOW", "CAPITALIZE", "CAPITALIZEALL", "TRIM", "DAY", "MONTH", "YEAR", "ABS" ] actions = { "ABS": lambda data: abs(data), "NOW": lambda data: datetime.date.today().strftime('%Y-%m-%d'), "DAY": lambda data: datetime.datetime.today().strftime('%A'), "MONTH": lambda data: datetime.date.today().strftime('%B'), "YEAR": lambda data: datetime.date.today().strftime('%Y'), "FIXED": lambda data, fixed_number: round(data, fixed_number), "UPPERCASE": lambda data: data.upper(), "LOWERCASE": lambda data: data.lower(), "CAPITALIZE": lambda data: data.capitalize(), "CAPITALIZEALL": lambda data: data.title(), "TRIM": lambda data: data.replace(' ', '') }
/reportbro-plus-lib-1.6.3.tar.gz/reportbro-plus-lib-1.6.3/reportbro_plus/enums.py
0.420124
0.36625
enums.py
pypi
from .enums import * from .utils import get_int_value class DocElementBase(object): """Base class for all elements defined in the report template.""" def __init__(self, report, data): self.report = report self.id = None self.y = get_int_value(data, 'y') self.render_y = 0 self.render_bottom = 0 self.bottom = self.y self.height = 0 self.print_if = None self.remove_empty_element = False self.spreadsheet_hide = True self.spreadsheet_column = None self.spreadsheet_add_empty_row = False self.first_render_element = True self.rendering_complete = False self.predecessors = [] self.successors = [] self.sort_order = 1 # sort order for elements with same 'y'-value def is_predecessor(self, elem): """Returns true if the given element is a direct predecessor of this element. An element is a direct predecessor if it ends before or on the same position as this elements starts. Further it has to end after start of a possible existing predecessor, if this is not the case then the given element is already a predecessor of the existing predecessor. The current element can only be printed after all predecessors are finished. """ return self.y >= elem.bottom and (len(self.predecessors) == 0 or elem.bottom > self.predecessors[0].y) def add_predecessor(self, predecessor): self.predecessors.append(predecessor) predecessor.successors.append(self) def has_uncompleted_predecessor(self, completed_elements): """returns True in case there is at least one predecessor which is not completely rendered yet.""" for predecessor in self.predecessors: if predecessor.id not in completed_elements or not predecessor.rendering_complete: return True return False def get_offset_y(self): """Returns offset y-coord for rendering of this element. The value is calculated as lowest bottom (i.e. highest value) of predecessors plus minimum space to any predecessor. """ max_bottom = 0 min_predecessor_dist = None for predecessor in self.predecessors: if predecessor.render_bottom > max_bottom: max_bottom = predecessor.render_bottom predecessor_dist = (self.y - predecessor.bottom) if min_predecessor_dist is None or predecessor_dist < min_predecessor_dist: min_predecessor_dist = predecessor_dist return max_bottom + (min_predecessor_dist if min_predecessor_dist else 0) def clear_predecessor(self, elem): if elem in self.predecessors: self.predecessors.remove(elem) def prepare(self, ctx, pdf_doc, only_verify): pass def is_printed(self, ctx): if self.print_if: return ctx.evaluate_expression(self.print_if, self.id, field='printIf') return True def finish_empty_element(self, offset_y): if self.remove_empty_element: self.render_bottom = offset_y else: self.render_bottom = offset_y + self.height self.rendering_complete = True def get_next_render_element(self, offset_y, container_top, container_height, ctx, pdf_doc): self.rendering_complete = True return None, True def render_pdf(self, container_offset_x, container_offset_y, pdf_doc): pass def render_spreadsheet(self, row, col, ctx, renderer): return row, col def cleanup(self): pass class DocElement(DocElementBase): def __init__(self, report, data): DocElementBase.__init__(self, report, data) self.id = get_int_value(data, 'id') self.x = get_int_value(data, 'x') self.width = get_int_value(data, 'width') self.height = get_int_value(data, 'height') self.bottom = self.y + self.height def get_next_render_element(self, offset_y, container_top, container_height, ctx, pdf_doc): if offset_y + self.height <= container_height: self.render_y = offset_y self.render_bottom = offset_y + self.height self.rendering_complete = True return self, True return None, False @staticmethod def draw_border(x, y, width, height, render_element_type, border_style, pdf_doc): pdf_doc.set_draw_color( border_style.border_color.r, border_style.border_color.g, border_style.border_color.b) pdf_doc.set_line_width(border_style.border_width) border_offset = border_style.border_width / 2 border_x = x + border_offset border_y = y + border_offset border_width = width - border_style.border_width border_height = height - border_style.border_width if border_style.border_all and render_element_type == RenderElementType.complete: pdf_doc.rect(border_x, border_y, border_width, border_height, style='D') else: if border_style.border_left: pdf_doc.line(border_x, border_y, border_x, border_y + border_height) if border_style.border_top and render_element_type in ( RenderElementType.complete, RenderElementType.first): pdf_doc.line(border_x, border_y, border_x + border_width, border_y) if border_style.border_right: pdf_doc.line(border_x + border_width, border_y, border_x + border_width, border_y + border_height) if border_style.border_bottom and render_element_type in ( RenderElementType.complete, RenderElementType.last): pdf_doc.line(border_x, border_y + border_height, border_x + border_width, border_y + border_height)
/reportbro-plus-lib-1.6.3.tar.gz/reportbro-plus-lib-1.6.3/reportbro_plus/docelement.py
0.802788
0.228372
docelement.py
pypi
Report Engine ============= The main components are: - A Report object. - An interface to construct a report from a given configuration: `ResourceProcessor`. - A convention for the layout of the code that actually produces the report, based on `ResourceProcessor` plus some helper tools to enforce that convention (`repottools`?). The main interface should be coded in Python 3.5. Here a graphical representation: ![PDF](https://github.com/NNPDF/reportengine/tree/designdocs/docs/reportengine_layout.pdf) Report ------ The Report object should be as simple as possible and easy to extend. The basic interface of the report object will consist on methods to: - Extract the required resources and parameters (see below) from the user specification. - Fill the construct the report with the resources provided by the engine. Our implementation will use `jinja2` templates to compile to Markdown. It will also be responsible for handling more complex objects, such as `matplotlib` figures and tables (for example to export them to the correct path). The report class should only understand a set of basic objects and know how to compile them to Markdown. This will call the appropriate macros in `jinja2` (for example, place a caption below a figure). Default helpers and styles exist to produce the final content (i.e. PDF or html files out of Markdown) but are largely a concern of the clients. Together with the template, data file, which is processed by a `ResourceProcessor` is used to supply the information necessary to build the report. ResourceProcessor ----------------- This class takes a configuration file which contains *input resources* and figures out the processing that needs to be done to obtain *output resources* (which are specified in the report layout in this case). While it is made with reports in mind, it is way more general. In addition to tools for running the configuration, there are tools to validate the inputs and analyze the requirements. While in the most simple case, the outputs are directly functions of the inputs, there is also the possibility of intermediate steps, so that the required operations can be represented as a *Direct Acyclic Graph (DAG)*. The class also takes a Python package which contains the functions needed to actually carry out the computations (as well as doing specific validations). This package will contain three kinds of functions: - Parsers: Parse the user input in the configuration file to produce an input resource. - Checks: Perform domain specific checks on the configuration before it is executed. - Providers: Compute a specific resource (taking other resources and parameters as input). Each of these is described in more detail below. ###Example Imagine we have one *input resource*, *fit*. And we need to produce two *output resources*: *arclength plots* and *arclength affinty*. Both of these require a rather expensive computation called *arclength*. `ResourceProcessor` would be called with these parameters, as well as a module `validphys` containing the following *provider* functions: ```python #provides the *resource* arclength def arclength(fit): ... def arclength_affinity(arclength): ... def plot_arclength(arclength): ... ``` The first job of `ResourceProcessor` is to figure out the appropriate order in which these functions need to be called. ###Documentation The docstrings of the provider functions (plus some additions) are automatically made available as documentation in the various interfaces. For example: ```python #provides the *resource* arclength def arclength(fit): """Computes the arclength for all replicas in ``fit``. It uses ``nndiff`` to calculate the analytical expression of the derivative of the neural network. ... def plot_arclength(arclength): """Plot distribution of arclengths.""" ... ``` Would cause the docs to be automatically available to various parts in the code and possibly the report itself (tooltips of figures?). ###Namespaces and parameters It is possible to call *final* providers with different *parameters* in different parts of the report. For example, imagine a function: ```python def plot_compare_pdfs(pdf, base_pdf): ... ``` It might be useful to call that function with `base_pdf` pointing at the previous fit or at the closure test prior in different parts of the report. As long as this resource is *final* (i.e. if the compare PDF figures are not required by any other resource in the report). All resources are resolved within *namespaces* which can be specified by the user (in the report layout). They are used to produce resources with completely different input, which would correspond to different execution graphs, in general. There is also the default namespace, which will be used if no namespace is specified. An independent DAG will be constructed for each namespace and all the functions necessary to construct them will be executed (even if the inputs are the same). Any caching behaviour is responsibility of the client. ###Interactive interfaces Using a `DAGResources` should be trivial to determine what needs to be recomputed when some *input resource* is changed by the user. This sets the stage for building a more interactive representation such as a web interface. ###Checks As much as possible failures due to incorrect user input must be checked **before** any computation takes place. `ResourceProcessor` should implement the basic checks (i.e. that the graph can actually be constructed). Additionally the Python 3.5 [`typing module`](https://docs.python.org/3/library/typing.html) could be used to check for the types of the resources. There is also support for domain-specific checks implemented as a `check` decorator. It takes a function as a parameter which in turn is called with the decorated function, the namespace and the instance of `ResourceProcessor`. The decorated function For example: ```python def pdfs_installed(resource, namespace, resolver): """Check if the relevant pdfs are installed in LHAPDF""" ... @check(pdfs_installed) def plot_compare_pdfs(pdf:PDF, base_pdf:PDF) -> reportengine.Figure: ... ``` The fact that the arguments are in fact PDFs would be checked by `ResourceProcessor` (which will know the return types of all producers), while the function `pdfs_installed` would be called before actually building the report. The checks are called in the same order as the functions would. ###Input The input resources are set by the user with a YAML file. Keys ending with an underscore *_* have a special meaning and are not allowed for clients. One such key is `namespaces_`, which is used to declare namespaces (see above). A basic configuration file would be: ```yaml fit: /path/to/fit base_pdf: NNPDF30_as_118 namespaces_: vsprevious: base_pdf: prevfitpdf vsclosure: base_pdf: MMHT ``` This would create 3 namespaces (the two explicitly defined and the default one), each of which contain two input resources, *fit* and *base_pdf*. Fit is equal for all of them, and of inherited from the global namespace, while *base_pdf* is different for each of them. An application specific parser would be defined to process the resource. It is implemented by the functions `parse_<resource>` defined in the client package (maybe with the option of specifying which module). They take as input the value only: ```python from valifphys.core import Fit, PDF def parse_fit(self, path) -> Fit: return Fit(path) def parse_base_pdf(self, lhapdfname) -> PDF: return PDF(lhapdfname) ``` If no such function is found, the resources will have the value given in the YAML file. The type would be checked as described above. Any error during the parsing would be intercepted and recast as a nice error message. ###SMPDF correspondence Many of these ideas are directly taken from [SMPDF](https://github.com/scarrazza/smpdf). In particular the [`actions`](https://github.com/scarrazza/smpdf/blob/master/src/smpdflib/actions.py) module is a primitive implementation of `ResourceProcessor`, though much of the work is done manually. A rough correspondence in terminology would be: action -> provider actiongroup -> namespace Configuration -> ResourceProcessor Eventually that part of SMPDF would be reworked to use this framework. Script conventions ------------------ The client functions (*resource providers*) will take a set of resources as input, and produce one new resource as output. The name of the new resource will be the same as that of the function. They will not have access to other information such as the `ResourceProcessor` instance that is running them. If they specify the return type using function signatures, it will be checked before executing the graph. However this is not mandatory. The function defined by the user should have no side effects. In particular they should not modify their input resources in any way (so we executing the DAG in any valid order would produce the same result) and the output should be a deterministic function of the output. This largely confines the possible errors in the client applications to the functions where they have originated. Also, if this is fulfilled, things like parallel execution of the DAG, or fault tolerance (producing a valid report even if a function fails) becomes feasible. In particular the functions should not write files (such as images) to disk,but instead should rely on centrally provided functionality (which would take care of saving to the correct paths, save in the requested format and so on). The output of the final resources should be objects from `reportengine`, or objects that can be casted to them. For example a `reportenfine.Figure` object would contain one or more `matplotlib` figures, but also the corresponding `caption` attributes. Saving the actual files to disk will be responsibility of `reportengine`. Of course the *no side effects* rule has exceptions. One example is caching the outputs, as indexed by the inputs (as implemented by `functools.lru_cache` for example). However the it should *look like* no side effects exist to the external world. In addition to resource providers, the client can also implement **checks** (see above). A difference is that checks do have access to the namespace and the `ResourceProcessor` instance where they belong. This is necessary to implement less trivial checks. For instance SMPDF checks that the PDF requested for plotting exist in LHAPDF. However if a new PDF set is to be generated in some previous step (and in another "namespace"), it is also considered valid to enter the name of that new PDF. It is not clear what is the best strategy for aggregating multiple objects of the same kind (for example compare the arclength distribution of two different PDF sets). The current approach is to make the resource providers explicitly aware and always operate over lists of items. However other strategies might be considered, such as a more general design of the graph-based execution and checking model.
/reportengine-0.31.tar.gz/reportengine-0.31/docs/DESIGN.md
0.651022
0.969699
DESIGN.md
pypi
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, hamming_loss from sklearn.model_selection import train_test_split from reportengine import collect from reportengine.figure import figure from reportengine.table import table from reportengine.checks import make_argcheck, CheckError def fit_result(algorithm, dataset): """Fit to a sample of the dataset where some labels have been shuffled using the default algorithm parameters""" y_train = dataset.target.copy() np.random.seed(1520) mask = np.random.randint(len(y_train), size=len(y_train)//2) to_shuffle = y_train[mask] np.random.shuffle(to_shuffle) y_train[mask] = to_shuffle return algorithm().fit(dataset.data, y_train) @figure def plot_2d(scatterdata): """Generate scatter plot of the values of xaxis vs yaxis""" x,y,category = scatterdata fig, ax = plt.subplots() ax.scatter(x,y, c=category, cmap=plt.cm.coolwarm) return fig @make_argcheck def _check_can_predict_probabilities(algorithm): res = hasattr(algorithm().fit([[0],[1]], [0,1]), 'predict_proba') if not res: raise CheckError(f"Algorithm {algorithm.__name__} doesn't support " "'predict_proba'") @make_argcheck def _check_fpr_threshold(fpr_threshold): """Check that it's in (0,1) if given""" if fpr_threshold is None: return if not 0<fpr_threshold<1: raise CheckError('fpr_threshold must be contained in (0,1)') @figure @_check_fpr_threshold @_check_can_predict_probabilities def plot_roc(fit_result, algorithm, dataset, fpr_threshold:(float, type(None))=None): """Plot the ROC curve for each category. Mark the true positive rate at the ``fpr_threshold`` if given""" probs = fit_result.predict_proba(dataset.data) fig, ax = plt.subplots() for i, label in enumerate(dataset.target_names): y_pred = probs[:,i] y_true = (dataset.target == i) fpr, tpr, _ = roc_curve(y_true, y_pred) color = f'C{i}' ax.plot(fpr, tpr, label=label, color=color) if fpr_threshold is not None: pos = np.searchsorted(fpr, fpr_threshold) ax.axhline(tpr[pos], linestyle='--', lw=0.5, color=color) ax.set_xlabel("False Positive rate") ax.set_ylabel("True Positive rate") ax.set_title("ROC curve") ax.legend() return fig fit_results = collect(fit_result, ['algorithms']) @table def hamming_loss_table(algorithms, fit_results, dataset): records = [] for algorithm, res in zip(algorithms, fit_results): records.append({'algorithm': algorithm.__name__, "Hamming " "loss": hamming_loss(dataset.target, res.predict(dataset.data))}) return pd.DataFrame(records)
/reportengine-0.31.tar.gz/reportengine-0.31/example/flowers/actions.py
0.886125
0.450299
actions.py
pypi
+---------------+---------------------+-------------------+ | |Lint Badge| | |Test Badge| | |Version Badge| | +---------------+---------------------+-------------------+ .. |Lint Badge| image:: https://github.com/freelawproject/reporters-db/workflows/Lint/badge.svg .. |Test Badge| image:: https://github.com/freelawproject/reporters-db/workflows/Tests/badge.svg .. |Version Badge| image:: https://badge.fury.io/py/reporters-db.svg Background of the Free Law Reporters Database ============================================= A long, long time ago near a courthouse not too far away, people started keeping books of every important opinion that was ever written. These books became known as *reporters* and were generally created by librarian-types of yore such as `Mr. William Cranch <https://en.wikipedia.org/wiki/William_Cranch>`__ and `Alex Dallas <https://en.wikipedia.org/wiki/Alexander_J._Dallas_%28statesman%29>`__. These people were busy for the next few centuries and created *thousands* of these books, culminating in what we know today as West's reporters or as regional reporters like the "Dakota Reports" or the thoroughly-named, "Synopses of the Decisions of the Supreme Court of Texas Arising from Restraints by Conscript and Other Military Authorities (Robards)." In this repository we've taken a look at all these reporters and tried to sort out what we know about them and convert that to data. This data is available as a JSON file, as Python variables, and can be browsed in an unofficial CSV (it's usually out of date). Naturally, converting several centuries' history into clean data results in a mess, but we've done our best and this mess is in use in a number of projects as listed below. As of version 3.2.32, this data contains information about 1,167 reporters and 2,102 name variations. We hope you'll find this useful to your endeavors and that you'll share your work with the community if you improve or use this work. Data Sourcing ============= This project has been enhanced several times with data from several sources: 1. The original data came from parsing the citation fields for millions of cases in CourtListener. 2. A second huge push came from parsing metadata obtained from two major legal publishers, and by parsing the citation fields of Havard's Case.law database. 3. An audit was performed and additional fields were added by using regular expressions to find number-word-number strings in the entire Harvard Case.law database. The results of this were sorted by frequency, with the top omissions fixed. Along the way, small and subtle improvements have been made as gaps were identified and fixed. The result is that this database should thus be very complete when it comes to reporter abbreviations and variations. It has the data from CourtListener, two major legal publishers, and Harvard's Case.law. Hundreds of hours have gone into this database to make it complete. Installation (Python) ===================== You can install the Free Law Reporters Database with a few simple commands: :: pip install reporters-db Of course, if you're not using Python, the data is in the ``json`` format, so you should be able to import it using your language of choice. People occasionally play with converting this to other languages, but no other implementations are presently known. API === Using this database is pretty simple. As this is a database, here are no public methods or classes, only variables. Importing any of these these variables loads them all, including loading several JSON files from disk. It is therefore recommended not to load these variables more than necessary. The simplest way to understand this data is to simply import these variables and look at them. All variables are imported from the package root as follows: :: from reporters_db import REPORTERS The available variables are: - ``REPORTERS`` — This is the main database and contains a huge dict of reporters as described below. - ``LAWS`` — Our database of statutory abbreviations, mapping the statute abbreviations to their metadata. For example ``Ark. Reg`` is the abbreviation for the ``Arkansas Register``. - ``JOURNALS`` — Same idea as ``LAWS``, but for legal journal abbreviations. - ``STATE_ABBREVIATIONS`` — Bluebook style abbreviations for each state. For example, ``Ala.`` for Alaska and ``Haw.`` for Hawaii. - ``CASE_NAME_ABBREVIATIONS`` — Bluebook style abbreviations for common words, mapping each abbreviation to a list of possible words. For example, ``Admin`` maps to ``["Administrative", "Administration"]``. A few specialized reporter-related variables are: - ``VARIATIONS_ONLY`` — This contains a dict mapping a canonical reporter abbreviation to a list of possible variations it could represent. For example, ``A. 2d`` sometimes incorrectly lacks a space, and has a variation list of ``["A.2d"]``. ``P.R.`` could be ``["Pen. & W.", "P.R.R.", "P."]``. - ``EDITIONS`` — A simple dict to map the abbreviations for each reporter edition to the canonical reporter. For example, ``A.2d`` maps to ``A.``. - ``NAMES_TO_EDITIONS`` — A simple dict to map the name of a reporter back to its canonilcal abbreviations. For example, ``Atlantic Reporter`` maps to ``['A.', 'A.2d']``. CSV === You can make a CSV of this data by running: :: make_csv.py We keep a copy of this CSV in this repository (``reporters.csv``), but it is not kept up to date. It should, however, provide a good idea of what's here. Known Implementations ===================== 1. This work was originally deployed in the `CourtListener <https://www.courtlistener.com>`__ citation finder beginning in about 2012. It has been used literally millions of times to identify citations between cases. 2. An extension for Firefox known as the `Free Law Ferret <http://citationstylist.org/2013/08/20/free-law-ferret-document-to-cited-cases-in-a-click/>`__ uses this code to find citations in your browser as you read things -- all over the Web. 3. A Node module called `Walverine <https://github.com/adelevie/walverine>`__ uses an iteration of this code to find citations using the V8 JavaScript engine. Additional usages can be `found via Github <https://github.com/freelawproject/reporters-db/network/dependents?package_id=UGFja2FnZS01MjU0MTgzNg%3D%3D>`__. Some Notes on the Data ====================== Some things to bear in mind as you are examining the Free Law Reporters Database: 1. Each Reporter key maps to a list of reporters that that key can represent. In some cases (especially in early reporters), the key is ambiguous, referring to more than one possible reporter. 2. Formats follow the Blue Book standard, with variations listed for local rules and other ways lawyers abbreviate it over the years or accidentally. 3. The ``variations`` key consists of data from local rules, found through organic usage in our corpus and from the `Cardiff Index to Legal Abbreviations <http://www.legalabbrevs.cardiff.ac.uk/>`__. We have used a dict for these values due to the fact that there can be variations for each series. 4. ``mlz_jurisdiction`` corresponds to the work that is being done for Multi-Lingual Zotero. This field is maintained by Frank Bennett and may sometimes be missing values. 5. Some reporters have ``href`` or ``notes`` fields to provide a link to the best available reference (often Wikipedia) or to provide notes about the reporter itself. 6. Regarding dates of the editions, there are a few things to know. In reporters with multiple series, if multiple volumes have the same dates, this indicates that the point where one series ends and the other begins is unknown. If an edition has 1750 as its start date, this indicates that the actual start date is unknown. Likewise, if an edition has ``null`` as its end date, that indicates the actual end date is either unknown, or it's known that the series has not completed. These areas need research before we can release version 1.1 of this database. Finally, dates are inclusive, so the first and last opinions in a reporter series have the same dates as the database. A complete data point has fields like so: :: "$citation": [ { "cite_type": "state|federal|neutral|specialty|specialty_west|specialty_lexis|state_regional|scotus_early", "editions": { "$citation": { "end": null, "regexes": [], "start": "1750-01-01T00:00:00" }, "$citation 2d": { "end": null, "regexes": [], "start": "1750-01-01T00:00:00" } }, "examples": [], "mlz_jurisdiction": [], "name": "", "variations": {}, "notes": "", "href": "", "publisher": "" } ], The "regexes" field and regexes.json placeholders ------------------------------------------------- The "regexes" field can contain raw regular expressions to match a custom citation format, or can contain placeholders to be substituted from ``regexes.json`` using `python Template formatting <https://docs.python.org/3/library/string.html#template-strings>`__. If custom regexes are provided, the tests will require that all regexes match at least one example in ``examples`` and that all examples match at least one regex. When adding a new regex it can be useful to ``pip install exrex`` and run the tests *without* adding any examples to get a listing of potential citations that would be matched by the new regex. ``state_abbreviations`` and ``case_name_abbreviations`` files ------------------------------------------------------------- 1. Abbreviations are based on data from the values in the nineteenth edition of the Blue Book supplemented with abbreviations found in our corpus. 2. ``case_name_abbreviations.json`` contains the abbreviations that are likely to occur in the case name of an opinion. 3. ``state_abbreviations.json`` contains the abbreviations that are likely to be used to refer to American states. Notes on Specific Data Point and References ------------------------------------------- 1. A good way to look up abbreviations is in `Prince's Bieber Dictionary of Legal Abbreviations <https://books.google.com/books?id=4aJsAwAAQBAJ&dq=%22Ohio+Law+Rep.%22&source=gbs_navlinks_s>`__. You can find a lot of this book on Google Books, but we have it as a PDF too. Just ask. 2. Mississippi supports neutral citations, but does so in their own format, as specified in `this rule <http://www.aallnet.org/main-menu/Advocacy/access/citation/neutralrules/rules-ms.html>`__. Research is needed for the format in ``reporters.json`` to see if it is used accidentally as a variant of their rule or whether it is an error in this database. 3. New Mexico dates confirmed via the `table here <http://www.nmcompcomm.us/nmcases/pdf/NM%20Reports%20to%20Official%20-%20Vols.%201-75.pdf>`__. 4. Both Puerto Rico and "Pennsylvania State Reports, Penrose and Watts" use the citation "P.R." Tests ===== We have a few tests that make sure things haven't completely broken. They are automatically run by Travis CI each time a push is completed and should be run by developers as well before pushing. They can be run with: :: python tests.py It's pretty simple, right? Releases -------- Update setup.py, add a git tag to the commit with the version number, and push to master. Be sure you have your tooling set up to push git tags. That's often not the default. Github Actions will push a release to PyPi if tests pass. License ======= This repository is available under the permissive BSD license, making it easy and safe to incorporate in your own libraries. Pull and feature requests welcome. Online editing in Github is possible (and easy!)
/reporters-db-3.2.36.tar.gz/reporters-db-3.2.36/README.rst
0.827793
0.750278
README.rst
pypi
import re from collections import OrderedDict from string import Template def suck_out_variations_only(reporters): """Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possibly referring to. """ variations_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for variation_key, variation_value in data["variations"].items(): try: variations_list = variations_out[variation_key] if variation_value not in variations_list: variations_list.append(variation_value) except KeyError: # The item wasn't there; add it. variations_out[variation_key] = [variation_value] return variations_out def suck_out_editions(reporters): """Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key. """ editions_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for edition_key, edition_value in data["editions"].items(): try: editions_out[edition_key] except KeyError: # The item wasn't there; add it. editions_out[edition_key] = reporter_key return editions_out def suck_out_formats(reporters): """Builds a dictionary mapping edition keys to their cite_format if any. The dictionary takes the form of: { 'T.C. Summary Opinion': '{reporter} {volume}-{page}', 'T.C. Memo.': '{reporter} {volume}-{page}' ... } In other words, this lets you go from an edition match to its parent key. """ formats_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # Map the cite_format if it exists for edition_key, edition_value in data["editions"].items(): try: formats_out[edition_key] = data["cite_format"] except KeyError: # The item wasn't there; add it. pass return formats_out def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key, data_list in reporters.items(): for data in data_list: abbrevs = data["editions"].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data["editions"][x]["start"]) + x abbrevs = sorted(abbrevs, key=sort_func) names[data["name"]] = abbrevs sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0])) return sorted_names def process_variables(variables): r"""Process contents of variables.json, in preparation for passing to recursive_substitute: - Strip keys ending in '#', which are treated as comments - Flatten nested dicts, so {"page": {"": "A", "foo": "B"}} becomes {"page": "A", "page_foo": "B"} - Add optional variants for each key, so {"page": "\d+"} becomes {"page_optional": "(?:\d+ ?)?"} - Resolve nested references """ # flatten variables and remove comments def flatten(d, parent_key=""): items = {} for k, v in d.items(): if k.endswith("#"): continue new_key = "_".join(i for i in (parent_key, k) if i) if isinstance(v, dict): items.update(flatten(v, new_key)) else: items[new_key] = v return items variables = flatten(variables) # add optional variables for k, v in list(variables.items()): variables[f"{k}_optional"] = f"(?:{v} ?)?" # resolve references variables = { k: recursive_substitute(v, variables) for k, v in variables.items() } return variables def recursive_substitute(template, variables, max_depth=100): """Recursively substitute values in `template` from `variables`. For example: >>> recursive_substitute("$a $b $c", {'a': '$b', 'b': '$c', 'c': 'foo'}) "foo foo foo" Infinite loops will raise a ValueError after max_depth loops. """ old_val = template for i in range(max_depth): new_val = Template(old_val).safe_substitute(variables) if new_val == old_val: break old_val = new_val else: raise ValueError(f"max_depth exceeded for template '{template}'") return new_val def substitute_edition(regex, edition_name): """Insert edition_name in place of $edition.""" return Template(regex).safe_substitute(edition=re.escape(edition_name)) def substitute_editions(regex, edition_name, variations): r"""Insert edition strings for the given edition into a regex with an $edition placeholder. Example: >>> substitute_editions(r'\d+ $edition \d+', 'Foo.', {'Foo. Var.': 'Foo.'}) "\\d+ (?:Foo\\.|Foo\\. Var\\.) \d+" """ if "$edition" not in regex and "${edition}" not in regex: return [regex] edition_strings = [edition_name] + [ k for k, v in variations.items() if v == edition_name ] return [substitute_edition(regex, e) for e in edition_strings]
/reporters-db-3.2.36.tar.gz/reporters-db-3.2.36/reporters_db/utils.py
0.639849
0.493775
utils.py
pypi
import re from . import parsers from dateutil import parser operators_dict = { "==": "equals", "!=": "notEqual", ">": "greaterThan", "<": "lessThan", ">=": "greaterOrEqual", "<=": "lessOrEqual", "contains": "contains", "not contains": "notContain", "startswith": "startsWith", } def set_filters(filters, metadata): """Append each filter in a list of filter to report metadata.""" for f in filters: column, operator, value = f filter_dict = { "column": parsers.get_columns_labels(metadata)[column], "operator": operators_dict.get(operator), "value": value, } metadata["reportMetadata"]["reportFilters"].append(filter_dict) def update_filter(index, key, value, metadata): """Update an arbitrary filter key-value pair in a list of filters.""" metadata["reportMetadata"]["reportFilters"][index][key] = value def increment_logical_filter(metadata): """Increment logical filter by an additional column. This is used to avoid an error being thrown when we filter by an identifier column without including it in the filter logic. """ logic = metadata["reportMetadata"]["reportBooleanFilter"] if logic: # get last number, for example, get 3 in '(1 AND (2 OR 3))' last_number = re.search(r"(\d+)\)*$", logic).group(1) # turn filter into '(1 AND (2 OR 3)) AND 4' new_logic = logic + " AND {}".format(int(last_number) + 1) metadata["reportMetadata"]["reportBooleanFilter"] = new_logic def set_logic(logic, metadata): """Set logical filter value.""" metadata["reportMetadata"]["reportBooleanFilter"] = logic def set_period(start, end, column, metadata): """Set date-related filters parameters.""" date_filter = metadata["reportMetadata"]["standardDateFilter"] date_filter["durationValue"] = "CUSTOM" if column: date_filter["column"] = parsers.get_columns_labels(metadata)[column] if start: date_filter["startDate"] = parser.parse(start, dayfirst=True).strftime( "%Y-%m-%d" ) if end: date_filter["endDate"] = parser.parse(end, dayfirst=True).strftime("%Y-%m-%d")
/helpers/report_filters.py
0.649023
0.454048
report_filters.py
pypi
import re import itertools from dateutil.parser import parse from reportforce.helpers import utils class Metadata(dict): @property def report_metadata(self): return self["reportMetadata"] @property def extended_metadata(self): return self["reportExtendedMetadata"] @property def report_format(self): return self.report_metadata["reportFormat"] @property def report_filters(self): return self.report_metadata["reportFilters"] @report_filters.setter def report_filters(self, params): for param in params: column, operator, value = param api_name = self.get_column_api_name(column) operator = self.get_operator(operator) value = self.format_value(value, api_name) self.report_filters.append( {"column": api_name, "operator": operator, "value": value} ) def format_value(self, value, column): dtype = self.get_column_dtype(column) if dtype in ["datetime", "date", "time"]: if utils.is_iterable(value): return ",".join(map(self.format_date, value)) else: return self.format_date(value) elif utils.is_iterable(value): return ",".join(map(utils.surround_with_quotes, value)) else: return utils.surround_with_quotes(value) @staticmethod def format_date(value): if value is not None: return parse(value, dayfirst=True).isoformat() operators = { "==": "equals", "!=": "notEqual", ">": "greaterThan", "<": "lessThan", ">=": "greaterOrEqual", "<=": "lessOrEqual", "contains": "contains", "not contains": "notContain", "startswith": "startsWith", } def get_operator(self, operator): return self.operators.get(operator) @property def boolean_filter(self): return self.report_metadata["reportBooleanFilter"] @boolean_filter.setter def boolean_filter(self, logic): if logic is not None: self.report_metadata["reportBooleanFilter"] = logic def increment_boolean_filter(self): logic = self.boolean_filter if logic: new_logic = self._increment_boolean_filter(logic) self.boolean_filter = new_logic @staticmethod def _increment_boolean_filter(logic): last_number = re.sub(r"[()]", "", logic).split()[-1] new_logic = logic + f" AND {int(last_number) + 1}" return new_logic @property def date_filter(self): return self.report_metadata["standardDateFilter"] @property def date_start(self): return self.date_filter["startDate"] @date_start.setter def date_start(self, date_string): self.date_filter["startDate"] = self.format_date(date_string) @property def date_end(self): return self.date_filter["endDate"] @date_end.setter def date_end(self, date_string): self.date_filter["endDate"] = self.format_date(date_string) @property def date_column(self): return self.date_filter["column"] @date_column.setter def date_column(self, column): self.date_filter["column"] = self.get_column_api_name(column) @property def date_interval(self): return self.date_filter["durationValue"] @date_interval.setter def date_interval(self, interval): self.date_filter["durationValue"] = interval def ignore_date_filter(self): self.date_interval = "CUSTOM" self.date_start = None self.date_end = None def set_date_interval(self, interval): start, end, interval = self.get_interval_info(interval) self.date_interval = interval self.date_start = start self.date_end = end @property def detail_column_info(self): return self.extended_metadata["detailColumnInfo"].items() @property def aggregate_column_info(self): return self.extended_metadata["aggregateColumnInfo"].items() @property def all_available_columns(self): return itertools.chain( *( obj["columns"].items() for obj in self["reportTypeMetadata"]["categories"] ) ) @property def all_columns_info(self): return itertools.chain( self.detail_column_info, self.aggregate_column_info, self.all_available_columns, ) def get_column_info_by_api_name(self, target, info): for api_name, infos in self.all_columns_info: if api_name == target: return infos.get(info) def get_column_info_by_label(self, target, info): for api_name, infos in self.all_columns_info: if infos["label"] == target: return api_name if info == "apiName" else infos.get(info) def get_column_label(self, column): return self.get_column_info_by_api_name(column, "label") def get_column_dtype(self, column): return self.get_column_info_by_api_name(column, "dataType") def get_column_api_name(self, column): return self.get_column_info_by_label(column, "apiName") def get_interval_info(self, interval): return self.get_date_filter_intervals()[interval].values() def get_date_filter_intervals(self): date_filter_intervals = {} for group in self["reportTypeMetadata"]["standardDateFilterDurationGroups"]: for interval in group["standardDateFilterDurations"]: date_filter_intervals.update( { interval["label"]: { "start": interval["startDate"], "end": interval["endDate"], "value": interval["value"], } } ) return date_filter_intervals @property def sort_by(self): return self.report_metadata["sortBy"] @sort_by.setter def sort_by(self, params): column, order = params self.report_metadata["sortBy"] = [ { "sortColumn": self.get_column_api_name(column), "sortOrder": order.title(), } ] def _get_strategy(self, id_column): is_lookup = self._is_lookup(id_column) if is_lookup: self.sort_by = (id_column, "Asc") self.report_filters = [(id_column, ">", "")] self.increment_boolean_filter() return self._filter_by_sorting return self._filter_past_values def _is_lookup(self, column): return self.get_column_info_by_label(column, "isLookup") def _filter_past_values(self, df, id_column): new_filter = (id_column, "!=", df[id_column]) self.report_filters = [new_filter] self.increment_boolean_filter() def _filter_by_sorting(self, df, id_column): last_value = df[id_column].iat[-1] self.report_filters[-1]["value"] = utils.surround_with_quotes(last_value)
/helpers/metadata.py
0.727685
0.203708
metadata.py
pypi
import re from . import parsers from dateutil import parser operators_dict = { "==": "equals", "!=": "notEqual", ">": "greaterThan", "<": "lessThan", ">=": "greaterOrEqual", "<=": "lessOrEqual", "contains": "contains", "not contains": "notContain", "startswith": "startsWith", } def set_filters(filters, metadata): """Append each filter in a list of filter to report metadata.""" for filter_ in filters: column, operator, value = filter_ filter_dict = { "column": parsers.get_columns_labels(metadata)[column], "operator": operators_dict.get(operator), "value": value, } metadata["reportMetadata"]["reportFilters"].append(filter_dict) def update_filter(index, key, value, metadata): """Update an arbitrary filter key-value pair in a list of filters.""" metadata["reportMetadata"]["reportFilters"][index][key] = value def increment_logical_filter(metadata): """Increment logical filter by an additional column. This is used to avoid an error being thrown when we filter by an identifier column without including it in the filter logic. """ logic = metadata["reportMetadata"]["reportBooleanFilter"] if logic: # get last number, for example, get 3 in '(1 AND (2 OR 3))' last_number = re.search(r"(\d+)\)*$", logic).group(1) # turn filter into '(1 AND (2 OR 3)) AND 4' new_logic = logic + " AND {}".format(int(last_number) + 1) metadata["reportMetadata"]["reportBooleanFilter"] = new_logic def set_logic(logic, metadata): """Set logical filter value.""" metadata["reportMetadata"]["reportBooleanFilter"] = logic def set_period(start, end, column, metadata): """Set date-related filters parameters.""" date_filter = metadata["reportMetadata"]["standardDateFilter"] date_filter["durationValue"] = "CUSTOM" if column: date_filter["column"] = parsers.get_columns_labels(metadata)[column] if start: date_filter["startDate"] = parser.parse(start, dayfirst=True).strftime( "%Y-%m-%d" ) if end: date_filter["endDate"] = parser.parse(end, dayfirst=True).strftime("%Y-%m-%d")
/helpers/sf_filters.py
0.65368
0.459076
sf_filters.py
pypi
import functools import pandas as pd from ..helpers import parsers from ..helpers.report_filters import update_filter, set_filters, increment_logical_filter URL = "https://{}/services/data/v{}/analytics/reports/{}" def report_generator(get_report): """Decorator function to yield reports (as a DataFrame) until the allData item of the response body is 'true', which eventually will be because we filter out already seen values of a specified row-identifier column. It then concatenates and returns all generated DataFrame. If an id_column is not provided or if the report is less than 2000 rows, then there is nothing that could be done. """ def generator(report_id, id_column, metadata, salesforce, **kwargs): """Request reports until allData is true by filtering them iteratively.""" url = salesforce.url + report_id report, report_cells, indices = get_report(url, metadata, salesforce, **kwargs) columns = parsers.get_columns(report) df = pd.DataFrame(report_cells, index=indices, columns=columns) yield df if id_column: already_seen = ",".join(df[id_column].values) set_filters([(id_column, "!=", already_seen)], metadata) increment_logical_filter(metadata) while not report["allData"]: # getting what is needed to build the dataframe report, report_cells, indices = get_report( url, metadata, salesforce, **kwargs ) df = pd.DataFrame(report_cells, index=indices, columns=columns) yield df # filtering out already seen values for the next report already_seen += ",".join(df[id_column].values) update_filter( index=-1, key="value", value=already_seen, metadata=metadata ) @functools.wraps(get_report) def concat(*args, **kwargs): kwargs.setdefault("params", {"includeDetails": "true"}) df = pd.concat(generator(*args, **kwargs)) if not isinstance(df.index, pd.MultiIndex): df = df.reset_index(drop=True) return df return concat
/helpers/generators.py
0.632049
0.26731
generators.py
pypi
from __future__ import absolute_import, division from copy import copy from functools import partial from .auto import tqdm as tqdm_auto try: import keras except ImportError as e: try: from tensorflow import keras except ImportError: raise e __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TqdmCallback'] class TqdmCallback(keras.callbacks.Callback): """`keras` callback for epoch and batch progress""" @staticmethod def bar2callback(bar, pop=None, delta=(lambda logs: 1)): def callback(_, logs=None): n = delta(logs) if logs: if pop: logs = copy(logs) [logs.pop(i, 0) for i in pop] bar.set_postfix(logs, refresh=False) bar.update(n) return callback def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1, tqdm_class=tqdm_auto, **tqdm_kwargs): """ Parameters ---------- epochs : int, optional data_size : int, optional Number of training pairs. batch_size : int, optional Number of training pairs per batch. verbose : int 0: epoch, 1: batch (transient), 2: batch. [default: 1]. Will be set to `0` unless both `data_size` and `batch_size` are given. tqdm_class : optional `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. tqdm_kwargs : optional Any other arguments used for all bars. """ if tqdm_kwargs: tqdm_class = partial(tqdm_class, **tqdm_kwargs) self.tqdm_class = tqdm_class self.epoch_bar = tqdm_class(total=epochs, unit='epoch') self.on_epoch_end = self.bar2callback(self.epoch_bar) if data_size and batch_size: self.batches = batches = (data_size + batch_size - 1) // batch_size else: self.batches = batches = None self.verbose = verbose if verbose == 1: self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False) self.on_batch_end = self.bar2callback( self.batch_bar, pop=['batch', 'size'], delta=lambda logs: logs.get('size', 1)) def on_train_begin(self, *_, **__): params = self.params.get auto_total = params('epochs', params('nb_epoch', None)) if auto_total is not None: self.epoch_bar.reset(total=auto_total) def on_epoch_begin(self, *_, **__): if self.verbose: params = self.params.get total = params('samples', params( 'nb_sample', params('steps', None))) or self.batches if self.verbose == 2: if hasattr(self, 'batch_bar'): self.batch_bar.close() self.batch_bar = self.tqdm_class( total=total, unit='batch', leave=True, unit_scale=1 / (params('batch_size', 1) or 1)) self.on_batch_end = self.bar2callback( self.batch_bar, pop=['batch', 'size'], delta=lambda logs: logs.get('size', 1)) elif self.verbose == 1: self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1) self.batch_bar.reset(total=total) else: raise KeyError('Unknown verbosity') def on_train_end(self, *_, **__): if self.verbose: self.batch_bar.close() self.epoch_bar.close() def display(self): """displays in the current cell in Notebooks""" container = getattr(self.epoch_bar, 'container', None) if container is None: return from .notebook import display display(container) batch_bar = getattr(self, 'batch_bar', None) if batch_bar is not None: display(batch_bar.container) @staticmethod def _implements_train_batch_hooks(): return True @staticmethod def _implements_test_batch_hooks(): return True @staticmethod def _implements_predict_batch_hooks(): return True
/reportio-0.3.5.tar.gz/reportio-0.3.5/future/tqdm/keras.py
0.815673
0.157914
keras.py
pypi
from __future__ import absolute_import from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange'] class FractionColumn(ProgressColumn): """Renders completed/total, e.g. '0.5/2.3 G'.""" def __init__(self, unit_scale=False, unit_divisor=1000): self.unit_scale = unit_scale self.unit_divisor = unit_divisor super().__init__() def render(self, task): """Calculate common unit for completed and total.""" completed = int(task.completed) total = int(task.total) if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( total, ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], self.unit_divisor, ) else: unit, suffix = filesize.pick_unit_and_suffix(total, [""], 1) precision = 0 if unit == 1 else 1 return Text( f"{completed/unit:,.{precision}f}/{total/unit:,.{precision}f} {suffix}", style="progress.download") class RateColumn(ProgressColumn): """Renders human readable transfer speed.""" def __init__(self, unit="", unit_scale=False, unit_divisor=1000): self.unit = unit self.unit_scale = unit_scale self.unit_divisor = unit_divisor super().__init__() def render(self, task): """Show data transfer speed.""" speed = task.speed if speed is None: return Text(f"? {self.unit}/s", style="progress.data.speed") if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( speed, ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], self.unit_divisor, ) else: unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1) precision = 0 if unit == 1 else 1 return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s", style="progress.data.speed") class tqdm_rich(std_tqdm): # pragma: no cover """ Experimental rich.progress GUI version of tqdm! """ # TODO: @classmethod: write()? def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`. Parameters ---------- progress : tuple, optional arguments for `rich.progress.Progress()`. """ kwargs = kwargs.copy() kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) progress = kwargs.pop('progress', None) super(tqdm_rich, self).__init__(*args, **kwargs) if self.disable: return warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) d = self.format_dict if progress is None: progress = ( "[progress.description]{task.description}" "[progress.percentage]{task.percentage:>4.0f}%", BarColumn(bar_width=None), FractionColumn( unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), "[", TimeElapsedColumn(), "<", TimeRemainingColumn(), ",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), "]" ) self._prog = Progress(*progress, transient=not self.leave) self._prog.__enter__() self._task_id = self._prog.add_task(self.desc or "", **d) def close(self, *args, **kwargs): if self.disable: return super(tqdm_rich, self).close(*args, **kwargs) self._prog.__exit__(None, None, None) def clear(self, *_, **__): pass def display(self, *_, **__): if not hasattr(self, '_prog'): return self._prog.update(self._task_id, completed=self.n, description=self.desc) def reset(self, total=None): """ Resets to 0 iterations for repeated use. Parameters ---------- total : int or float, optional. Total to use for the new bar. """ if hasattr(self, '_prog'): self._prog.reset(total=total) super(tqdm_rich, self).reset(total=total) def trrange(*args, **kwargs): """ A shortcut for `tqdm.rich.tqdm(xrange(*args), **kwargs)`. On Python3+, `range` is used instead of `xrange`. """ return tqdm_rich(_range(*args), **kwargs) # Aliases tqdm = tqdm_rich trange = trrange
/reportio-0.3.5.tar.gz/reportio-0.3.5/future/tqdm/rich.py
0.759493
0.233062
rich.py
pypi
import sys from functools import wraps from tqdm import tqdm from tqdm.auto import tqdm as tqdm_auto from tqdm.utils import ObjectWrapper __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tenumerate', 'tzip', 'tmap'] class DummyTqdmFile(ObjectWrapper): """Dummy file-like that will write to tqdm""" def __init__(self, wrapped): super(DummyTqdmFile, self).__init__(wrapped) self._buf = [] def write(self, x, nolock=False): nl = b"\n" if isinstance(x, bytes) else "\n" pre, sep, post = x.rpartition(nl) if sep: blank = type(nl)() tqdm.write(blank.join(self._buf + [pre, sep]), end=blank, file=self._wrapped, nolock=nolock) self._buf = [post] else: self._buf.append(x) def __del__(self): if self._buf: blank = type(self._buf[0])() try: tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped) except (OSError, ValueError): pass def builtin_iterable(func): """Wraps `func()` output in a `list()` in py2""" if sys.version_info[:1] < (3,): @wraps(func) def inner(*args, **kwargs): return list(func(*args, **kwargs)) return inner return func def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs): """ Equivalent of `numpy.ndenumerate` or builtin `enumerate`. Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ try: import numpy as np except ImportError: pass else: if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size, **tqdm_kwargs) return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start) @builtin_iterable def tzip(iter1, *iter2plus, **tqdm_kwargs): """ Equivalent of builtin `zip`. Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ kwargs = tqdm_kwargs.copy() tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) for i in zip(tqdm_class(iter1, **tqdm_kwargs), *iter2plus): yield i @builtin_iterable def tmap(function, *sequences, **tqdm_kwargs): """ Equivalent of builtin `map`. Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ for i in tzip(*sequences, **tqdm_kwargs): yield function(*i)
/reportio-0.3.5.tar.gz/reportio-0.3.5/future/tqdm/contrib/__init__.py
0.512205
0.163279
__init__.py
pypi
__version__='3.3.0' __doc__=""" PDFPathObject is an efficient way to draw paths on a Canvas. Do not instantiate directly, obtain one from the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py """ from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: """Represents a graphic path. There are certain 'modes' to PDF drawing, and making a separate object to expose Path operations ensures they are completed with no run-time overhead. Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes; and then add it back into the canvas with one of the relevant operators. Path objects are probably not long, so we pack onto one line the code argument allows a canvas to get the operations appended directly so avoiding the final getCode """ def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path must start with a moveto or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self): "pack onto one line; used internally" return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): """Contributed to piddlePDF by Robert Kern, 28/7/99. Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2. The algorithm is an elliptical generalization of the formulae in Jim Fitzsimmon's TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): """Like arc, but draws a line from the current point to the start if the start is not the current point.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width, height): """Adds a rectangle to the path""" self._code_append('%s re' % fp_str((x, y, width, height))) def ellipse(self, x, y, width, height): """adds an ellipse to the path""" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): """adds a circle to the path""" x1 = x_cen - r y1 = y_cen - r width = height = 2*r self.ellipse(x1, y1, width, height) def roundRect(self, x, y, width, height, radius): """Draws a rectangle with rounded corners. The corners are approximately quadrants of a circle, with the given radius.""" #use a precomputed set of factors for the bezier approximation #to a circle. There are six relevant points on the x axis and y axis. #sketch them and it should all make sense! m = 0.4472 #radius multiplier xhi = x,x+width xlo, xhi = min(xhi), max(xhi) yhi = y,y+height ylo, yhi = min(yhi), max(yhi) if isinstance(radius,(list,tuple)): r = [max(0,r) for r in radius] if len(r)<4: r += (4-len(r))*[0] self.moveTo(xlo + r[2], ylo) #start at bottom left self.lineTo(xhi - r[3], ylo) #bottom row if r[3]>0: t = m*r[3] self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + r[3]) #bottom right self.lineTo(xhi, yhi - r[1]) #right edge if r[1]>0: t = m*r[1] self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - r[1], yhi) #top right self.lineTo(xlo + r[0], yhi) #top row if r[0]>0: t = m*r[0] self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - r[0]) #top left self.lineTo(xlo, ylo + r[2]) #left edge if r[2]>0: t = m*r[2] self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + r[2], ylo) #bottom left # 4 radii top left top right bittom left bottom right else: t = m * radius self.moveTo(xlo + radius, ylo) self.lineTo(xhi - radius, ylo) #bottom row self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + radius) #bottom right self.lineTo(xhi, yhi - radius) #right edge self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - radius, yhi) #top right self.lineTo(xlo + radius, yhi) #top row self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - radius) #top left self.lineTo(xlo, ylo + radius) #left edge self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + radius, ylo) #bottom left self.close() def close(self): "draws a line back to where it started" self._code_append('h')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfgen/pathobject.py
0.817611
0.594963
pathobject.py
pypi
__version__='3.3.0' __doc__=""" This module includes any mathematical methods needed for PIDDLE. It should have no dependencies beyond the Python library. So far, just Robert Kern's bezierArc. """ from math import sin, cos, pi, ceil def bezierArc(x1,y1, x2,y2, startAng=0, extent=90): """bezierArc(x1,y1, x2,y2, startAng=0, extent=90) --> List of Bezier curve control points. (x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The coordinate system has coordinates that increase to the right and down. Angles, measured in degress, start with 0 to the right (the positive X axis) and increase counter-clockwise. The arc extends from startAng to startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down semi-circle. The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4) such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and (x3, y3) as their respective Bezier control points.""" x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2) if abs(extent) <= 90: arcList = [startAng] fragAngle = float(extent) Nfrag = 1 else: arcList = [] Nfrag = int(ceil(abs(extent)/90.)) fragAngle = float(extent) / Nfrag x_cen = (x1+x2)/2. y_cen = (y1+y2)/2. rx = (x2-x1)/2. ry = (y2-y1)/2. halfAng = fragAngle * pi / 360. kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng)) if fragAngle < 0: sign = -1 else: sign = 1 pointList = [] for i in range(Nfrag): theta0 = (startAng + i*fragAngle) * pi / 180. theta1 = (startAng + (i+1)*fragAngle) *pi / 180. if fragAngle > 0: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) - kappa * sin(theta0)), y_cen - ry * (sin(theta0) + kappa * cos(theta0)), x_cen + rx * (cos(theta1) + kappa * sin(theta1)), y_cen - ry * (sin(theta1) - kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) else: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) + kappa * sin(theta0)), y_cen - ry * (sin(theta0) - kappa * cos(theta0)), x_cen + rx * (cos(theta1) - kappa * sin(theta1)), y_cen - ry * (sin(theta1) + kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) return pointList
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfgen/pdfgeom.py
0.863765
0.635534
pdfgeom.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py
0.563858
0.221035
_fontdata_widths_helveticaboldoblique.py
pypi
SymbolEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent', 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus', 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi', 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex', 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho', 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', 'braceleft', 'bar', 'braceright', 'similar', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Euro', 'Upsilon1', 'minute', 'lessequal', 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree', 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional', 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence', 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn', 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply', 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset', 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element', 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif', 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot', 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup', 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp', 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex', 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex', None, 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', 'bracerightbt', None)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_enc_symbol.py
0.621311
0.246998
_fontdata_enc_symbol.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courieroblique.py
0.620277
0.171338
_fontdata_widths_courieroblique.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courierbold.py
0.620277
0.171338
_fontdata_widths_courierbold.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courier.py
0.620277
0.171338
_fontdata_widths_courier.py
pypi
from reportlab.pdfbase.pdfdoc import PDFString, PDFStream, PDFDictionary, PDFName, PDFObject from reportlab.lib.colors import obj_R_G_B #==========================public interfaces def textFieldAbsolute(canvas, title, x, y, width, height, value="", maxlen=1000000, multiline=0): """Place a text field on the current page with name title at ABSOLUTE position (x,y) with dimensions (width, height), using value as the default value and maxlen as the maximum permissible length. If multiline is set make it a multiline field. """ theform = getForm(canvas) return theform.textField(canvas, title, x, y, x+width, y+height, value, maxlen, multiline) def textFieldRelative(canvas, title, xR, yR, width, height, value="", maxlen=1000000, multiline=0): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return textFieldAbsolute(canvas, title, xA, yA, width, height, value, maxlen, multiline) def buttonFieldAbsolute(canvas, title, value, x, y, width=16.7704, height=14.907): """Place a check button field on the current page with name title and default value value (one of "Yes" or "Off") at ABSOLUTE position (x,y). """ theform = getForm(canvas) return theform.buttonField(canvas, title, value, x, y, width=width, height=height) def buttonFieldRelative(canvas, title, value, xR, yR, width=16.7704, height=14.907): "same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return buttonFieldAbsolute(canvas, title, value, xA, yA, width=width, height=height) def selectFieldAbsolute(canvas, title, value, options, x, y, width, height): """Place a select field (drop down list) on the current page with name title and with options listed in the sequence options default value value (must be one of options) at ABSOLUTE position (x,y) with dimensions (width, height).""" theform = getForm(canvas) theform.selectField(canvas, title, value, options, x, y, x+width, y+height) def selectFieldRelative(canvas, title, value, options, xR, yR, width, height): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return selectFieldAbsolute(canvas, title, value, options, xA, yA, width, height) #==========================end of public interfaces from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf def getForm(canvas): "get form from canvas, create the form if needed" try: return canvas.AcroForm except AttributeError: theform = canvas.AcroForm = AcroForm() # install the form in the document d = canvas._doc cat = d._catalog cat.AcroForm = theform return theform class AcroForm(PDFObject): def __init__(self): self.fields = [] def textField(self, canvas, title, xmin, ymin, xmax, ymax, value="", maxlen=1000000, multiline=0): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen, font, fontsize, R, G, B, multiline) self.fields.append(field) canvas._addAnnotation(field) def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font=font, fontsize=fontsize, R=R, G=G, B=B) self.fields.append(field) canvas._addAnnotation(field) def buttonField(self, canvas, title, value, xmin, ymin, width=16.7704, height=14.907): # determine the page ref doc = canvas._doc page = doc.thisPageRef() field = ButtonField(title, value, xmin, ymin, page, width=width, height=height) self.fields.append(field) canvas._addAnnotation(field) def format(self, document): from reportlab.pdfbase.pdfdoc import PDFArray proxy = PDFPattern(FormPattern, Resources=getattr(self,'resources',None) or FormResources(), NeedAppearances=getattr(self,'needAppearances','false'), fields=PDFArray(self.fields), SigFlags=getattr(self,'sigFlags',0)) return proxy.format(document) FormPattern = [ '<<\r\n', '/NeedAppearances ',['NeedAppearances'],'\r\n' '/DA ', PDFString('/Helv 0 Tf 0 g '), '\r\n', '/DR ',["Resources"],'\r\n', '/Fields ', ["fields"],'\r\n', PDFPatternIf('SigFlags',['\r\n/SigFlags ',['SigFlags']]), '>>' ] def FormFontsDictionary(): from reportlab.pdfbase.pdfdoc import PDFDictionary fontsdictionary = PDFDictionary() fontsdictionary.__RefOnly__ = 1 for fullname, shortname in FORMFONTNAMES.items(): fontsdictionary[shortname] = FormFont(fullname, shortname) fontsdictionary["ZaDb"] = PDFPattern(ZaDbPattern) return fontsdictionary def FormResources(): return PDFPattern(FormResourcesDictionaryPattern, Encoding=PDFPattern(EncodingPattern,PDFDocEncoding=PDFPattern(PDFDocEncodingPattern)), Font=FormFontsDictionary()) ZaDbPattern = [ ' <<' ' /BaseFont' ' /ZapfDingbats' ' /Name' ' /ZaDb' ' /Subtype' ' /Type1' ' /Type' ' /Font' '>>'] FormResourcesDictionaryPattern = [ '<<', ' /Encoding ', ["Encoding"], '\r\n', ' /Font ', ["Font"], '\r\n', '>>' ] FORMFONTNAMES = { "Helvetica": "Helv", "Helvetica-Bold": "HeBo", 'Courier': "Cour", 'Courier-Bold': "CoBo", 'Courier-Oblique': "CoOb", 'Courier-BoldOblique': "CoBO", 'Helvetica-Oblique': "HeOb", 'Helvetica-BoldOblique': "HeBO", 'Times-Roman': "Time", 'Times-Bold': "TiBo", 'Times-Italic': "TiIt", 'Times-BoldItalic': "TiBI", } EncodingPattern = [ '<<', ' /PDFDocEncoding ', ["PDFDocEncoding"], '\r\n', '>>', ] PDFDocEncodingPattern = [ '<<' ' /Differences' ' [' ' 24' ' /breve' ' /caron' ' /circumflex' ' /dotaccent' ' /hungarumlaut' ' /ogonek' ' /ring' ' /tilde' ' 39' ' /quotesingle' ' 96' ' /grave' ' 128' ' /bullet' ' /dagger' ' /daggerdbl' ' /ellipsis' ' /emdash' ' /endash' ' /florin' ' /fraction' ' /guilsinglleft' ' /guilsinglright' ' /minus' ' /perthousand' ' /quotedblbase' ' /quotedblleft' ' /quotedblright' ' /quoteleft' ' /quoteright' ' /quotesinglbase' ' /trademark' ' /fi' ' /fl' ' /Lslash' ' /OE' ' /Scaron' ' /Ydieresis' ' /Zcaron' ' /dotlessi' ' /lslash' ' /oe' ' /scaron' ' /zcaron' ' 160' ' /Euro' ' 164' ' /currency' ' 166' ' /brokenbar' ' 168' ' /dieresis' ' /copyright' ' /ordfeminine' ' 172' ' /logicalnot' ' /.notdef' ' /registered' ' /macron' ' /degree' ' /plusminus' ' /twosuperior' ' /threesuperior' ' /acute' ' /mu' ' 183' ' /periodcentered' ' /cedilla' ' /onesuperior' ' /ordmasculine' ' 188' ' /onequarter' ' /onehalf' ' /threequarters' ' 192' ' /Agrave' ' /Aacute' ' /Acircumflex' ' /Atilde' ' /Adieresis' ' /Aring' ' /AE' ' /Ccedilla' ' /Egrave' ' /Eacute' ' /Ecircumflex' ' /Edieresis' ' /Igrave' ' /Iacute' ' /Icircumflex' ' /Idieresis' ' /Eth' ' /Ntilde' ' /Ograve' ' /Oacute' ' /Ocircumflex' ' /Otilde' ' /Odieresis' ' /multiply' ' /Oslash' ' /Ugrave' ' /Uacute' ' /Ucircumflex' ' /Udieresis' ' /Yacute' ' /Thorn' ' /germandbls' ' /agrave' ' /aacute' ' /acircumflex' ' /atilde' ' /adieresis' ' /aring' ' /ae' ' /ccedilla' ' /egrave' ' /eacute' ' /ecircumflex' ' /edieresis' ' /igrave' ' /iacute' ' /icircumflex' ' /idieresis' ' /eth' ' /ntilde' ' /ograve' ' /oacute' ' /ocircumflex' ' /otilde' ' /odieresis' ' /divide' ' /oslash' ' /ugrave' ' /uacute' ' /ucircumflex' ' /udieresis' ' /yacute' ' /thorn' ' /ydieresis' ' ]' ' /Type' ' /Encoding' '>>'] def FormFont(BaseFont, Name): from reportlab.pdfbase.pdfdoc import PDFName return PDFPattern(FormFontPattern, BaseFont=PDFName(BaseFont), Name=PDFName(Name), Encoding=PDFPattern(PDFDocEncodingPattern)) FormFontPattern = [ '<<', ' /BaseFont ', ["BaseFont"], '\r\n', ' /Encoding ', ["Encoding"], '\r\n', ' /Name ', ["Name"], '\r\n', ' /Subtype ' ' /Type1 ' ' /Type ' ' /Font ' '>>' ] def resetPdfForm(): pass from reportlab.rl_config import register_reset register_reset(resetPdfForm) resetPdfForm() def TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen=1000000, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627, multiline=0): from reportlab.pdfbase.pdfdoc import PDFString, PDFName Flags = 0 if multiline: Flags = Flags | (1<<12) # bit 13 is at position 12 :) fontname = FORMFONTNAMES[font] return PDFPattern(TextFieldPattern, value=PDFString(value), maxlen=maxlen, page=page, title=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B, Flags=Flags) TextFieldPattern = [ '<<' ' /DA' ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)' ' /DV ', ["value"], '\r\n', ' /F 4 /FT /Tx' '/MK << /BC [ 0 0 0 ] >>' ' /MaxLen ', ["maxlen"], '\r\n', ' /P ', ["page"], '\r\n', ' /Rect ' ' [', ["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ]' '/Subtype /Widget' ' /T ', ["title"], '\r\n', ' /Type' ' /Annot' ' /V ', ["value"], '\r\n', ' /Ff ', ["Flags"],'\r\n', '>>'] def SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627): #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B) from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray if value not in options: raise ValueError("value %s must be one of options %s" % (repr(value), repr(options))) fontname = FORMFONTNAMES[font] optionstrings = list(map(PDFString, options)) optionarray = PDFArray(optionstrings) return PDFPattern(SelectFieldPattern, Options=optionarray, Selected=PDFString(value), Page=page, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B) SelectFieldPattern = [ '<< % a select list\r\n' ' /DA ', ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)\r\n', #' (/Helv 12 Tf 0 g)\r\n', ' /DV ', ["Selected"],'\r\n', ' /F ', ' 4\r\n', ' /FT ', ' /Ch\r\n', ' /MK ', ' <<', ' /BC', ' [', ' 0', ' 0', ' 0', ' ]', ' /BG', ' [', ' 1', ' 1', ' 1', ' ]', ' >>\r\n', ' /Opt ', ["Options"],'\r\n', ' /P ', ["Page"],'\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] \r\n', '/Subtype', ' /Widget\r\n', ' /T ', ["Name"],'\r\n', ' /Type ', ' /Annot', ' /V ', ["Selected"],'\r\n', '>>'] def ButtonField(title, value, xmin, ymin, page, width=16.7704, height=14.907): if value not in ("Yes", "Off"): raise ValueError("button value must be 'Yes' or 'Off': "+repr(value)) fontSize = (11.3086/14.907)*height dx = (3.6017/16.7704)*width dy = (3.3881/14.907)*height return PDFPattern(ButtonFieldPattern, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmin+width, ymax=ymin+width, Hide=PDFPattern(['<< /S /Hide >>']), APDOff=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f\r\n' % vars(), width=width, height=height), APDYes=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET\r\n' % vars(), width=width, height=height), APNYes=ButtonStream('q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET Q\r\n' % vars(), width=width, height=height), Value=PDFName(value), Page=page) ButtonFieldPattern = ['<< ', '/AA', ' <<', ' /D ', ["Hide"],'\r\n', #' %(imported.18.0)s', ' >> ', '/AP ', ' <<', ' /D', ' <<', ' /Off ', #' %(imported.40.0)s', ["APDOff"], '\r\n', ' /Yes ', #' %(imported.39.0)s', ["APDYes"], '\r\n', ' >>', '\r\n', ' /N', ' << ', ' /Yes ', #' %(imported.38.0)s', ["APNYes"], '\r\n', ' >>', ' >>\r\n', ' /AS ', ["Value"], '\r\n', ' /DA ', PDFString('/ZaDb 0 Tf 0 g'), '\r\n', '/DV ', ["Value"], '\r\n', '/F ', ' 4 ', '/FT ', ' /Btn ', '/H ', ' /T ', '/MK ', ' <<', ' /AC (\\376\\377)', #PDFString('\376\377'), ' /CA ', PDFString('4'), ' /RC ', PDFString('\376\377'), ' >> ','\r\n', '/P ', ["Page"], '\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] ','\r\n', '/Subtype', ' /Widget ', '/T ', ["Name"], '\r\n', '/Type', ' /Annot ', '/V ', ["Value"], '\r\n', ' >>'] def buttonStreamDictionary(width=16.7704, height=14.907): "everything except the length for the button appearance streams" result = PDFDictionary() result["SubType"] = "/Form" result["BBox"] = "[0 0 %(width)s %(height)s]" % vars() font = PDFDictionary() font["ZaDb"] = PDFPattern(ZaDbPattern) resources = PDFDictionary() resources["ProcSet"] = "[ /PDF /Text ]" resources["Font"] = font result["Resources"] = resources return result def ButtonStream(content, width=16.7704, height=14.907): result = PDFStream(buttonStreamDictionary(width=width,height=height), content) result.filters = [] return result
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/pdfform.py
0.613005
0.359772
pdfform.py
pypi
widths = {'A': 667, 'AE': 944, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 667, 'G': 722, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 667, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 889, 'X': 667, 'Y': 611, 'Yacute': 611, 'Ydieresis': 611, 'Z': 611, 'Zcaron': 611, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 570, 'asciitilde': 570, 'asterisk': 500, 'at': 832, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 220, 'braceleft': 348, 'braceright': 348, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 389, 'exclamdown': 389, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 570, 'logicalnot': 606, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 606, 'mu': 576, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 266, 'ordmasculine': 300, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 500, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 389, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 444, 'w': 667, 'x': 500, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py
0.560974
0.26389
_fontdata_widths_timesbolditalic.py
pypi
widths = {'A': 722, 'AE': 889, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 556, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 389, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 889, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 556, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 556, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 944, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 611, 'Zcaron': 611, 'a': 444, 'aacute': 444, 'acircumflex': 444, 'acute': 333, 'adieresis': 444, 'ae': 667, 'agrave': 444, 'ampersand': 778, 'aring': 444, 'asciicircum': 469, 'asciitilde': 541, 'asterisk': 500, 'at': 921, 'atilde': 444, 'b': 500, 'backslash': 278, 'bar': 200, 'braceleft': 480, 'braceright': 480, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 200, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 278, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 564, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 564, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 564, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 564, 'logicalnot': 564, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 564, 'mu': 500, 'multiply': 564, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 453, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 564, 'plusminus': 564, 'q': 500, 'question': 444, 'questiondown': 444, 'quotedbl': 408, 'quotedblbase': 444, 'quotedblleft': 444, 'quotedblright': 444, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 180, 'r': 333, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 278, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesroman.py
0.558568
0.184327
_fontdata_widths_timesroman.py
pypi
widths = {'Alpha': 722, 'Beta': 667, 'Chi': 722, 'Delta': 612, 'Epsilon': 611, 'Eta': 722, 'Euro': 750, 'Gamma': 603, 'Ifraktur': 686, 'Iota': 333, 'Kappa': 722, 'Lambda': 686, 'Mu': 889, 'Nu': 722, 'Omega': 768, 'Omicron': 722, 'Phi': 763, 'Pi': 768, 'Psi': 795, 'Rfraktur': 795, 'Rho': 556, 'Sigma': 592, 'Tau': 611, 'Theta': 741, 'Upsilon': 690, 'Upsilon1': 620, 'Xi': 645, 'Zeta': 611, 'aleph': 823, 'alpha': 631, 'ampersand': 778, 'angle': 768, 'angleleft': 329, 'angleright': 329, 'apple': 790, 'approxequal': 549, 'arrowboth': 1042, 'arrowdblboth': 1042, 'arrowdbldown': 603, 'arrowdblleft': 987, 'arrowdblright': 987, 'arrowdblup': 603, 'arrowdown': 603, 'arrowhorizex': 1000, 'arrowleft': 987, 'arrowright': 987, 'arrowup': 603, 'arrowvertex': 603, 'asteriskmath': 500, 'bar': 200, 'beta': 549, 'braceex': 494, 'braceleft': 480, 'braceleftbt': 494, 'braceleftmid': 494, 'bracelefttp': 494, 'braceright': 480, 'bracerightbt': 494, 'bracerightmid': 494, 'bracerighttp': 494, 'bracketleft': 333, 'bracketleftbt': 384, 'bracketleftex': 384, 'bracketlefttp': 384, 'bracketright': 333, 'bracketrightbt': 384, 'bracketrightex': 384, 'bracketrighttp': 384, 'bullet': 460, 'carriagereturn': 658, 'chi': 549, 'circlemultiply': 768, 'circleplus': 768, 'club': 753, 'colon': 278, 'comma': 250, 'congruent': 549, 'copyrightsans': 790, 'copyrightserif': 790, 'degree': 400, 'delta': 494, 'diamond': 753, 'divide': 549, 'dotmath': 250, 'eight': 500, 'element': 713, 'ellipsis': 1000, 'emptyset': 823, 'epsilon': 439, 'equal': 549, 'equivalence': 549, 'eta': 603, 'exclam': 333, 'existential': 549, 'five': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'gamma': 411, 'gradient': 713, 'greater': 549, 'greaterequal': 549, 'heart': 753, 'infinity': 713, 'integral': 274, 'integralbt': 686, 'integralex': 686, 'integraltp': 686, 'intersection': 768, 'iota': 329, 'kappa': 549, 'lambda': 549, 'less': 549, 'lessequal': 549, 'logicaland': 603, 'logicalnot': 713, 'logicalor': 603, 'lozenge': 494, 'minus': 549, 'minute': 247, 'mu': 576, 'multiply': 549, 'nine': 500, 'notelement': 713, 'notequal': 549, 'notsubset': 713, 'nu': 521, 'numbersign': 500, 'omega': 686, 'omega1': 713, 'omicron': 549, 'one': 500, 'parenleft': 333, 'parenleftbt': 384, 'parenleftex': 384, 'parenlefttp': 384, 'parenright': 333, 'parenrightbt': 384, 'parenrightex': 384, 'parenrighttp': 384, 'partialdiff': 494, 'percent': 833, 'period': 250, 'perpendicular': 658, 'phi': 521, 'phi1': 603, 'pi': 549, 'plus': 549, 'plusminus': 549, 'product': 823, 'propersubset': 713, 'propersuperset': 713, 'proportional': 713, 'psi': 686, 'question': 444, 'radical': 549, 'radicalex': 500, 'reflexsubset': 713, 'reflexsuperset': 713, 'registersans': 790, 'registerserif': 790, 'rho': 549, 'second': 411, 'semicolon': 278, 'seven': 500, 'sigma': 603, 'sigma1': 439, 'similar': 549, 'six': 500, 'slash': 278, 'space': 250, 'spade': 753, 'suchthat': 439, 'summation': 713, 'tau': 439, 'therefore': 863, 'theta': 521, 'theta1': 631, 'three': 500, 'trademarksans': 786, 'trademarkserif': 890, 'two': 500, 'underscore': 500, 'union': 768, 'universal': 713, 'upsilon': 576, 'weierstrass': 987, 'xi': 493, 'zero': 500, 'zeta': 494}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_symbol.py
0.650245
0.257549
_fontdata_widths_symbol.py
pypi
WinAnsiEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase', 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron', 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash', 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet', 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling', 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright', 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute', 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior', 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters', 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis', 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn', 'ydieresis')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_enc_winansi.py
0.540439
0.153644
_fontdata_enc_winansi.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py
0.620277
0.171338
_fontdata_widths_courierboldoblique.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helvetica.py
0.572245
0.290893
_fontdata_widths_helvetica.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 778, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 778, 'L': 667, 'Lslash': 667, 'M': 944, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 611, 'Q': 778, 'R': 722, 'S': 556, 'Scaron': 556, 'T': 667, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 1000, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 667, 'Zcaron': 667, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 833, 'aring': 500, 'asciicircum': 581, 'asciitilde': 520, 'asterisk': 500, 'at': 930, 'atilde': 500, 'b': 556, 'backslash': 278, 'bar': 220, 'braceleft': 394, 'braceright': 394, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 556, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 556, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 333, 'k': 556, 'l': 278, 'less': 570, 'logicalnot': 570, 'lslash': 278, 'm': 833, 'macron': 333, 'minus': 570, 'mu': 556, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 300, 'ordmasculine': 330, 'oslash': 500, 'otilde': 500, 'p': 556, 'paragraph': 540, 'parenleft': 333, 'parenright': 333, 'percent': 1000, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 556, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 444, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 333, 'thorn': 556, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesbold.py
0.5564
0.181953
_fontdata_widths_timesbold.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticabold.py
0.563858
0.221035
_fontdata_widths_helveticabold.py
pypi
widths = {'A': 611, 'AE': 889, 'Aacute': 611, 'Acircumflex': 611, 'Adieresis': 611, 'Agrave': 611, 'Aring': 611, 'Atilde': 611, 'B': 611, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 444, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 667, 'Ntilde': 667, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 611, 'S': 500, 'Scaron': 500, 'T': 556, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 611, 'W': 833, 'X': 611, 'Y': 556, 'Yacute': 556, 'Ydieresis': 556, 'Z': 556, 'Zcaron': 556, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 667, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 422, 'asciitilde': 541, 'asterisk': 500, 'at': 920, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 275, 'braceleft': 400, 'braceright': 400, 'bracketleft': 389, 'bracketright': 389, 'breve': 333, 'brokenbar': 275, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 675, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 889, 'emdash': 889, 'endash': 500, 'equal': 675, 'eth': 500, 'exclam': 333, 'exclamdown': 389, 'f': 278, 'fi': 500, 'five': 500, 'fl': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 675, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 444, 'l': 278, 'less': 675, 'logicalnot': 675, 'lslash': 278, 'm': 722, 'macron': 333, 'minus': 675, 'mu': 500, 'multiply': 675, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 667, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 523, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 675, 'plusminus': 675, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 420, 'quotedblbase': 556, 'quotedblleft': 556, 'quotedblright': 556, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 214, 'r': 389, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 444, 'w': 667, 'x': 444, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesitalic.py
0.546496
0.215516
_fontdata_widths_timesitalic.py
pypi
MacRomanEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', None, 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', None, 'AE', 'Oslash', None, 'plusminus', None, None, 'yen', 'mu', None, None, None, None, None, 'ordfeminine', 'ordmasculine', None, 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', None, 'florin', None, None, 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', None, 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', None, 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_enc_macroman.py
0.529263
0.177401
_fontdata_enc_macroman.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py
0.572245
0.290893
_fontdata_widths_helveticaoblique.py
pypi
from reportlab.platypus.flowables import Flowable from reportlab.lib.units import inch from string import ascii_lowercase, ascii_uppercase, digits as string_digits class Barcode(Flowable): """Abstract Base for barcodes. Includes implementations of some methods suitable for the more primitive barcode types""" fontName = 'Courier' fontSize = 12 humanReadable = 0 def _humanText(self): return self.encoded def __init__(self, value='',**kwd): self.value = str(value) self._setKeywords(**kwd) if not hasattr(self, 'gap'): self.gap = None def _calculate(self): self.validate() self.encode() self.decompose() self.computeSize() def _setKeywords(self,**kwd): for (k, v) in kwd.items(): setattr(self, k, v) def validate(self): self.valid = 1 self.validated = self.value def encode(self): self.encoded = self.validated def decompose(self): self.decomposed = self.encoded def computeSize(self, *args): barWidth = self.barWidth wx = barWidth * self.ratio if self.gap == None: self.gap = barWidth w = 0.0 for c in self.decomposed: if c in 'sb': w = w + barWidth elif c in 'SB': w = w + wx else: # 'i' w = w + self.gap if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.bearers: self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def width(self): self._calculate() return self._width width = property(width) def height(self): self._calculate() return self._height height = property(height) def draw(self): self._calculate() barWidth = self.barWidth wx = barWidth * self.ratio left = self.quiet and self.lquiet or 0 b = self.bearers * barWidth bb = b * 0.5 tb = self.barHeight - (b * 1.5) for c in self.decomposed: if c == 'i': left = left + self.gap elif c == 's': left = left + barWidth elif c == 'S': left = left + wx elif c == 'b': self.rect(left, bb, barWidth, tb) left = left + barWidth elif c == 'B': self.rect(left, bb, wx, tb) left = left + wx if self.bearers: if getattr(self,'bearerBox', None): canv = self.canv if hasattr(canv,'_Gadd'): #this is a widget rect takes other arguments canv.rect(bb, bb, self.width, self.barHeight-b, strokeWidth=b, strokeColor=self.barFillColor or self.barStrokeColor, fillColor=None) else: canv.saveState() canv.setLineWidth(b) canv.rect(bb, bb, self.width, self.barHeight-b, stroke=1, fill=0) canv.restoreState() else: w = self._width - (self.lquiet + self.rquiet) self.rect(self.lquiet, 0, w, b) self.rect(self.lquiet, self.barHeight - b, w, b) self.drawHumanReadable() def drawHumanReadable(self): if self.humanReadable: #we have text from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth s = str(self._humanText()) fontSize = self.fontSize fontName = self.fontName w = stringWidth(s,fontName,fontSize) width = self._width if self.quiet: width -= self.lquiet+self.rquiet x = self.lquiet else: x = 0 if w>width: fontSize *= width/float(w) y = 1.07*getAscent(fontName)*fontSize/1000. self.annotate(x+width/2.,-y,s,fontName,fontSize) def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): canv = self.canv canv.saveState() canv.setFont(self.fontName,fontSize) if anchor=='middle': func = 'drawCentredString' elif anchor=='end': func = 'drawRightString' else: func = 'drawString' getattr(canv,func)(x,y,text) canv.restoreState() def _checkVal(self, name, v, allowed): if v not in allowed: raise ValueError('%s attribute %s is invalid %r\nnot in allowed %r' % ( self.__class__.__name__, name, v, allowed)) return v class MultiWidthBarcode(Barcode): """Base for variable-bar-width codes like Code93 and Code128""" def computeSize(self, *args): barWidth = self.barWidth oa, oA = ord('a') - 1, ord('A') - 1 w = 0.0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: w = w + barWidth * (oc - oa) elif c in ascii_uppercase: w = w + barWidth * (oc - oA) if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def draw(self): self._calculate() oa, oA = ord('a') - 1, ord('A') - 1 barWidth = self.barWidth left = self.quiet and self.lquiet or 0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: left = left + (oc - oa) * barWidth elif c in ascii_uppercase: w = (oc - oA) * barWidth self.rect(left, 0, w, self.barHeight) left += w self.drawHumanReadable() class I2of5(Barcode): """ Interleaved 2 of 5 is a numeric-only barcode. It encodes an even number of digits; if an odd number is given, a 0 is prepended. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Whether to compute and include the check digit bearers (float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on). bearerBox (bool default False) if true draw a true rectangle of width bearers around the barcode. quiet (bool, default 1): Whether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Interleaved 2 of 5: http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html http://www.adams1.com/pub/russadam/i25code.html Official Spec, "ANSI/AIM BC2-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { 'start' : 'bsbs', 'stop' : 'Bsb', 'B0' : 'bbBBb', 'S0' : 'ssSSs', 'B1' : 'BbbbB', 'S1' : 'SsssS', 'B2' : 'bBbbB', 'S2' : 'sSssS', 'B3' : 'BBbbb', 'S3' : 'SSsss', 'B4' : 'bbBbB', 'S4' : 'ssSsS', 'B5' : 'BbBbb', 'S5' : 'SsSss', 'B6' : 'bBBbb', 'S6' : 'sSSss', 'B7' : 'bbbBB', 'S7' : 'sssSS', 'B8' : 'BbbBb', 'S8' : 'SssSs', 'B9' : 'bBbBb', 'S9' : 'sSsSs' } barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 3.0 bearerBox = False quiet = 1 lquiet = None rquiet = None stop = 1 def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated cs = self.checksum c = len(s) #ensure len(result)%2 == 0, checksum included if ((c % 2 == 0) and cs) or ((c % 2 == 1) and not cs): s = '0' + s c += 1 if cs: c = 3*sum([int(s[i]) for i in range(0,c,2)])+sum([int(s[i]) for i in range(1,c,2)]) s += str((10 - c) % 10) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] a = dval.append for i in range(0, len(self.encoded), 2): b = self.patterns['B' + self.encoded[i]] s = self.patterns['S' + self.encoded[i+1]] for i in range(0, len(b)): a(b[i] + s[i]) if self.stop: a(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class MSI(Barcode): """ MSI is a numeric-only barcode. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidths. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on MSI Bar Code: http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html http://www.adams1.com/pub/russadam/plessy.html """ patterns = { 'start' : 'Bs', 'stop' : 'bSb', '0' : 'bSbSbSbS', '1' : 'bSbSbSBs', '2' : 'bSbSBsbS', '3' : 'bSbSBsBs', '4' : 'bSBsbSbS', '5' : 'bSBsbSBs', '6' : 'bSBsBsbS', '7' : 'bSBsBsBs', '8' : 'BsbSbSbS', '9' : 'BsbSbSBs' } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value="", **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated if self.checksum: c = '' for i in range(1, len(s), 2): c = c + s[i] d = str(int(c) * 2) t = 0 for c in d: t = t + int(c) for i in range(0, len(s), 2): t = t + int(s[i]) c = 10 - (t % 10) s = s + str(c) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] dval += [self.patterns[c] for c in self.encoded] if self.stop: dval.append(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class Codabar(Barcode): """ Codabar is a numeric plus some puntuation ("-$:/.+") barcode with four start/stop characters (A, B, C, and D). Options that may be passed to constructor: value (string required.): The value to encode. barWidth (float, default .0065): X-Dimension, or width of the smallest element minimum is 6.5 mils (.0065 inch) ratio (float, default 2.0): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 0): Whether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Whether to include quiet zones in the symbol. stop (bool, default 1): Whether to include start/stop symbols. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Codabar http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html http://www.barcodeman.com/codabar.html Official Spec, "ANSI/AIM BC3-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB', '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb', '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb', '9': 'BsbSbsb', '-': 'bsbSBsb', '$': 'bsBSbsb', ':': 'BsbsBsB', '/': 'BsBsbsB', '.': 'BsBsBsb', '+': 'bsBsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB', 'C': 'bsbSbSB', 'D': 'bsbSBSb' } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, '$' : 11, ':' : 12, '/' : 13, '.' : 14, '+' : 15, 'A' : 16, 'B' : 17, 'C' : 18, 'D' : 19 } chars = string_digits + "-$:/.+" stop = 1 barHeight = None barWidth = inch * 0.0065 ratio = 2.0 # XXX ? checksum = 0 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: if ((i != 0) and (i != len(s) - 1)) or (c not in 'ABCD'): self.Valid = 0 continue vval = vval + c if self.stop: if vval[0] not in 'ABCD': vval = 'A' + vval if vval[-1] not in 'ABCD': vval = vval + vval[0] self.validated = vval return vval def encode(self): s = self.validated if self.checksum: v = sum([self.values[c] for c in s]) s += self.chars[v % 16] self.encoded = s def decompose(self): dval = ''.join([self.patterns[c]+'i' for c in self.encoded]) self.decomposed = dval[:-1] return self.decomposed class Code11(Barcode): """ Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus dash ("-"). 11 characters total, hence the name. value (int or string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2. bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Code 11: http://www.cwi.nl/people/dik/english/codes/barcodes.html """ chars = '0123456789-' patterns = { '0' : 'bsbsB', '1' : 'BsbsB', '2' : 'bSbsB', '3' : 'BSbsb', '4' : 'bsBsB', '5' : 'BsBsb', '6' : 'bSBsb', '7' : 'bsbSB', '8' : 'BsbSb', '9' : 'Bsbsb', '-' : 'bsBsb', 'S' : 'bsBSb' # Start/Stop } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 # XXX ? checksum = -1 # Auto bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: self.Valid = 0 continue vval = vval + c self.validated = vval return vval def _addCSD(self,s,m): # compute first checksum i = c = 0 v = 1 V = self.values while i < len(s): c += v * V[s[-(i+1)]] i += 1 v += 1 if v==m: v = 1 return s+self.chars[c % 11] def encode(self): s = self.validated tcs = self.checksum if tcs<0: self.checksum = tcs = 1+int(len(s)>10) if tcs > 0: s = self._addCSD(s,11) if tcs > 1: s = self._addCSD(s,10) self.encoded = self.stop and ('S' + s + 'S') or s def decompose(self): self.decomposed = ''.join([(self.patterns[c]+'i') for c in self.encoded])[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/common.py
0.583085
0.304462
common.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import MultiWidthBarcode _patterns = { '0' : ('AcAaAb', 0), '1' : ('AaAbAc', 1), '2' : ('AaAcAb', 2), '3' : ('AaAdAa', 3), '4' : ('AbAaAc', 4), '5' : ('AbAbAb', 5), '6' : ('AbAcAa', 6), '7' : ('AaAaAd', 7), '8' : ('AcAbAa', 8), '9' : ('AdAaAa', 9), 'A' : ('BaAaAc', 10), 'B' : ('BaAbAb', 11), 'C' : ('BaAcAa', 12), 'D' : ('BbAaAb', 13), 'E' : ('BbAbAa', 14), 'F' : ('BcAaAa', 15), 'G' : ('AaBaAc', 16), 'H' : ('AaBbAb', 17), 'I' : ('AaBcAa', 18), 'J' : ('AbBaAb', 19), 'K' : ('AcBaAa', 20), 'L' : ('AaAaBc', 21), 'M' : ('AaAbBb', 22), 'N' : ('AaAcBa', 23), 'O' : ('AbAaBb', 24), 'P' : ('AcAaBa', 25), 'Q' : ('BaBaAb', 26), 'R' : ('BaBbAa', 27), 'S' : ('BaAaBb', 28), 'T' : ('BaAbBa', 29), 'U' : ('BbAaBa', 30), 'V' : ('BbBaAa', 31), 'W' : ('AaBaBb', 32), 'X' : ('AaBbBa', 33), 'Y' : ('AbBaBa', 34), 'Z' : ('AbCaAa', 35), '-' : ('AbAaCa', 36), '.' : ('CaAaAb', 37), ' ' : ('CaAbAa', 38), '$' : ('CbAaAa', 39), '/' : ('AaBaCa', 40), '+' : ('AaCaBa', 41), '%' : ('BaAaCa', 42), '#' : ('AbAbBa', 43), '!' : ('CaBaAa', 44), '=' : ('CaAaBa', 45), '&' : ('AbBbAa', 46), 'start' : ('AaAaDa', -1), 'stop' : ('AaAaDaA', -2) } _charsbyval = {} for k, v in _patterns.items(): _charsbyval[v[1]] = k _extended = { '\x00' : '!U', '\x01' : '#A', '\x02' : '#B', '\x03' : '#C', '\x04' : '#D', '\x05' : '#E', '\x06' : '#F', '\x07' : '#G', '\x08' : '#H', '\x09' : '#I', '\x0a' : '#J', '\x0b' : '#K', '\x0c' : '#L', '\x0d' : '#M', '\x0e' : '#N', '\x0f' : '#O', '\x10' : '#P', '\x11' : '#Q', '\x12' : '#R', '\x13' : '#S', '\x14' : '#T', '\x15' : '#U', '\x16' : '#V', '\x17' : '#W', '\x18' : '#X', '\x19' : '#Y', '\x1a' : '#Z', '\x1b' : '!A', '\x1c' : '!B', '\x1d' : '!C', '\x1e' : '!D', '\x1f' : '!E', '!' : '=A', '"' : '=B', '#' : '=C', '$' : '=D', '%' : '=E', '&' : '=F', '\'' : '=G', '(' : '=H', ')' : '=I', '*' : '=J', '+' : '=K', ',' : '=L', '/' : '=O', ':' : '=Z', ';' : '!F', '<' : '!G', '=' : '!H', '>' : '!I', '?' : '!J', '@' : '!V', '[' : '!K', '\\' : '!L', ']' : '!M', '^' : '!N', '_' : '!O', '`' : '!W', 'a' : '&A', 'b' : '&B', 'c' : '&C', 'd' : '&D', 'e' : '&E', 'f' : '&F', 'g' : '&G', 'h' : '&H', 'i' : '&I', 'j' : '&J', 'k' : '&K', 'l' : '&L', 'm' : '&M', 'n' : '&N', 'o' : '&O', 'p' : '&P', 'q' : '&Q', 'r' : '&R', 's' : '&S', 't' : '&T', 'u' : '&U', 'v' : '&V', 'w' : '&W', 'x' : '&X', 'y' : '&Y', 'z' : '&Z', '{' : '!P', '|' : '!Q', '}' : '!R', '~' : '!S', '\x7f' : '!T' } def _encode93(str): s = list(str) s.reverse() # compute 'C' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 20: v = 1 s.insert(0, _charsbyval[c % 47]) # compute 'K' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 15: v = 1 s.insert(0, _charsbyval[c % 47]) s.reverse() return ''.join(s) class _Code93Base(MultiWidthBarcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 barHeight = None stop = 1 def __init__(self, value='', **args): if type(value) is type(1): value = asNative(value) for (k, v) in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 MultiWidthBarcode.__init__(self, value) def decompose(self): dval = self.stop and [_patterns['start'][0]] or [] dval += [_patterns[c][0] for c in self.encoded] if self.stop: dval.append(_patterns['stop'][0]) self.decomposed = ''.join(dval) return self.decomposed class Standard93(_Code93Base): """ Code 93 is a Uppercase alphanumeric symbology with some punctuation. See Extended Code 93 for a variant that can represent the entire 128 characrter ASCII set. Options that may be passed to constructor: value (int, or numeric string. required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 93: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_93.html Official Spec, "NSI/AIM BC5-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = "" self.valid = 1 for c in self.value.upper(): if c not in _patterns: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = _encode93(self.validated) return self.encoded class Extended93(_Code93Base): """ Extended Code 93 is a convention for encoding the entire 128 character set using pairs of characters to represent the characters missing in Standard Code 93. It is very much like Extended Code 39 in that way. See Standard93 for arguments. """ def validate(self): vval = [] self.valid = 1 a = vval.append for c in self.value: if c not in _patterns and c not in _extended: self.valid = 0 continue a(c) self.validated = ''.join(vval) return self.validated def encode(self): self.encoded = "" for c in self.validated: if c in _patterns: self.encoded = self.encoded + c elif c in _extended: self.encoded = self.encoded + _extended[c] else: raise ValueError self.encoded = _encode93(self.encoded) return self.encoded def _humanText(self): return self.validated+self.encoded[-2:]
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/code93.py
0.510008
0.449332
code93.py
pypi
import re import itertools try: from itertools import zip_longest except: from itertools import izip_longest as zip_longest try: unicode except NameError: # No unicode in Python 3 unicode = str class QR: valid = None bits = None group = 0 def __init__(self, data): if self.valid and not self.valid(data): raise ValueError self.data = data def __len__(self): return len(self.data) @property def bitlength(self): if self.bits is None: return 0 q, r = divmod(len(self), len(self.bits)) return q * sum(self.bits) + sum(self.bits[:r]) def getLengthBits(self, ver): if 0 < ver < 10: return self.lengthbits[0] elif ver < 27: return self.lengthbits[1] elif ver < 41: return self.lengthbits[2] raise ValueError("Unknown version: " + ver) def getLength(self): return len(self.data) def __repr__(self): return repr(self.data) def write_header(self, buffer, version): buffer.put(self.mode, 4) lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for g in zip_longest(*[iter(self.data)] * self.group): bits = 0 n = 0 for i in range(self.group): if g[i] is not None: n *= len(self.chars) n += self.chars.index(g[i]) bits += self.bits[i] buffer.put(n, bits) class QRNumber(QR): valid = re.compile(u'[0-9]*$').match chars = u'0123456789' bits = (4,3,3) group = 3 mode = 0x1 lengthbits = (10, 12, 14) class QRAlphaNum(QR): valid = re.compile(u'[-0-9A-Z $%*+./:]*$').match chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:' bits = (6,5) group = 2 mode = 0x2 lengthbits = (9, 11, 13) class QR8bitByte(QR): bits = (8,) group = 1 mode = 0x4 lengthbits = (8, 16, 16) def __init__(self, data): if isinstance(data, unicode): self.data = data.encode('utf-8') # XXX This really needs an ECI too else: self.data = data # It'd better be byte data def write(self, buffer, version): self.write_header(buffer, version) for c in self.data: if isinstance(c, str): c = ord(c) buffer.put(c, 8) class QRKanji(QR): bits = (13,) group = 1 mode = 0x8 lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrkanji(data) except UnicodeEncodeError: raise ValueError('Not valid kanji') def unicode_to_qrkanji(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('shift-jis') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrkanji', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0x8140 <= c <=0x9ffc: c -= 0x8140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) elif 0xe040 <= c <= 0xebbf: c -= 0xc140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) else: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) class QRHanzi(QR): bits = (13,) group = 1 mode = 0xD lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrhanzi(data) except UnicodeEncodeError: raise ValueError('Not valid hanzi') def unicode_to_qrhanzi(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('gb2312') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrhanzi', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0xa1a1 <= c <=0xaafe: c -= 0xa1a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) elif 0xb0a1 <= c <= 0xfafe: c -= 0xa6a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) else: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write_header(self, buffer, version): buffer.put(self.mode, 4) buffer.put(1, 4) # Subset 1: GB2312 encoding lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) # Special modes class QRECI(QR): mode = 0x7 lengthbits = (0, 0, 0) def __init__(self, data): if not 0 < data < 999999: # Spec says 999999, format supports up to 0x1fffff = 2097151 raise ValueError("ECI out of range") self.data = data def write(self, buffer, version): self.write_header(buffer, version) if self.data <= 0x7f: buffer.put(self.data, 8) elif self.data <= 0x3fff: buffer.put(self.data | 0x8000, 16) elif self.data <= 0x1fffff: buffer.put(self.data | 0xC00000, 24) class QRStructAppend(QR): mode = 0x3 lengthbits = (0, 0, 0) def __init__(self, part, total, parity): if not 0 < part <= 16: raise ValueError("part out of range [1,16]") if not 0 < total <= 16: raise ValueError("total out of range [1,16]") self.part = part self.total = total self.parity = parity def write(self, buffer, version): self.write_header(buffer, version) buffer.put(self.part, 4) buffer.put(self.total, 4) buffer.put(self.parity, 8) class QRFNC1First(QR): mode = 0x5 lengthbits = (0, 0, 0) def __init__(self): pass def write(self, buffer, version): self.write_header(buffer, version) class QRFNC1Second(QR): valid = re.compile('^([A-Za-z]|[0-9][0-9])$').match mode = 0x9 lengthbits = (0, 0, 0) def write(self, buffer, version): self.write_header(buffer, version) d = self.data if len(d) == 1: d = ord(d) + 100 else: d = int(d) buffer.put(d, 8) class QRCode: def __init__(self, version, errorCorrectLevel): self.version = version self.errorCorrectLevel = errorCorrectLevel self.modules = None self.moduleCount = 0 self.dataCache = None self.dataList = [] def addData(self, data): if isinstance(data, QR): newData = data else: for conv in (QRNumber, QRAlphaNum, QRKanji, QR8bitByte): try: newData = conv(data) break except ValueError: pass else: raise ValueError self.dataList.append(newData) self.dataCache = None def isDark(self, row, col): return self.modules[row][col] def getModuleCount(self): return self.moduleCount def calculate_version(self): # Calculate version for data to fit the QR Code capacity for version in range(1, 40): rsBlocks = QRRSBlock.getRSBlocks(version, self.errorCorrectLevel) totalDataCount = sum(block.dataCount for block in rsBlocks) length = 0 for data in self.dataList: length += 4 length += data.getLengthBits(version) length += data.bitlength if length <= totalDataCount * 8: break return version def make(self): if self.version is None: self.version = self.calculate_version() self.makeImpl(False, self.getBestMaskPattern()) def makeImpl(self, test, maskPattern): self.moduleCount = self.version * 4 + 17 self.modules = [ [False] * self.moduleCount for x in range(self.moduleCount) ] self.setupPositionProbePattern(0, 0) self.setupPositionProbePattern(self.moduleCount - 7, 0) self.setupPositionProbePattern(0, self.moduleCount - 7) self.setupPositionAdjustPattern() self.setupTimingPattern() self.setupTypeInfo(test, maskPattern) if (self.version >= 7): self.setupTypeNumber(test) if (self.dataCache == None): self.dataCache = QRCode.createData(self.version, self.errorCorrectLevel, self.dataList) self.mapData(self.dataCache, maskPattern) _positionProbePattern = [ [True, True, True, True, True, True, True], [True, False, False, False, False, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, False, False, False, False, True], [True, True, True, True, True, True, True], ] def setupPositionProbePattern(self, row, col): if row == 0: self.modules[row+7][col:col+7] = [False] * 7 if col == 0: self.modules[row+7][col+7] = False else: self.modules[row+7][col-1] = False else: # col == 0 self.modules[row-1][col:col+8] = [False] * 8 for r, data in enumerate(self._positionProbePattern): self.modules[row+r][col:col+7] = data if col == 0: self.modules[row+r][col+7] = False else: self.modules[row+r][col-1] = False def getBestMaskPattern(self): minLostPoint = 0 pattern = 0 for i in range(8): self.makeImpl(True, i); lostPoint = QRUtil.getLostPoint(self); if (i == 0 or minLostPoint > lostPoint): minLostPoint = lostPoint pattern = i return pattern def setupTimingPattern(self): for r in range(8, self.moduleCount - 8): self.modules[r][6] = (r % 2 == 0) self.modules[6][8:self.moduleCount - 8] = itertools.islice( itertools.cycle([True, False]), self.moduleCount - 16) _positionAdjustPattern = [ [True, True, True, True, True], [True, False, False, False, True], [True, False, True, False, True], [True, False, False, False, True], [True, True, True, True, True], ] def setupPositionAdjustPattern(self): pos = QRUtil.getPatternPosition(self.version) maxpos = self.moduleCount - 8 for row, col in itertools.product(pos, pos): if col <= 8 and (row <= 8 or row >= maxpos): continue elif col >= maxpos and row <= 8: continue for r, data in enumerate(self._positionAdjustPattern): self.modules[row + r - 2][col-2:col+3] = data def setupTypeNumber(self, test): bits = QRUtil.getBCHTypeNumber(self.version) for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; def setupTypeInfo(self, test, maskPattern): data = (self.errorCorrectLevel << 3) | maskPattern bits = QRUtil.getBCHTypeInfo(data) # vertical for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1) if (i < 6): self.modules[i][8] = mod elif (i < 8): self.modules[i + 1][8] = mod else: self.modules[self.moduleCount - 15 + i][8] = mod # horizontal for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1); if (i < 8): self.modules[8][self.moduleCount - i - 1] = mod elif (i < 9): self.modules[8][15 - i - 1 + 1] = mod else: self.modules[8][15 - i - 1] = mod # fixed module self.modules[self.moduleCount - 8][8] = (not test) def _dataPosIterator(self): cols = itertools.chain(range(self.moduleCount - 1, 6, -2), range(5, 0, -2)) rows = (list(range(9, self.moduleCount - 8)), list(itertools.chain(range(6), range(7, self.moduleCount))), list(range(9, self.moduleCount))) rrows = tuple( list(reversed(r)) for r in rows) ppos = QRUtil.getPatternPosition(self.version) ppos = set(itertools.chain.from_iterable( (p-2, p-1, p, p+1, p+2) for p in ppos)) maxpos = self.moduleCount - 11 for col in cols: rows, rrows = rrows, rows if col <= 8: rowidx = 0 elif col >= self.moduleCount - 8: rowidx = 2 else: rowidx = 1 for row in rows[rowidx]: for c in range(2): c = col - c if self.version >= 7: if row < 6 and c >= self.moduleCount - 11: continue elif col < 6 and row >= self.moduleCount - 11: continue if row in ppos and c in ppos: if not (row < 11 and (c < 11 or c > maxpos) or c < 11 and (row < 11 or row > maxpos)): continue yield (c, row) _dataPosList = None def dataPosIterator(self): if not self._dataPosList: self._dataPosList = list(self._dataPosIterator()) return self._dataPosList def _dataBitIterator(self, data): for byte in data: for bit in [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]: yield bool(byte & bit) _dataBitList = None def dataBitIterator(self, data): if not self._dataBitList: self._dataBitList = list(self._dataBitIterator(data)) return iter(self._dataBitList) def mapData(self, data, maskPattern): bits = self.dataBitIterator(data) mask = QRUtil.getMask(maskPattern) for (col, row), dark in zip_longest(self.dataPosIterator(), bits, fillvalue=False): self.modules[row][col] = dark ^ mask(row, col) PAD0 = 0xEC PAD1 = 0x11 @staticmethod def createData(version, errorCorrectLevel, dataList): rsBlocks = QRRSBlock.getRSBlocks(version, errorCorrectLevel) buffer = QRBitBuffer(); for data in dataList: data.write(buffer, version) # calc num max data. totalDataCount = 0; for block in rsBlocks: totalDataCount += block.dataCount if (buffer.getLengthInBits() > totalDataCount * 8): raise Exception("code length overflow. (%d > %d)" % (buffer.getLengthInBits(), totalDataCount * 8)) # end code if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): buffer.put(0, 4) # padding while (buffer.getLengthInBits() % 8 != 0): buffer.putBit(False) # padding while (True): if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD0, 8) if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD1, 8) return QRCode.createBytes(buffer, rsBlocks) @staticmethod def createBytes(buffer, rsBlocks): offset = 0 maxDcCount = 0 maxEcCount = 0 totalCodeCount = 0 dcdata = [] ecdata = [] for block in rsBlocks: totalCodeCount += block.totalCount dcCount = block.dataCount ecCount = block.totalCount - dcCount maxDcCount = max(maxDcCount, dcCount) maxEcCount = max(maxEcCount, ecCount) dcdata.append(buffer.buffer[offset:offset+dcCount]) offset += dcCount rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) rawPoly = QRPolynomial(dcdata[-1], rsPoly.getLength() - 1) modPoly = rawPoly.mod(rsPoly) rLen = rsPoly.getLength() - 1 mLen = modPoly.getLength() ecdata.append([ (modPoly.get(i) if i >= 0 else 0) for i in range(mLen - rLen, mLen) ]) data = [ d for dd in itertools.chain( zip_longest(*dcdata), zip_longest(*ecdata)) for d in dd if d is not None] return data class QRErrorCorrectLevel: L = 1 M = 0 Q = 3 H = 2 class QRMaskPattern: PATTERN000 = 0 PATTERN001 = 1 PATTERN010 = 2 PATTERN011 = 3 PATTERN100 = 4 PATTERN101 = 5 PATTERN110 = 6 PATTERN111 = 7 class QRUtil: PATTERN_POSITION_TABLE = [ [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170] ] G15 = ((1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)) G18 = ((1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)) G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) @staticmethod def getBCHTypeInfo(data): d = data << 10; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) return ( (data << 10) | d) ^ QRUtil.G15_MASK @staticmethod def getBCHTypeNumber(data): d = data << 12; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) return (data << 12) | d @staticmethod def getBCHDigit(data): digit = 0; while (data != 0): digit += 1 data >>= 1 return digit @staticmethod def getPatternPosition(version): return QRUtil.PATTERN_POSITION_TABLE[version - 1] maskPattern = { 0: lambda i,j: (i + j) % 2 == 0, 1: lambda i,j: i % 2 == 0, 2: lambda i,j: j % 3 == 0, 3: lambda i,j: (i + j) % 3 == 0, 4: lambda i,j: (i // 2 + j // 3) % 2 == 0, 5: lambda i,j: (i*j)%2 + (i*j)%3 == 0, 6: lambda i,j: ( (i * j) % 2 + (i * j) % 3) % 2 == 0, 7: lambda i,j: ( (i * j) % 3 + (i + j) % 2) % 2 == 0 } @classmethod def getMask(cls, maskPattern): return cls.maskPattern[maskPattern] @staticmethod def getErrorCorrectPolynomial(errorCorrectLength): a = QRPolynomial([1], 0); for i in range(errorCorrectLength): a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) return a @classmethod def maskScoreRule1vert(cls, modules): score = 0 lastCount = [0] lastRow = None for row in modules: # Vertical patterns if lastRow: changed = [a ^ b for a,b in zip(row, lastRow)] scores = [a and (b-4+3) for a,b in zip_longest(changed, lastCount, fillvalue=0) if b >= 4] score += sum(scores) lastCount = [0 if a else b + 1 for a,b in zip_longest(changed, lastCount, fillvalue=0)] lastRow = row score += sum([b-4+3 for b in lastCount if b >= 4]) # final counts return score @classmethod def maskScoreRule2(cls, modules): score = 0 lastRow = modules[0] for row in modules[1:]: lastCol0, lastCol1 = row[0], lastRow[0] for col0, col1 in zip(row[1:], lastRow[1:]): if col0 == col1 == lastCol0 == lastCol1: score += 3 lastCol0, lastCol1 = col0, col1 lastRow = row return score @classmethod def maskScoreRule3hor( cls, modules, pattern = [True, False, True, True, True, False, True, False, False, False, False]): patternlen = len(pattern) score = 0 for row in modules: j = 0 maxj = len(row) - patternlen while j < maxj: if row[j:j+patternlen] == pattern: score += 40 j += patternlen else: j += 1 return score @classmethod def maskScoreRule4(cls, modules): cellCount = len(modules)**2 count = sum(sum(row) for row in modules) return 10 * (abs(100 * count // cellCount - 50) // 5) @classmethod def getLostPoint(cls, qrCode): lostPoint = 0; # LEVEL1 lostPoint += cls.maskScoreRule1vert(qrCode.modules) lostPoint += cls.maskScoreRule1vert(zip(*qrCode.modules)) # LEVEL2 lostPoint += cls.maskScoreRule2(qrCode.modules) # LEVEL3 lostPoint += cls.maskScoreRule3hor(qrCode.modules) lostPoint += cls.maskScoreRule3hor(zip(*qrCode.modules)) # LEVEL4 lostPoint += cls.maskScoreRule4(qrCode.modules) return lostPoint class QRMath: @staticmethod def glog(n): if (n < 1): raise Exception("glog(" + n + ")") return LOG_TABLE[n]; @staticmethod def gexp(n): while n < 0: n += 255 while n >= 256: n -= 255 return EXP_TABLE[n]; EXP_TABLE = [x for x in range(256)] LOG_TABLE = [x for x in range(256)] for i in range(8): EXP_TABLE[i] = 1 << i; for i in range(8, 256): EXP_TABLE[i] = (EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]) for i in range(255): LOG_TABLE[EXP_TABLE[i] ] = i class QRPolynomial: def __init__(self, num, shift): if (len(num) == 0): raise Exception(len(num) + "/" + shift) offset = 0 while offset < len(num) and num[offset] == 0: offset += 1 self.num = num[offset:] + [0]*shift def get(self, index): return self.num[index] def getLength(self): return len(self.num) def multiply(self, e): num = [0] * (self.getLength() + e.getLength() - 1); for i in range(self.getLength()): for j in range(e.getLength()): num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) return QRPolynomial(num, 0); def mod(self, e): if (self.getLength() < e.getLength()): return self; ratio = QRMath.glog(self.num[0] ) - QRMath.glog(e.num[0] ) num = [nn ^ QRMath.gexp(QRMath.glog(en) + ratio) for nn,en in zip(self.num, e.num)] num += self.num[e.getLength():] # recursive call return QRPolynomial(num, 0).mod(e); class QRRSBlock: RS_BLOCK_TABLE = [ # L # M # Q # H # 1 [1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], # 2 [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], # 3 [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], # 4 [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], # 5 [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], # 6 [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], # 7 [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], # 8 [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], # 9 [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], # 10 [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], # 11 [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], # 12 [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], # 13 [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], # 14 [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], # 15 [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12], # 16 [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], # 17 [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], # 18 [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], # 19 [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], # 20 [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], # 21 [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], # 22 [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], # 23 [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], # 24 [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], # 25 [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], # 26 [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], # 27 [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], # 28 [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], # 29 [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], # 30 [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], # 31 [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], # 32 [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], # 33 [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], # 34 [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], # 35 [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], # 36 [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], # 37 [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], # 38 [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], # 39 [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], # 40 [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16] ] def __init__(self, totalCount, dataCount): self.totalCount = totalCount self.dataCount = dataCount @staticmethod def getRSBlocks(version, errorCorrectLevel): rsBlock = QRRSBlock.getRsBlockTable(version, errorCorrectLevel); if rsBlock == None: raise Exception("bad rs block @ version:" + version + "/errorCorrectLevel:" + errorCorrectLevel) length = len(rsBlock) // 3 list = [] for i in range(length): count = rsBlock[i * 3 + 0] totalCount = rsBlock[i * 3 + 1] dataCount = rsBlock[i * 3 + 2] for j in range(count): list.append(QRRSBlock(totalCount, dataCount)) return list; @staticmethod def getRsBlockTable(version, errorCorrectLevel): if errorCorrectLevel == QRErrorCorrectLevel.L: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 0]; elif errorCorrectLevel == QRErrorCorrectLevel.M: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 1]; elif errorCorrectLevel == QRErrorCorrectLevel.Q: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 2]; elif errorCorrectLevel == QRErrorCorrectLevel.H: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 3]; else: return None; class QRBitBuffer: def __init__(self): self.buffer = [] self.length = 0 def __repr__(self): return ".".join([str(n) for n in self.buffer]) def get(self, index): bufIndex = index // 8 return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 def put(self, num, length): for i in range(length): self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) def getLengthInBits(self): return self.length def putBit(self, bit): bufIndex = self.length // 8 if len(self.buffer) <= bufIndex: self.buffer.append(0) if bit: self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) self.length += 1
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/qrencoder.py
0.436142
0.187653
qrencoder.py
pypi
from __future__ import print_function __version__='3.3.0' __all__ = ('USPS_4State',) from reportlab.graphics.barcode.common import Barcode from reportlab.lib.utils import asNative def nhex(i): 'normalized hex' r = hex(i) r = r[:2]+r[2:].lower() if r.endswith('l'): r = r[:-1] return r class USPS_4State(Barcode): ''' USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A ''' _widthSize = 1 _heightSize = 1 _fontSize = 11 _humanReadable = 0 if True: tops = dict( F = (0.0625,0.0825), T = (0.0195,0.0285), A = (0.0625,0.0825), D = (0.0195,0.0285), ) bottoms = dict( F = (-0.0625,-0.0825), T = (-0.0195,-0.0285), D = (-0.0625,-0.0825), A = (-0.0195,-0.0285), ) dimensions = dict( width = (0.015, 0.025), pitch = (0.0416, 0.050), hcz = (0.125,0.125), vcz = (0.028,0.028), ) else: tops = dict( F = (0.067,0.115), T = (0.021,0.040), A = (0.067,0.115), D = (0.021,0.040), ) bottoms = dict( F = (-0.067,-0.115), D = (-0.067,-0.115), T = (-0.021,-0.040), A = (-0.021,-0.040), ) dimensions = dict( width = (0.015, 0.025), pitch = (0.0416,0.050), hcz = (0.125,0.125), vcz = (0.040,0.040), ) def __init__(self,value='01234567094987654321',routing='',**kwd): self._init() value = str(value) if isinstance(value,int) else asNative(value) if not routing: #legal values for combined tracking + routing if len(value) in (20,25,29,31): value, routing = value[:20], value[20:] else: raise ValueError('value+routing length must be 20, 25, 29 or 31 digits not %d' % len(value)) elif len(routing) not in (5,9,11): raise ValueError('routing length must be 5, 9 or 11 digits not %d' % len(routing)) self._tracking = value self._routing = routing self._setKeywords(**kwd) def _init(self): self._bvalue = None self._codewords = None self._characters = None self._barcodes = None def scale(kind,D,s): V = D[kind] return 72*(V[0]*(1-s)+s*V[1]) scale = staticmethod(scale) def tracking(self,tracking): self._init() self._tracking = tracking tracking = property(lambda self: self._tracking,tracking) def routing(self,routing): self._init() self._routing = routing routing = property(lambda self: self._routing,routing) def widthSize(self,value): self._sized = None self._widthSize = min(max(0,value),1) widthSize = property(lambda self: self._widthSize,widthSize) def heightSize(self,value): self._sized = None self._heightSize = value heightSize = property(lambda self: self._heightSize,heightSize) def fontSize(self,value): self._sized = None self._fontSize = value fontSize = property(lambda self: self._fontSize,fontSize) def humanReadable(self,value): self._sized = None self._humanReadable = value humanReadable = property(lambda self: self._humanReadable,humanReadable) def binary(self): '''convert the 4 state string values to binary >>> print(nhex(USPS_4State('01234567094987654321','').binary)) 0x1122103b5c2004b1 >>> print(nhex(USPS_4State('01234567094987654321','01234').binary)) 0xd138a87bab5cf3804b1 >>> print(nhex(USPS_4State('01234567094987654321','012345678').binary)) 0x202bdc097711204d21804b1 >>> print(nhex(USPS_4State('01234567094987654321','01234567891').binary)) 0x16907b2a24abc16a2e5c004b1 ''' value = self._bvalue if not value: routing = self.routing n = len(routing) try: if n==0: value = 0 elif n==5: value = int(routing)+1 elif n==9: value = int(routing)+100001 elif n==11: value = int(routing)+1000100001 else: raise ValueError except: raise ValueError('Problem converting %s, routing code must be 0, 5, 9 or 11 digits' % routing) tracking = self.tracking svalue = tracking[0:2] try: value *= 10 value += int(svalue[0]) value *= 5 value += int(svalue[1]) except: raise ValueError('Problem converting %s, barcode identifier must be 2 digits' % svalue) i = 2 for name,nd in (('special services',3), ('customer identifier',6), ('sequence number',9)): j = i i += nd svalue = tracking[j:i] try: if len(svalue)!=nd: raise ValueError for j in range(nd): value *= 10 value += int(svalue[j]) except: raise ValueError('Problem converting %s, %s must be %d digits' % (svalue,name,nd)) self._bvalue = value return value binary = property(binary) def codewords(self): '''convert binary value into codewords >>> print(USPS_4State('01234567094987654321','01234567891').codewords) (673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602) ''' if not self._codewords: value = self.binary A, J = divmod(value,636) A, I = divmod(A,1365) A, H = divmod(A,1365) A, G = divmod(A,1365) A, F = divmod(A,1365) A, E = divmod(A,1365) A, D = divmod(A,1365) A, C = divmod(A,1365) A, B = divmod(A,1365) assert 0<=A<=658, 'improper value %s passed to _2codewords A-->%s' % (hex(int(value)),A) self._fcs = _crc11(value) if self._fcs&1024: A += 659 J *= 2 self._codewords = tuple(map(int,(A,B,C,D,E,F,G,H,I,J))) return self._codewords codewords = property(codewords) def table1(self): self.__class__.table1 = _initNof13Table(5,1287) return self.__class__.table1 table1 = property(table1) def table2(self): self.__class__.table2 = _initNof13Table(2,78) return self.__class__.table2 table2 = property(table2) def characters(self): ''' convert own codewords to characters >>> print(' '.join(hex(c)[2:] for c in USPS_4State('01234567094987654321','01234567891').characters)) dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b ''' if not self._characters: codewords = self.codewords fcs = self._fcs C = [] aC = C.append table1 = self.table1 table2 = self.table2 for i in range(10): cw = codewords[i] if cw<=1286: c = table1[cw] else: c = table2[cw-1287] if (fcs>>i)&1: c = ~c & 0x1fff aC(c) self._characters = tuple(C) return self._characters characters = property(characters) def barcodes(self): '''Get 4 state bar codes for current routing and tracking >>> print(USPS_4State('01234567094987654321','01234567891').barcodes) AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA ''' if not self._barcodes: C = self.characters B = [] aB = B.append bits2bars = self._bits2bars for dc,db,ac,ab in self.table4: aB(bits2bars[((C[dc]>>db)&1)+2*((C[ac]>>ab)&1)]) self._barcodes = ''.join(B) return self._barcodes barcodes = property(barcodes) table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11), (8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11), (6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12), (9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6), (6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8), (6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7), (5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7), (4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9), (6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12), (4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0), (1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6), (0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9), (6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10), (6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11), (1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7), (4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3), (3, 10, 8, 2)) _bits2bars = 'T','D','A','F' horizontalClearZone = property(lambda self: self.scale('hcz',self.dimensions,self.widthScale)) verticalClearZone = property(lambda self: self.scale('vcz',self.dimensions,self.heightScale)) @property def barWidth(self): if '_barWidth' in self.__dict__: return self.__dict__['_barWidth'] return self.scale('width',self.dimensions,self.widthScale) @barWidth.setter def barWidth(self,value): n, x = self.dimensions['width'] self.__dict__['_barWidth'] = 72*min(max(value/72.0,n),x) @property def pitch(self): if '_pitch' in self.__dict__: return self.__dict__['_pitch'] return self.scale('pitch',self.dimensions,self.widthScale) @pitch.setter def pitch(self,value): n, x = self.dimensions['pitch'] self.__dict__['_pitch'] = 72*min(max(value/72.0,n),x) @property def barHeight(self): if '_barHeight' in self.__dict__: return self.__dict__['_barHeight'] return self.scale('F',self.tops,self.heightScale) - self.scale('F',self.bottoms,self.heightScale) @barHeight.setter def barHeight(self,value): n = self.tops['F'][0] - self.bottoms['F'][0] x = self.tops['F'][1] - self.bottoms['F'][1] value = self.__dict__['_barHeight'] = 72*min(max(value/72.0,n),x) self.heightSize = (value - n)/(x-n) widthScale = property(lambda self: min(1,max(0,self.widthSize))) heightScale = property(lambda self: min(1,max(0,self.heightSize))) def width(self): self.computeSize() return self._width width = property(width) def height(self): self.computeSize() return self._height height = property(height) def computeSize(self): if not getattr(self,'_sized',None): ws = self.widthScale hs = self.heightScale barHeight = self.barHeight barWidth = self.barWidth pitch = self.pitch hcz = self.horizontalClearZone vcz = self.verticalClearZone self._width = 2*hcz + barWidth + 64*pitch self._height = 2*vcz+barHeight if self.humanReadable: self._height += self.fontSize*1.2+vcz self._sized = True def wrap(self,aW,aH): self.computeSize() return self.width, self.height def _getBarVInfo(self,y0=0): vInfo = {} hs = self.heightScale for b in ('T','D','A','F'): y = self.scale(b,self.bottoms,hs)+y0 vInfo[b] = y,self.scale(b,self.tops,hs)+y0 - y return vInfo def draw(self): self.computeSize() hcz = self.horizontalClearZone vcz = self.verticalClearZone bw = self.barWidth x = hcz y0 = vcz+self.barHeight*0.5 dw = self.pitch vInfo = self._getBarVInfo(y0) for b in self.barcodes: yb, hb = vInfo[b] self.rect(x,yb,bw,hb) x += dw self.drawHumanReadable() def value(self): tracking = self.tracking routing = self.routing routing = routing and (routing,) or () return ' '.join((tracking[0:2],tracking[2:5],tracking[5:11],tracking[11:])+routing) value = property(value,lambda self,value: self.__dict__.__setitem__('tracking',value)) def drawHumanReadable(self): if self.humanReadable: hcz = self.horizontalClearZone vcz = self.verticalClearZone fontName = self.fontName fontSize = self.fontSize y = self.barHeight+2*vcz+0.2*fontSize self.annotate(hcz,y,self.value,fontName,fontSize) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): Barcode.annotate(self,x,y,text,fontName,fontSize,anchor='start') def _crc11(value): ''' >>> usps = [USPS_4State('01234567094987654321',x).binary for x in ('','01234','012345678','01234567891')] >>> print(' '.join(nhex(x) for x in usps)) 0x1122103b5c2004b1 0xd138a87bab5cf3804b1 0x202bdc097711204d21804b1 0x16907b2a24abc16a2e5c004b1 >>> print(' '.join(nhex(_crc11(x)) for x in usps)) 0x51 0x65 0x606 0x751 ''' hexbytes = nhex(int(value))[2:] hexbytes = '0'*(26-len(hexbytes))+hexbytes gp = 0x0F35 fcs = 0x07FF data = int(hexbytes[:2],16)<<5 for b in range(2,8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 for x in range(2,2*13,2): data = int(hexbytes[x:x+2],16)<<3 for b in range(8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 return fcs def _ru13(i): '''reverse unsigned 13 bit number >>> print(_ru13(7936), _ru13(31), _ru13(47), _ru13(7808)) 31 7936 7808 47 ''' r = 0 for x in range(13): r <<= 1 r |= i & 1 i >>= 1 return r def _initNof13Table(N,lenT): '''create and return table of 13 bit values with N bits on >>> T = _initNof13Table(5,1287) >>> print(' '.join('T[%d]=%d' % (i, T[i]) for i in (0,1,2,3,4,1271,1272,1284,1285,1286))) T[0]=31 T[1]=7936 T[2]=47 T[3]=7808 T[4]=55 T[1271]=6275 T[1272]=6211 T[1284]=856 T[1285]=744 T[1286]=496 ''' T = lenT*[None] l = 0 u = lenT-1 for c in range(8192): bc = 0 for b in range(13): bc += (c&(1<<b))!=0 if bc!=N: continue r = _ru13(c) if r<c: continue #we already looked at this pair if r==c: T[u] = c u -= 1 else: T[l] = c l += 1 T[l] = r l += 1 assert l==(u+1), 'u+1(%d)!=l(%d) for %d of 13 table' % (u+1,l,N) return T def _test(): import doctest return doctest.testmod() if __name__ == "__main__": _test()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/usps4s.py
0.468791
0.240189
usps4s.py
pypi
from reportlab.graphics.barcode.code39 import Standard39 from reportlab.lib import colors from reportlab.lib.units import cm from string import ascii_uppercase, digits as string_digits class BaseLTOLabel(Standard39) : """ Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en """ LABELWIDTH = 7.9 * cm LABELHEIGHT = 1.7 * cm LABELROUND = 0.15 * cm CODERATIO = 2.75 CODENOMINALWIDTH = 7.4088 * cm CODEBARHEIGHT = 1.11 * cm CODEBARWIDTH = 0.0432 * cm CODEGAP = CODEBARWIDTH CODELQUIET = 10 * CODEBARWIDTH CODERQUIET = 10 * CODEBARWIDTH def __init__(self, prefix="", number=None, subtype="1", border=None, checksum=False, availheight=None) : """ Initializes an LTO label. prefix : Up to six characters from [A-Z][0-9]. Defaults to "". number : Label's number or None. Defaults to None. subtype : LTO subtype string , e.g. "1" for LTO1. Defaults to "1". border : None, or the width of the label's border. Defaults to None. checksum : Boolean indicates if checksum char has to be printed. Defaults to False. availheight : Available height on the label, or None for automatic. Defaults to None. """ self.height = max(availheight, self.CODEBARHEIGHT) self.border = border if (len(subtype) != 1) \ or (subtype not in ascii_uppercase + string_digits) : raise ValueError("Invalid subtype '%s'" % subtype) if ((not number) and (len(prefix) > 6)) \ or not prefix.isalnum() : raise ValueError("Invalid prefix '%s'" % prefix) label = "%sL%s" % ((prefix + str(number or 0).zfill(6 - len(prefix)))[:6], subtype) if len(label) != 8 : raise ValueError("Invalid set of parameters (%s, %s, %s)" \ % (prefix, number, subtype)) self.label = label Standard39.__init__(self, label, ratio=self.CODERATIO, barHeight=self.height, barWidth=self.CODEBARWIDTH, gap=self.CODEGAP, lquiet=self.CODELQUIET, rquiet=self.CODERQUIET, quiet=True, checksum=checksum) def drawOn(self, canvas, x, y) : """Draws the LTO label onto the canvas.""" canvas.saveState() canvas.translate(x, y) if self.border : canvas.setLineWidth(self.border) canvas.roundRect(0, 0, self.LABELWIDTH, self.LABELHEIGHT, self.LABELROUND) Standard39.drawOn(self, canvas, (self.LABELWIDTH-self.CODENOMINALWIDTH)/2.0, self.LABELHEIGHT-self.height) canvas.restoreState() class VerticalLTOLabel(BaseLTOLabel) : """ A class for LTO labels with rectangular blocks around the tape identifier. """ LABELFONT = ("Helvetica-Bold", 14) BLOCKWIDTH = 1*cm BLOCKHEIGHT = 0.45*cm LINEWIDTH = 0.0125 NBBLOCKS = 7 COLORSCHEME = ("red", "yellow", "lightgreen", "lightblue", "grey", "orangered", "pink", "darkgreen", "orange", "purple") def __init__(self, *args, **kwargs) : """ Initializes the label. colored : boolean to determine if blocks have to be colorized. """ if "colored" in kwargs: self.colored = kwargs["colored"] del kwargs["colored"] else : self.colored = False kwargs["availheight"] = self.LABELHEIGHT-self.BLOCKHEIGHT BaseLTOLabel.__init__(self, *args, **kwargs) def drawOn(self, canvas, x, y) : """Draws some blocks around the identifier's characters.""" BaseLTOLabel.drawOn(self, canvas, x, y) canvas.saveState() canvas.setLineWidth(self.LINEWIDTH) canvas.setStrokeColorRGB(0, 0, 0) canvas.translate(x, y) xblocks = (self.LABELWIDTH-(self.NBBLOCKS*self.BLOCKWIDTH))/2.0 for i in range(self.NBBLOCKS) : (font, size) = self.LABELFONT newfont = self.LABELFONT if i == (self.NBBLOCKS - 1) : part = self.label[i:] (font, size) = newfont size /= 2.0 newfont = (font, size) else : part = self.label[i] canvas.saveState() canvas.translate(xblocks+(i*self.BLOCKWIDTH), 0) if self.colored and part.isdigit() : canvas.setFillColorRGB(*getattr(colors, self.COLORSCHEME[int(part)], colors.Color(1, 1, 1)).rgb()) else: canvas.setFillColorRGB(1, 1, 1) canvas.rect(0, 0, self.BLOCKWIDTH, self.BLOCKHEIGHT, fill=True) canvas.translate((self.BLOCKWIDTH+canvas.stringWidth(part, *newfont))/2.0, (self.BLOCKHEIGHT/2.0)) canvas.rotate(90.0) canvas.setFont(*newfont) canvas.setFillColorRGB(0, 0, 0) canvas.drawCentredString(0, 0, part) canvas.restoreState() canvas.restoreState() def test() : """Test this.""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib import pagesizes canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) canvas.setFont("Helvetica", 30) (width, height) = pagesizes.A4 canvas.drawCentredString(width/2.0, height-4*cm, "Sample LTO labels") xpos = xorig = 2 * cm ypos = yorig = 2 * cm colwidth = 10 * cm lineheight = 3.9 * cm count = 1234 BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 BaseLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", colored=True).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125, colored=True).drawOn(canvas, xpos, ypos) canvas.showPage() canvas.save() if __name__ == "__main__" : test()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/lto.py
0.740737
0.255924
lto.py
pypi
__all__ = ('QrCodeWidget') import itertools from reportlab.platypus.flowables import Flowable from reportlab.graphics.shapes import Group, Rect from reportlab.lib import colors from reportlab.lib.validators import isNumber, isNumberOrNone, isColor, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.widgetbase import Widget from reportlab.lib.units import mm from reportlab.lib.utils import asUnicodeEx, isUnicode from reportlab.graphics.barcode import qrencoder class isLevel(Validator): def test(self, x): return x in ['L', 'M', 'Q', 'H'] isLevel = isLevel() class isUnicodeOrQRList(Validator): def _test(self, x): if isUnicode(x): return True if all(isinstance(v, qrencoder.QR) for v in x): return True return False def test(self, x): return self._test(x) or self.normalizeTest(x) def normalize(self, x): if self._test(x): return x try: return asUnicodeEx(x) except UnicodeError: raise ValueError("Can't convert to unicode: %r" % x) isUnicodeOrQRList = isUnicodeOrQRList() class SRect(Rect): def __init__(self, x, y, width, height, fillColor=colors.black): Rect.__init__(self, x, y, width, height, fillColor=fillColor, strokeColor=None, strokeWidth=0) class QrCodeWidget(Widget): codeName = "QR" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isUnicodeOrQRList, desc='QRCode data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), barFillColor = AttrMapValue(isColor, desc='bar color'), barWidth = AttrMapValue(isNumber, desc='Width of bars.'), # maybe should be named just width? barHeight = AttrMapValue(isNumber, desc='Height of bars.'), # maybe should be named just height? barBorder = AttrMapValue(isNumber, desc='Width of QR border.'), # maybe should be named qrBorder? barLevel = AttrMapValue(isLevel, desc='QR Code level.'), # maybe should be named qrLevel qrVersion = AttrMapValue(isNumberOrNone, desc='QR Code version. None for auto'), # Below are ignored, they make no sense barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), ) x = 0 y = 0 barFillColor = colors.black barStrokeColor = None barStrokeWidth = 0 barHeight = 32*mm barWidth = 32*mm barBorder = 4 barLevel = 'L' qrVersion = None value = None def __init__(self, value='Hello World', **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.barLevel) self.__dict__['qr'] = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() g = Group() color = self.barFillColor border = self.barBorder width = self.barWidth height = self.barHeight x = self.x y = self.y g.add(SRect(x, y, width, height, fillColor=None)) moduleCount = self.qr.getModuleCount() minwh = float(min(width, height)) boxsize = minwh / (moduleCount + border * 2.0) offsetX = x + (width - minwh) / 2.0 offsetY = y + (minwh - height) / 2.0 for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * boxsize y = (r + border + 1) * boxsize s = SRect(offsetX + x, offsetY + height - y, count * boxsize, boxsize, fillColor=color) g.add(s) c += count return g # Flowable version class QrCode(Flowable): height = 32*mm width = 32*mm qrBorder = 4 qrLevel = 'L' qrVersion = None value = None def __init__(self, value=None, **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.qrLevel) self.qr = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() moduleCount = self.qr.getModuleCount() border = self.qrBorder xsize = self.width / (moduleCount + border * 2.0) ysize = self.height / (moduleCount + border * 2.0) for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * xsize y = self.height - (r + border + 1) * ysize self.rect(x, y, count * xsize, ysize * 1.05) c += count def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/qr.py
0.540196
0.250071
qr.py
pypi
try: from pylibdmtx import pylibdmtx except ImportError: pylibdmtx = None __all__ = () else: __all__=('DataMatrix',) from reportlab.graphics.barcode.common import Barcode from reportlab.lib.utils import asBytes from reportlab.platypus.paraparser import _num as paraparser_num from reportlab.graphics.widgetbase import Widget from reportlab.lib.validators import isColor, isString, isColorOrNone, isNumber, isBoxAnchor from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import toColor from reportlab.graphics.shapes import Group, Rect def _numConv(x): return x if isinstance(x,(int,float)) else paraparser_num(x) class _DMTXCheck: @classmethod def pylibdmtx_check(cls): if not pylibdmtx: raise ValueError('The %s class requires package pylibdmtx' % cls.__name__) class DataMatrix(Barcode,_DMTXCheck): def __init__(self, value='', **kwds): self.pylibdmtx_check() self._recalc = True self.value = value self.cellSize = kwds.pop('cellSize','5x5') self.size = kwds.pop('size','SquareAuto') self.encoding = kwds.pop('encoding','Ascii') self.anchor = kwds.pop('anchor','sw') self.color = kwds.pop('color',(0,0,0)) self.bgColor = kwds.pop('bgColor',None) self.x = kwds.pop('x',0) self.y = kwds.pop('y',0) self.border = kwds.pop('border',5) @property def value(self): return self._value @value.setter def value(self,v): self._value = asBytes(v) self._recalc = True @property def size(self): return self._size @size.setter def size(self,v): self._size = self._checkVal('size', v, pylibdmtx.ENCODING_SIZE_NAMES) self._recalc = True @property def border(self): return self._border @border.setter def border(self,v): self._border = _numConv(v) self._recalc = True @property def x(self): return self._x @x.setter def x(self,v): self._x = _numConv(v) self._recalc = True @property def y(self): return self._y @y.setter def y(self,v): self._y = _numConv(v) self._recalc = True @property def cellSize(self): return self._cellSize @size.setter def cellSize(self,v): self._cellSize = v self._recalc = True @property def encoding(self): return self._encoding @encoding.setter def encoding(self,v): self._encoding = self._checkVal('encoding', v, pylibdmtx.ENCODING_SCHEME_NAMES) self._recalc = True @property def anchor(self): return self._anchor @anchor.setter def anchor(self,v): self._anchor = self._checkVal('anchor', v, ('n','ne','e','se','s','sw','w','nw','c')) self._recalc = True def recalc(self): if not self._recalc: return data = self._value size = self._size encoding = self._encoding e = pylibdmtx.encode(data, size=size, scheme=encoding) iW = e.width iH = e.height p = e.pixels iCellSize = 5 bpp = 3 #bytes per pixel rowLen = iW*bpp cellLen = iCellSize*bpp assert len(p)//rowLen == iH matrix = list(filter(None, (''.join( (('x' if p[j:j+bpp] != b'\xff\xff\xff' else ' ') for j in range(i,i+rowLen,cellLen))).strip() for i in range(0,iH*rowLen,rowLen*iCellSize)))) self._nRows = len(matrix) self._nCols = len(matrix[-1]) self._matrix = '\n'.join(matrix) cellWidth = self._cellSize if cellWidth: cellWidth = cellWidth.split('x') if len(cellWidth)>2: raise ValueError('cellSize needs to be distance x distance not %r' % self._cellSize) elif len(cellWidth)==2: cellWidth, cellHeight = cellWidth else: cellWidth = cellHeight = cellWidth[0] cellWidth = _numConv(cellWidth) cellHeight = _numConv(cellHeight) else: cellWidth = cellHeight = iCellSize self._cellWidth = cellWidth self._cellHeight = cellHeight self._recalc = False self._bord = max(self.border,cellWidth,cellHeight) self._width = cellWidth*self._nCols + 2*self._bord self._height = cellHeight*self._nRows + 2*self._bord @property def matrix(self): self.recalc() return self._matrix @property def width(self): self.recalc() return self._width @property def height(self): self.recalc() return self._height @property def cellWidth(self): self.recalc() return self._cellWidth @property def cellHeight(self): self.recalc() return self._cellHeight def draw(self): self.recalc() canv = self.canv w = self.width h = self.height x = self.x y = self.y b = self._bord anchor = self.anchor if anchor in ('nw','n','ne'): y -= h elif anchor in ('c','e','w'): y -= h//2 if anchor in ('ne','e','se'): x -= w elif anchor in ('n','c','s'): x -= w//2 canv.saveState() if self.bgColor: canv.setFillColor(toColor(self.bgColor)) canv.rect(x, y-h, w, h, fill=1, stroke=0) canv.setFillColor(toColor(self.color)) canv.setStrokeColor(None) cellWidth = self.cellWidth cellHeight = self.cellHeight yr = y - b - cellHeight x += b for row in self.matrix.split('\n'): xr = x for c in row: if c=='x': canv.rect(xr, yr, cellWidth, cellHeight, fill=1, stroke=0) xr += cellWidth yr -= cellHeight canv.restoreState() class DataMatrixWidget(Widget,_DMTXCheck): codeName = "DataMatrix" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isString, desc='Datamatrix data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), color = AttrMapValue(isColor, desc='foreground color'), bgColor = AttrMapValue(isColorOrNone, desc='background color'), encoding = AttrMapValue(isString, desc='encoding'), size = AttrMapValue(isString, desc='size'), cellSize = AttrMapValue(isString, desc='cellSize'), anchor = AttrMapValue(isBoxAnchor, desc='anchor pooint for x,y'), ) _defaults = dict( x = ('0',_numConv), y = ('0',_numConv), color = ('black',toColor), bgColor = (None,lambda _: toColor(_) if _ is not None else _), encoding = ('Ascii',None), size = ('SquareAuto',None), cellSize = ('5x5',None), anchor = ('sw', None), ) def __init__(self,value='Hello Cruel World!', **kwds): self.pylibdmtx_check() self.value = value for k,(d,c) in self._defaults.items(): v = kwds.pop(k,d) if c: v = c(v) setattr(self,k,v) def rect(self, x, y, w, h, fill=1, stroke=0): self._gadd(Rect(x,y,w,h,strokeColor=None,fillColor=self._fillColor)) def saveState(self,*args,**kwds): pass restoreState = setStrokeColor = saveState def setFillColor(self,c): self._fillColor = c def draw(self): m = DataMatrix(value=self.value,**{k: getattr(self,k) for k in self._defaults}) m.canv = self m.y += m.height g = Group() self._gadd = g.add m.draw() return g
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/dmtx.py
0.663669
0.252718
dmtx.py
pypi
from reportlab.lib.units import inch from reportlab.graphics.barcode.common import Barcode from string import digits as string_digits, whitespace as string_whitespace from reportlab.lib.utils import asNative _fim_patterns = { 'A' : "|| | ||", 'B' : "| || || |", 'C' : "|| | | ||", 'D' : "||| | |||", # XXX There is an E. # The below has been seen, but dunno if it is E or not: # 'E' : '|||| ||||' } _postnet_patterns = { '1' : "...||", '2' : "..|.|", '3' : "..||.", '4' : ".|..|", '5' : ".|.|.", '6' : ".||..", '7' : "|...|", '8' : "|..|.", '9' : "|.|..", '0' : "||...", 'S' : "|", } class FIM(Barcode): """ FIM (Facing ID Marks) encode only one letter. There are currently four defined: A Courtesy reply mail with pre-printed POSTNET B Business reply mail without pre-printed POSTNET C Business reply mail with pre-printed POSTNET D OCR Readable mail without pre-printed POSTNET Options that may be passed to constructor: value (single character string from the set A - D. required.): The value to encode. quiet (bool, default 0): Whether to include quiet zones in the symbol. The following may also be passed, but doing so will generate nonstandard symbols which should not be used. This is mainly documented here to show the defaults: barHeight (float, default 5/8 inch): Height of the code. This might legitimately be overriden to make a taller symbol that will 'bleed' off the edge of the paper, leaving 5/8 inch remaining. lquiet (float, default 1/4 inch): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, default 15/32 inch): Quiet zone size to right left of code, if quiet is true. Sources of information on FIM: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ barWidth = inch * (1.0/32.0) spaceWidth = inch * (1.0/16.0) barHeight = inch * (5.0/8.0) rquiet = inch * (0.25) lquiet = inch * (15.0/32.0) quiet = 0 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.valid = 1 self.validated = '' for c in self.value: if c in string_whitespace: continue elif c in "abcdABCD": self.validated = self.validated + c.upper() else: self.valid = 0 if len(self.validated) != 1: raise ValueError("Input must be exactly one character") return self.validated def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _fim_patterns[c] return self.decomposed def computeSize(self): self._width = (len(self.decomposed) - 1) * self.spaceWidth + self.barWidth if self.quiet: self._width += self.lquiet + self.rquiet self._height = self.barHeight def draw(self): self._calculate() left = self.quiet and self.lquiet or 0 for c in self.decomposed: if c == '|': self.rect(left, 0.0, self.barWidth, self.barHeight) left += self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.value class POSTNET(Barcode): """ POSTNET is used in the US to encode "zip codes" (postal codes) on mail. It can encode 5, 9, or 11 digit codes. I've read that it's pointless to do 5 digits, since USPS will just have to re-print them with 9 or 11 digits. Sources of information on POSTNET: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ quiet = 0 shortHeight = inch * 0.050 barHeight = inch * 0.125 barWidth = inch * 0.018 spaceWidth = inch * 0.0275 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.validated = '' self.valid = 1 count = 0 for c in self.value: if c in (string_whitespace + '-'): pass elif c in string_digits: count = count + 1 if count == 6: self.validated = self.validated + '-' self.validated = self.validated + c else: self.valid = 0 if len(self.validated) not in [5, 10, 12]: self.valid = 0 return self.validated def encode(self): self.encoded = "S" check = 0 for c in self.validated: if c in string_digits: self.encoded = self.encoded + c check = check + int(c) elif c == '-': pass else: raise ValueError("Invalid character in input") check = (10 - check) % 10 self.encoded = self.encoded + repr(check) + 'S' return self.encoded def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _postnet_patterns[c] return self.decomposed def computeSize(self): self._width = len(self.decomposed) * self.barWidth + (len(self.decomposed) - 1) * self.spaceWidth self._height = self.barHeight def draw(self): self._calculate() sdown = self.barHeight - self.shortHeight left = 0 for c in self.decomposed: if c == '.': h = self.shortHeight else: h = self.barHeight self.rect(left, 0.0, self.barWidth, h) left = left + self.barWidth + self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.encoded[1:-1]
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/usps.py
0.692954
0.352759
usps.py
pypi
__version__='3.3.0' __all__= ( 'BarcodeI2of5', 'BarcodeCode128', 'BarcodeStandard93', 'BarcodeExtended93', 'BarcodeStandard39', 'BarcodeExtended39', 'BarcodeMSI', 'BarcodeCodabar', 'BarcodeCode11', 'BarcodeFIM', 'BarcodePOSTNET', 'BarcodeUSPS_4State', ) from reportlab.lib.validators import isInt, isNumber, isString, isColorOrNone, isBoolean, EitherOr, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import rl_exec from reportlab.graphics.shapes import Rect, Group, String from reportlab.graphics.charts.areas import PlotArea ''' #snippet #first make your Drawing from reportlab.graphics.shapes import Drawing d= Drawing(100,50) #create and set up the widget from reportlab.graphics.barcode.widgets import BarcodeStandard93 bc = BarcodeStandard93() bc.value = 'RGB-123456' #add to the drawing and save d.add(bc) # d.save(formats=['gif','pict'],fnRoot='bc_sample') ''' class _BarcodeWidget(PlotArea): _attrMap = AttrMap(BASE=PlotArea, barStrokeColor = AttrMapValue(isColorOrNone, desc='Color of bar borders.'), barFillColor = AttrMapValue(isColorOrNone, desc='Color of bar interior areas.'), barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), value = AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), textColor = AttrMapValue(isColorOrNone, desc='Color of human readable text.'), valid = AttrMapValue(isBoolean), validated = AttrMapValue(isString,desc="validated form of input"), encoded = AttrMapValue(None,desc="encoded form of input"), decomposed = AttrMapValue(isString,desc="decomposed form of input"), canv = AttrMapValue(None,desc="temporarily used for internal methods"), gap = AttrMapValue(isNumberOrNone, desc='Width of inter character gaps.'), ) textColor = barFillColor = black barStrokeColor = None barStrokeWidth = 0 _BCC = None def __init__(self,_value='',**kw): PlotArea.__init__(self) if 'width' in self.__dict__: del self.__dict__['width'] if 'height' in self.__dict__: del self.__dict__['height'] self.x = self.y = 0 kw.setdefault('value',_value) self._BCC.__init__(self,**kw) def rect(self,x,y,w,h,**kw): #this allows the base code to draw rectangles for us using self.rect #using direct keyword argument overrides see eg common.py line 140 on for k,v in (('strokeColor',self.barStrokeColor), ('strokeWidth',self.barStrokeWidth), ('fillColor',self.barFillColor)): kw.setdefault(k,v) self._Gadd(Rect(self.x+x,self.y+y,w,h, **kw)) def draw(self): if not self._BCC: raise NotImplementedError("Abstract class %s cannot be drawn" % self.__class__.__name__) self.canv = self G = Group() self._Gadd = G.add self._Gadd(Rect(self.x,self.y,self.width,self.height,fillColor=None,strokeColor=None,strokeWidth=0.0001)) self._BCC.draw(self) del self.canv, self._Gadd return G def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): self._Gadd(String(self.x+x,self.y+y,text,fontName=fontName,fontSize=fontSize, textAnchor=anchor,fillColor=self.textColor)) def _BCW(doc,codeName,attrMap,mod,value,**kwds): """factory for Barcode Widgets""" _pre_init = kwds.pop('_pre_init','') _methods = kwds.pop('_methods','') name = 'Barcode'+codeName ns = vars().copy() code = 'from %s import %s' % (mod,codeName) rl_exec(code,ns) ns['_BarcodeWidget'] = _BarcodeWidget ns['doc'] = ("\n\t'''%s'''" % doc) if doc else '' code = '''class %(name)s(_BarcodeWidget,%(codeName)s):%(doc)s \t_BCC = %(codeName)s \tcodeName = %(codeName)r \tdef __init__(self,**kw):%(_pre_init)s \t\t_BarcodeWidget.__init__(self,%(value)r,**kw)%(_methods)s''' % ns rl_exec(code,ns) Klass = ns[name] if attrMap: Klass._attrMap = attrMap for k, v in kwds.items(): setattr(Klass,k,v) return Klass BarcodeI2of5 = _BCW( """Interleaved 2 of 5 is used in distribution and warehouse industries. It encodes an even-numbered sequence of numeric digits. There is an optional module 10 check digit; if including this, the total length must be odd so that it becomes even after including the check digit. Otherwise the length must be even. Since the check digit is optional, our library does not check it. """, "I2of5", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).'''), ratio = AttrMapValue(isNumber,'''(float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch))'''), gap = AttrMapValue(isNumberOrNone,'''(float or None, default None): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length.'''), checksum = AttrMapValue(isBoolean,'''(bool, default 1): Whether to compute and include the check digit'''), bearers = AttrMapValue(isNumber,'''(float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on).'''), bearerBox = AttrMapValue(isBoolean,'''(bool, default 0): if True turn bearers into a box'''), quiet = AttrMapValue(isBoolean,'''(bool, default 1): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length.'''), rquiet = AttrMapValue(isNumber,'''(float, defaults as above): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.common', 1234, _tests = [ '12', '1234', '123456', '12345678', '1234567890' ], ) BarcodeCode128 = _BCW("""Code 128 encodes any number of characters in the ASCII character set.""", "Code128", AttrMap(BASE=BarcodeI2of5,UNWANTED=('bearers','checksum','ratio','checksum','stop')), 'reportlab.graphics.barcode.code128', "AB-12345678", _tests = ['ReportLab Rocks!', 'PFWZF'], ) BarcodeCode128Auto = _BCW( 'Modified Code128 to use auto encoding', 'Code128Auto', AttrMap(BASE=BarcodeCode128), 'reportlab.graphics.barcode.code128', 'XY149740345GB' ) BarcodeStandard93=_BCW("""This is a compressed form of Code 39""", "Standard93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "CODE 93", ) BarcodeExtended93=_BCW("""This is a compressed form of Code 39, allowing the full ASCII charset""", "Extended93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "L@@K! Code 93 ;-)", ) BarcodeStandard39=_BCW("""Code39 is widely used in non-retail, especially US defence and health. Allowed characters are 0-9, A-Z (caps only), space, and -.$/+%*.""", "Standard39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B%R", ) BarcodeExtended39=_BCW("""Extended 39 encodes the full ASCII character set by encoding characters as pairs of Code 39 characters; $, /, % and + are used as shift characters.""", "Extended39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B}", ) BarcodeMSI=_BCW("""MSI is used for inventory control in retail applications. There are several methods for calculating check digits so we do not implement one. """, "MSI", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', 1234, ) BarcodeCodabar=_BCW("""Used in blood banks, photo labs and FedEx labels. Encodes 0-9, -$:/.+, and four start/stop characters A-D.""", "Codabar", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', "A012345B", ) BarcodeCode11=_BCW("""Used mostly for labelling telecommunications equipment. It encodes numeric digits.""", 'Code11', AttrMap(BASE=BarcodeI2of5, checksum = AttrMapValue(isInt,'''(integer, default 2): Whether to compute and include the check digit(s). (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2.'''), ), 'reportlab.graphics.barcode.common', "01234545634563", ) BarcodeFIM=_BCW(""" FIM was developed as part of the POSTNET barcoding system. FIM (Face Identification Marking) is used by the cancelling machines to sort mail according to whether or not they have bar code and their postage requirements. There are four types of FIM called FIM A, FIM B, FIM C, and FIM D. The four FIM types have the following meanings: FIM A- Postage required pre-barcoded FIM B - Postage pre-paid, no bar code exists FIM C- Postage prepaid prebarcoded FIM D- Postage required, no bar code exists""", "FIM", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 1/32in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 1/16in): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, default 5/8in): The bar height.'''), quiet = AttrMapValue(isBoolean,'''(bool, default 0): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, default: 15/32in): Quiet zone size to left of code, if quiet is true.'''), rquiet = AttrMapValue(isNumber,'''(float, default 1/4in): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "A", ) BarcodePOSTNET=_BCW('', "POSTNET", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 0.018*in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 0.0275in): width of intercharacter gap.'''), shortHeight = AttrMapValue(isNumber,'''(float, default 0.05in): The short bar height.'''), barHeight = AttrMapValue(isNumber,'''(float, default 0.125in): The full bar height.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "78247-1043", ) BarcodeUSPS_4State=_BCW('', "USPS_4State", AttrMap(BASE=_BarcodeWidget, widthSize = AttrMapValue(isNumber,'''(float, default 1): the bar width size adjustment between 0 and 1.'''), heightSize = AttrMapValue(isNumber,'''(float, default 1): the bar height size adjustment between 0 and 1.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), tracking = AttrMapValue(isString, desc='tracking data'), routing = AttrMapValue(isString, desc='routing data'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), barWidth = AttrMapValue(isNumber, desc='barWidth'), barHeight = AttrMapValue(isNumber, desc='barHeight'), pitch = AttrMapValue(isNumber, desc='pitch'), ), 'reportlab.graphics.barcode.usps4s', '01234567094987654321', _pre_init="\n\t\tkw.setdefault('routing','01234567891')\n", _methods = "\n\tdef annotate(self,x,y,text,fontName,fontSize,anchor='middle'):\n\t\t_BarcodeWidget.annotate(self,x,y,text,fontName,fontSize,anchor='start')\n" ) BarcodeECC200DataMatrix = _BCW( 'ECC200DataMatrix', 'ECC200DataMatrix', AttrMap(BASE=_BarcodeWidget, x=AttrMapValue(isNumber, desc='X position of the lower-left corner of the barcode.'), y=AttrMapValue(isNumber, desc='Y position of the lower-left corner of the barcode.'), barWidth=AttrMapValue(isNumber, desc='Size of data modules.'), barFillColor=AttrMapValue(isColorOrNone, desc='Color of data modules.'), value=AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), height=AttrMapValue(None, desc='ignored'), width=AttrMapValue(None, desc='ignored'), strokeColor=AttrMapValue(None, desc='ignored'), strokeWidth=AttrMapValue(None, desc='ignored'), fillColor=AttrMapValue(None, desc='ignored'), background=AttrMapValue(None, desc='ignored'), debug=AttrMapValue(None, desc='ignored'), gap=AttrMapValue(None, desc='ignored'), row_modules=AttrMapValue(None, desc='???'), col_modules=AttrMapValue(None, desc='???'), row_regions=AttrMapValue(None, desc='???'), col_regions=AttrMapValue(None, desc='???'), cw_data=AttrMapValue(None, desc='???'), cw_ecc=AttrMapValue(None, desc='???'), row_usable_modules = AttrMapValue(None, desc='???'), col_usable_modules = AttrMapValue(None, desc='???'), valid = AttrMapValue(None, desc='???'), validated = AttrMapValue(None, desc='???'), decomposed = AttrMapValue(None, desc='???'), ), 'reportlab.graphics.barcode.ecc200datamatrix', 'JGB 0204H20B012722900021AC35B2100001003241014241014TPS01 WJ067073605GB185 MOUNT PLEASANT MAIL CENTER EC1A1BB9ZGBREC1A1BB EC1A1BB STEST FILE FOR SPEC ' ) if __name__=='__main__': raise ValueError('widgets.py has no script function')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/widgets.py
0.680029
0.206354
widgets.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import Barcode from string import ascii_uppercase, ascii_lowercase, digits as string_digits _patterns = { '0': ("bsbSBsBsb", 0), '1': ("BsbSbsbsB", 1), '2': ("bsBSbsbsB", 2), '3': ("BsBSbsbsb", 3), '4': ("bsbSBsbsB", 4), '5': ("BsbSBsbsb", 5), '6': ("bsBSBsbsb", 6), '7': ("bsbSbsBsB", 7), '8': ("BsbSbsBsb", 8), '9': ("bsBSbsBsb", 9), 'A': ("BsbsbSbsB", 10), 'B': ("bsBsbSbsB", 11), 'C': ("BsBsbSbsb", 12), 'D': ("bsbsBSbsB", 13), 'E': ("BsbsBSbsb", 14), 'F': ("bsBsBSbsb", 15), 'G': ("bsbsbSBsB", 16), 'H': ("BsbsbSBsb", 17), 'I': ("bsBsbSBsb", 18), 'J': ("bsbsBSBsb", 19), 'K': ("BsbsbsbSB", 20), 'L': ("bsBsbsbSB", 21), 'M': ("BsBsbsbSb", 22), 'N': ("bsbsBsbSB", 23), 'O': ("BsbsBsbSb", 24), 'P': ("bsBsBsbSb", 25), 'Q': ("bsbsbsBSB", 26), 'R': ("BsbsbsBSb", 27), 'S': ("bsBsbsBSb", 28), 'T': ("bsbsBsBSb", 29), 'U': ("BSbsbsbsB", 30), 'V': ("bSBsbsbsB", 31), 'W': ("BSBsbsbsb", 32), 'X': ("bSbsBsbsB", 33), 'Y': ("BSbsBsbsb", 34), 'Z': ("bSBsBsbsb", 35), '-': ("bSbsbsBsB", 36), '.': ("BSbsbsBsb", 37), ' ': ("bSBsbsBsb", 38), '*': ("bSbsBsBsb", None), '$': ("bSbSbSbsb", 39), '/': ("bSbSbsbSb", 40), '+': ("bSbsbSbSb", 41), '%': ("bsbSbSbSb", 42) } _stdchrs = string_digits + ascii_uppercase + "-. $/+%" _extended = { '\0': "%U", '\01': "$A", '\02': "$B", '\03': "$C", '\04': "$D", '\05': "$E", '\06': "$F", '\07': "$G", '\010': "$H", '\011': "$I", '\012': "$J", '\013': "$K", '\014': "$L", '\015': "$M", '\016': "$N", '\017': "$O", '\020': "$P", '\021': "$Q", '\022': "$R", '\023': "$S", '\024': "$T", '\025': "$U", '\026': "$V", '\027': "$W", '\030': "$X", '\031': "$Y", '\032': "$Z", '\033': "%A", '\034': "%B", '\035': "%C", '\036': "%D", '\037': "%E", '!': "/A", '"': "/B", '#': "/C", '$': "/D", '%': "/E", '&': "/F", '\'': "/G", '(': "/H", ')': "/I", '*': "/J", '+': "/K", ',': "/L", '/': "/O", ':': "/Z", ';': "%F", '<': "%G", '=': "%H", '>': "%I", '?': "%J", '@': "%V", '[': "%K", '\\': "%L", ']': "%M", '^': "%N", '_': "%O", '`': "%W", 'a': "+A", 'b': "+B", 'c': "+C", 'd': "+D", 'e': "+E", 'f': "+F", 'g': "+G", 'h': "+H", 'i': "+I", 'j': "+J", 'k': "+K", 'l': "+L", 'm': "+M", 'n': "+N", 'o': "+O", 'p': "+P", 'q': "+Q", 'r': "+R", 's': "+S", 't': "+T", 'u': "+U", 'v': "+V", 'w': "+W", 'x': "+X", 'y': "+Y", 'z': "+Z", '{': "%P", '|': "%Q", '}': "%R", '~': "%S", '\177': "%T" } _extchrs = _stdchrs + ascii_lowercase + \ "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017" + \ "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + \ "*!'#&\"(),:;<=>?@[\\]^_`{|}~\177" def _encode39(value, cksum, stop): v = sum([_patterns[c][1] for c in value]) % 43 if cksum: value += _stdchrs[v] if stop: value = '*'+value+'*' return value class _Code39Base(Barcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 gap = None barHeight = None ratio = 2.2 checksum = 1 bearers = 0.0 stop = 1 def __init__(self, value = "", **args): value = asNative(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def decompose(self): dval = "" for c in self.encoded: dval = dval + _patterns[c][0] + 'i' self.decomposed = dval[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded class Standard39(_Code39Base): """ Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html http://www.adams1.com/pub/russadam/39code.html http://www.barcodeman.com/c39_1.html Official Spec, "ANSI/AIM BC1-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = [].append self.valid = 1 for c in self.value: if c in ascii_lowercase: c = c.upper() if c not in _stdchrs: self.valid = 0 continue vval(c) self.validated = ''.join(vval.__self__) return self.validated def encode(self): self.encoded = _encode39(self.validated, self.checksum, self.stop) return self.encoded class Extended39(_Code39Base): """ Extended Code 39 is a convention for encoding additional characters not present in stanmdard Code 39 by using pairs of characters to represent the characters missing in Standard Code 39. See Standard39 for arguments. Sources of Information on Extended Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html http://www.barcodeman.com/c39_ext.html """ def validate(self): vval = "" self.valid = 1 for c in self.value: if c not in _extchrs: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = "" for c in self.validated: if c in _extended: self.encoded = self.encoded + _extended[c] elif c in _stdchrs: self.encoded = self.encoded + c else: raise ValueError self.encoded = _encode39(self.encoded, self.checksum,self.stop) return self.encoded
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/barcode/code39.py
0.42919
0.47926
code39.py
pypi
__version__='3.3.0' __doc__='''This module defines a Area mixin classes''' from reportlab.lib.validators import isNumber, isColorOrNone, isNoneOrShape from reportlab.graphics.widgetbase import Widget from reportlab.graphics.shapes import Rect, Group, Line, Polygon from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import grey class PlotArea(Widget): "Abstract base class representing a chart's plot area, pretty unusable by itself." _attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the lower-left corner of the chart.'), y = AttrMapValue(isNumber, desc='Y position of the lower-left corner of the chart.'), width = AttrMapValue(isNumber, desc='Width of the chart.'), height = AttrMapValue(isNumber, desc='Height of the chart.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color of the plot area border.'), strokeWidth = AttrMapValue(isNumber, desc='Width plot area border.'), fillColor = AttrMapValue(isColorOrNone, desc='Color of the plot area interior.'), background = AttrMapValue(isNoneOrShape, desc='Handle to background object e.g. Rect(0,0,width,height).'), debug = AttrMapValue(isNumber, desc='Used only for debugging.'), ) def __init__(self): self.x = 20 self.y = 10 self.height = 85 self.width = 180 self.strokeColor = None self.strokeWidth = 1 self.fillColor = None self.background = None self.debug = 0 def makeBackground(self): if self.background is not None: BG = self.background if isinstance(BG,Group): g = BG for bg in g.contents: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height else: g = Group() if type(BG) not in (type(()),type([])): BG=(BG,) for bg in BG: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height g.add(bg) return g else: strokeColor,strokeWidth,fillColor=self.strokeColor, self.strokeWidth, self.fillColor if (strokeWidth and strokeColor) or fillColor: g = Group() _3d_dy = getattr(self,'_3d_dy',None) x = self.x y = self.y h = self.height w = self.width if _3d_dy is not None: _3d_dx = self._3d_dx if fillColor and not strokeColor: from reportlab.lib.colors import Blacker c = Blacker(fillColor, getattr(self,'_3d_blacken',0.7)) else: c = strokeColor if not strokeWidth: strokeWidth = 0.5 if fillColor or strokeColor or c: bg = Polygon([x,y,x,y+h,x+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fillColor) g.add(bg) g.add(Line(x,y,x+_3d_dx,y+_3d_dy, strokeWidth=0.5, strokeColor=c)) g.add(Line(x+_3d_dx,y+_3d_dy, x+_3d_dx,y+h+_3d_dy,strokeWidth=0.5, strokeColor=c)) fc = Blacker(c, getattr(self,'_3d_blacken',0.8)) g.add(Polygon([x,y,x+_3d_dx,y+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fc)) bg = Line(x+_3d_dx,y+_3d_dy, x+w+_3d_dx,y+_3d_dy,strokeWidth=0.5, strokeColor=c) else: bg = None else: bg = Rect(x, y, w, h, strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor) if bg: g.add(bg) return g else: return None
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/areas.py
0.821331
0.218211
areas.py
pypi
from reportlab.lib.colors import _PCMYK_black from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.shapes import Circle, Drawing, Group, Line, Rect, String from reportlab.graphics.widgetbase import Widget from reportlab.lib.attrmap import * from reportlab.lib.validators import * from reportlab.lib.units import cm from reportlab.pdfbase.pdfmetrics import getFont from reportlab.graphics.charts.lineplots import _maxWidth class DotBox(Widget): """Returns a dotbox widget.""" #Doesn't use TypedPropertyCollection for labels - this can be a later improvement _attrMap = AttrMap( xlabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="List of text labels for boxes on left hand side"), ylabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="Text label for second box on left hand side"), labelFontName = AttrMapValue(isString, desc="Name of font used for the labels"), labelFontSize = AttrMapValue(isNumber, desc="Size of font used for the labels"), labelOffset = AttrMapValue(isNumber, desc="Space between label text and grid edge"), strokeWidth = AttrMapValue(isNumber, desc='Width of the grid and dot outline'), gridDivWidth = AttrMapValue(isNumber, desc="Width of each 'box'"), gridColor = AttrMapValue(isColor, desc='Colour for the box and gridding'), dotDiameter = AttrMapValue(isNumber, desc="Diameter of the circle used for the 'dot'"), dotColor = AttrMapValue(isColor, desc='Colour of the circle on the box'), dotXPosition = AttrMapValue(isNumber, desc='X Position of the circle'), dotYPosition = AttrMapValue(isNumber, desc='X Position of the circle'), x = AttrMapValue(isNumber, desc='X Position of dotbox'), y = AttrMapValue(isNumber, desc='Y Position of dotbox'), ) def __init__(self): self.xlabels=["Value", "Blend", "Growth"] self.ylabels=["Small", "Medium", "Large"] self.labelFontName = "Helvetica" self.labelFontSize = 6 self.labelOffset = 5 self.strokeWidth = 0.5 self.gridDivWidth=0.5*cm self.gridColor=colors.Color(25/255.0,77/255.0,135/255.0) self.dotDiameter=0.4*cm self.dotColor=colors.Color(232/255.0,224/255.0,119/255.0) self.dotXPosition = 1 self.dotYPosition = 1 self.x = 30 self.y = 5 def _getDrawingDimensions(self): leftPadding=rightPadding=topPadding=bottomPadding=5 #find width of grid tx=len(self.xlabels)*self.gridDivWidth #add padding (and offset) tx=tx+leftPadding+rightPadding+self.labelOffset #add in maximum width of text tx=tx+_maxWidth(self.xlabels, self.labelFontName, self.labelFontSize) #find height of grid ty=len(self.ylabels)*self.gridDivWidth #add padding (and offset) ty=ty+topPadding+bottomPadding+self.labelOffset #add in maximum width of text ty=ty+_maxWidth(self.ylabels, self.labelFontName, self.labelFontSize) #print (tx, ty) return (tx,ty) def demo(self,drawing=None): if not drawing: tx,ty=self._getDrawingDimensions() drawing = Drawing(tx,ty) drawing.add(self.draw()) return drawing def draw(self): g = Group() #box g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth, strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=None)) #internal gridding for f in range (1,len(self.ylabels)): #horizontal g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x, y1 = self.y+f*self.gridDivWidth, x2 = self.x+len(self.xlabels)*self.gridDivWidth, y2 = self.y+f*self.gridDivWidth)) for f in range (1,len(self.xlabels)): #vertical g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x+f*self.gridDivWidth, y1 = self.y, x2 = self.x+f*self.gridDivWidth, y2 = self.y+len(self.ylabels)*self.gridDivWidth)) # draw the 'dot' g.add(Circle(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=self.dotColor, cx = self.x+(self.dotXPosition*self.gridDivWidth), cy = self.y+(self.dotYPosition*self.gridDivWidth), r = self.dotDiameter/2.0)) #used for centering y-labels (below) ascent=getFont(self.labelFontName).face.ascent if ascent==0: ascent=0.718 # default (from helvetica) ascent=ascent*self.labelFontSize # normalize #do y-labels if self.ylabels != None: for f in range (len(self.ylabels)-1,-1,-1): if self.ylabels[f]!= None: g.add(String(strokeColor=self.gridColor, text = self.ylabels[f], fontName = self.labelFontName, fontSize = self.labelFontSize, fillColor=_PCMYK_black, x = self.x-self.labelOffset, y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0), textAnchor = 'end')) #do x-labels if self.xlabels != None: for f in range (0,len(self.xlabels)): if self.xlabels[f]!= None: l=Label() l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0 l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset l.angle=90 l.textAnchor='start' l.fontName = self.labelFontName l.fontSize = self.labelFontSize l.fillColor = _PCMYK_black l.setText(self.xlabels[f]) l.boxAnchor = 'sw' l.draw() g.add(l) return g if __name__ == "__main__": d = DotBox() d.demo().save(fnRoot="dotbox")
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/dotbox.py
0.609408
0.25767
dotbox.py
pypi
__version__='3.3.0' __doc__="Utilities used here and there." from time import mktime, gmtime, strftime from math import log10, pi, floor, sin, cos, hypot import weakref from reportlab.graphics.shapes import transformPoints, inverse, Ellipse, Group, String, numericXShift from reportlab.lib.utils import flatten from reportlab.pdfbase.pdfmetrics import stringWidth ### Dinu's stuff used in some line plots (likely to vansih). def mkTimeTuple(timeString): "Convert a 'dd/mm/yyyy' formatted string to a tuple for use in the time module." L = [0] * 9 dd, mm, yyyy = list(map(int, timeString.split('/'))) L[:3] = [yyyy, mm, dd] return tuple(L) def str2seconds(timeString): "Convert a number of seconds since the epoch into a date string." return mktime(mkTimeTuple(timeString)) def seconds2str(seconds): "Convert a date string into the number of seconds since the epoch." return strftime('%Y-%m-%d', gmtime(seconds)) ### Aaron's rounding function for making nice values on axes. def nextRoundNumber(x): """Return the first 'nice round number' greater than or equal to x Used in selecting apropriate tick mark intervals; we say we want an interval which places ticks at least 10 points apart, work out what that is in chart space, and ask for the nextRoundNumber(). Tries the series 1,2,5,10,20,50,100.., going up or down as needed. """ #guess to nearest order of magnitude if x in (0, 1): return x if x < 0: return -1.0 * nextRoundNumber(-x) else: lg = int(log10(x)) if lg == 0: if x < 1: base = 0.1 else: base = 1.0 elif lg < 0: base = 10.0 ** (lg - 1) else: base = 10.0 ** lg # e.g. base(153) = 100 # base will always be lower than x if base >= x: return base * 1.0 elif (base * 2) >= x: return base * 2.0 elif (base * 5) >= x: return base * 5.0 else: return base * 10.0 _intervals=(.1, .2, .25, .5) _j_max=len(_intervals)-1 def find_interval(lo,hi,I=5): 'determine tick parameters for range [lo, hi] using I intervals' if lo >= hi: if lo==hi: if lo==0: lo = -.1 hi = .1 else: lo = 0.9*lo hi = 1.1*hi else: raise ValueError("lo>hi") x=(hi - lo)/float(I) b= (x>0 and (x<1 or x>10)) and 10**floor(log10(x)) or 1 b = b while 1: a = x/b if a<=_intervals[-1]: break b = b*10 j = 0 while a>_intervals[j]: j = j + 1 while 1: ss = _intervals[j]*b n = lo/ss l = int(n)-(n<0) n = ss*l x = ss*(l+I) a = I*ss if n>0: if a>=hi: n = 0.0 x = a elif hi<0: a = -a if lo>a: n = a x = 0 if hi<=x and n<=lo: break j = j + 1 if j>_j_max: j = 0 b = b*10 return n, x, ss, lo - n + x - hi def find_good_grid(lower,upper,n=(4,5,6,7,8,9), grid=None): if grid: t = divmod(lower,grid)[0] * grid hi, z = divmod(upper,grid) if z>1e-8: hi = hi+1 hi = hi*grid else: try: n[0] except TypeError: n = range(max(1,n-2),max(n+3,2)) w = 1e308 for i in n: z=find_interval(lower,upper,i) if z[3]<w: t, hi, grid = z[:3] w=z[3] return t, hi, grid def ticks(lower, upper, n=(4,5,6,7,8,9), split=1, percent=0, grid=None, labelVOffset=0): ''' return tick positions and labels for range lower<=x<=upper n=number of intervals to try (can be a list or sequence) split=1 return ticks then labels else (tick,label) pairs ''' t, hi, grid = find_good_grid(lower, upper, n, grid) power = floor(log10(grid)) if power==0: power = 1 w = grid/10.**power w = int(w)!=w if power > 3 or power < -3: format = '%+'+repr(w+7)+'.0e' else: if power >= 0: digits = int(power)+w format = '%' + repr(digits)+'.0f' else: digits = w-int(power) format = '%'+repr(digits+2)+'.'+repr(digits)+'f' if percent: format=format+'%%' T = [] n = int(float(hi-t)/grid+0.1)+1 if split: labels = [] for i in range(n): v = t+grid*i T.append(v) labels.append(format % (v+labelVOffset)) return T, labels else: for i in range(n): v = t+grid*i T.append((v, format % (v+labelVOffset))) return T def findNones(data): m = len(data) if None in data: b = 0 while b<m and data[b] is None: b += 1 if b==m: return data l = m-1 while data[l] is None: l -= 1 l+=1 if b or l: data = data[b:l] I = [i for i in range(len(data)) if data[i] is None] for i in I: data[i] = 0.5*(data[i-1]+data[i+1]) return b, l, data return 0,m,data def pairFixNones(pairs): Y = [x[1] for x in pairs] b,l,nY = findNones(Y) m = len(Y) if b or l<m or nY!=Y: if b or l<m: pairs = pairs[b:l] pairs = [(x[0],y) for x,y in zip(pairs,nY)] return pairs def maverage(data,n=6): data = (n-1)*[data[0]]+data data = [float(sum(data[i-n:i]))/n for i in range(n,len(data)+1)] return data def pairMaverage(data,n=6): return [(x[0],s) for x,s in zip(data, maverage([x[1] for x in data],n))] class DrawTimeCollector: ''' generic mechanism for collecting information about nodes at the time they are about to be drawn ''' def __init__(self,formats=['gif']): self._nodes = weakref.WeakKeyDictionary() self.clear() self._pmcanv = None self.formats = formats self.disabled = False def clear(self): self._info = [] self._info_append = self._info.append def record(self,func,node,*args,**kwds): self._nodes[node] = (func,args,kwds) node.__dict__['_drawTimeCallback'] = self def __call__(self,node,canvas,renderer): func = self._nodes.get(node,None) if func: func, args, kwds = func i = func(node,canvas,renderer, *args, **kwds) if i is not None: self._info_append(i) @staticmethod def rectDrawTimeCallback(node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return x1 = node.x y1 = node.y x2 = x1 + node.width y2 = y1 + node.height D = kwds.copy() D['rect']=DrawTimeCollector.transformAndFlatten(A,((x1,y1),(x2,y2))) return D @staticmethod def transformAndFlatten(A,p): ''' transform an flatten a list of points A transformation matrix p points [(x0,y0),....(xk,yk).....] ''' if tuple(A)!=(1,0,0,1,0,0): iA = inverse(A) p = transformPoints(iA,p) return tuple(flatten(p)) @property def pmcanv(self): if not self._pmcanv: import renderPM self._pmcanv = renderPM.PMCanvas(1,1) return self._pmcanv def wedgeDrawTimeCallback(self,node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return if isinstance(node,Ellipse): c = self.pmcanv c.ellipse(node.cx, node.cy, node.rx,node.ry) p = c.vpath p = [(x[1],x[2]) for x in p] else: p = node.asPolygon().points p = [(p[i],p[i+1]) for i in range(0,len(p),2)] D = kwds.copy() D['poly'] = self.transformAndFlatten(A,p) return D def save(self,fnroot): ''' save the current information known to this collector fnroot is the root name of a resource to name the saved info override this to get the right semantics for your collector ''' import pprint f=open(fnroot+'.default-collector.out','w') try: pprint.pprint(self._info,f) finally: f.close() def xyDist(xxx_todo_changeme, xxx_todo_changeme1 ): '''return distance between two points''' (x0,y0) = xxx_todo_changeme (x1,y1) = xxx_todo_changeme1 return hypot((x1-x0),(y1-y0)) def lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5 ): (x00,y00) = xxx_todo_changeme2 (x01,y01) = xxx_todo_changeme3 (x10,y10) = xxx_todo_changeme4 (x11,y11) = xxx_todo_changeme5 p = x00,y00 r = x01-x00,y01-y00 q = x10,y10 s = x11-x10,y11-y10 rs = float(r[0]*s[1]-r[1]*s[0]) qp = q[0]-p[0],q[1]-p[1] qpr = qp[0]*r[1]-qp[1]*r[0] qps = qp[0]*s[1]-qp[1]*s[0] if abs(rs)<1e-8: if abs(qpr)<1e-8: return 'collinear' return None t = qps/rs u = qpr/rs if 0<=t<=1 and 0<=u<=1: return p[0]+t*r[0], p[1]+t*r[1] def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside=0, G=None,textAnchor='start'): '''make a group with circular text in it''' if not G: G = Group() angle %= 360 pi180 = pi/180 phi = angle*pi180 width = stringWidth(text, fontName, fontSize) sig = inside and -1 or 1 hsig = sig*0.5 sig90 = sig*90 if textAnchor!='start': if textAnchor=='middle': phi += sig*(0.5*width)/radius elif textAnchor=='end': phi += sig*float(width)/radius elif textAnchor=='numeric': phi += sig*float(numericXShift(textAnchor,text,width,fontName,fontSize,None))/radius for letter in text: width = stringWidth(letter, fontName, fontSize) beta = float(width)/radius h = Group() h.add(String(0, 0, letter, fontName=fontName,fontSize=fontSize,textAnchor="start")) h.translate(x+cos(phi)*radius,y+sin(phi)*radius) #translate to radius and angle h.rotate((phi-hsig*beta)/pi180-sig90) # rotate as needed G.add(h) #add to main group phi -= sig*beta #increment return G class CustomDrawChanger: ''' a class to simplify making changes at draw time ''' def __init__(self): self.store = None def __call__(self,change,obj): if change: self.store = self._changer(obj) assert isinstance(self.store,dict), '%s.changer should return a dict of changed attributes' % self.__class__.__name__ elif self.store is not None: for a,v in self.store.items(): setattr(obj,a,v) self.store = None def _changer(self,obj): ''' When implemented this method should return a dictionary of original attribute values so that a future self(False,obj) can restore them. ''' raise RuntimeError('Abstract method _changer called') class FillPairedData(list): def __init__(self,v,other=0): list.__init__(self,v) self.other = other
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/utils.py
0.541045
0.34308
utils.py
pypi
__version__='3.3.0' __doc__="""This will be a collection of legends to be used with charts.""" import copy from reportlab.lib import colors from reportlab.lib.validators import isNumber, OneOf, isString, isColorOrNone,\ isNumberOrNone, isListOfNumbersOrNone, isBoolean,\ EitherOr, NoneOr, AutoOr, isAuto, Auto, isBoxAnchor, SequenceOf, isInstanceOf from reportlab.lib.attrmap import * from reportlab.pdfbase.pdfmetrics import stringWidth, getFont from reportlab.graphics.widgetbase import Widget, TypedPropertyCollection, PropHolder from reportlab.graphics.shapes import Drawing, Group, String, Rect, Line, STATE_DEFAULTS from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol from reportlab.lib.utils import isSeq, find_locals, isStr, asNative from reportlab.graphics.shapes import _baseGFontName def _transMax(n,A): X = n*[0] m = 0 for a in A: m = max(m,len(a)) for i,x in enumerate(a): X[i] = max(X[i],x) X = [0] + X[:m] for i in range(m): X[i+1] += X[i] return X def _objStr(s): if isStr(s): return asNative(s) else: return str(s) def _getStr(s): if isSeq(s): return list(map(_getStr,s)) else: return _objStr(s) def _getLines(s): if isSeq(s): return tuple([(x or '').split('\n') for x in s]) else: return (s or '').split('\n') def _getLineCount(s): T = _getLines(s) if isSeq(s): return max([len(x) for x in T]) else: return len(T) def _getWidths(i,s, fontName, fontSize, subCols): S = [] aS = S.append if isSeq(s): for j,t in enumerate(s): sc = subCols[j,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in t.split('\n')] m = max(sc.minWidth,m and max(m) or 0) aS(m) aS(sc.rpad) del S[-1] else: sc = subCols[0,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in s.split('\n')] aS(max(sc.minWidth,m and max(m) or 0)) return S class SubColProperty(PropHolder): dividerLines = 0 _attrMap = AttrMap( minWidth = AttrMapValue(isNumber,desc="minimum width for this subcol"), rpad = AttrMapValue(isNumber,desc="right padding for this subcol"), align = AttrMapValue(OneOf('left','right','center','centre','numeric'),desc='alignment in subCol'), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), leading = AttrMapValue(isNumberOrNone, desc="leading for the strings"), fillColor = AttrMapValue(isColorOrNone, desc="fontColor"), underlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="underline definitions"), overlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="overline definitions"), dx = AttrMapValue(isNumber, desc="x offset from default position"), dy = AttrMapValue(isNumber, desc="y offset from default position"), vAlign = AttrMapValue(OneOf('top','bottom','middle'),desc='vertical alignment in the row'), ) class LegendCallout: def _legendValues(legend,*args): '''return a tuple of values from the first function up the stack with isinstance(self,legend)''' L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([L[a] for a in args]) _legendValues = staticmethod(_legendValues) def _selfOrLegendValues(self,legend,*args): L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([getattr(self,a,L[a]) for a in args]) def __call__(self,legend,g,thisx,y,colName): col, name = colName class LegendSwatchCallout(LegendCallout): def __call__(self,legend,g,thisx,y,i,colName,swatch): col, name = colName class LegendColEndCallout(LegendCallout): def __call__(self,legend, g, x, xt, y, width, lWidth): pass class Legend(Widget): """A simple legend containing rectangular swatches and strings. The swatches are filled rectangles whenever the respective color object in 'colorNamePairs' is a subclass of Color in reportlab.lib.colors. Otherwise the object passed instead is assumed to have 'x', 'y', 'width' and 'height' attributes. A legend then tries to set them or catches any error. This lets you plug-in any widget you like as a replacement for the default rectangular swatches. Strings can be nicely aligned left or right to the swatches. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate of upper-left reference point"), y = AttrMapValue(isNumber, desc="y-coordinate of upper-left reference point"), deltax = AttrMapValue(isNumberOrNone, desc="x-distance between neighbouring swatches"), deltay = AttrMapValue(isNumberOrNone, desc="y-distance between neighbouring swatches"), dxTextSpace = AttrMapValue(isNumber, desc="Distance between swatch rectangle and text"), autoXPadding = AttrMapValue(isNumber, desc="x Padding between columns if deltax=None",advancedUsage=1), autoYPadding = AttrMapValue(isNumber, desc="y Padding between rows if deltay=None",advancedUsage=1), yGap = AttrMapValue(isNumber, desc="Additional gap between rows",advancedUsage=1), dx = AttrMapValue(isNumber, desc="Width of swatch rectangle"), dy = AttrMapValue(isNumber, desc="Height of swatch rectangle"), columnMaximum = AttrMapValue(isNumber, desc="Max. number of items per column"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text with respect to swatches"), colorNamePairs = AttrMapValue(None, desc="List of color/name tuples (color can also be widget)"), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), leading = AttrMapValue(isNumberOrNone, desc="text leading"), fillColor = AttrMapValue(isColorOrNone, desc="swatches filling color"), strokeColor = AttrMapValue(isColorOrNone, desc="Border color of the swatches"), strokeWidth = AttrMapValue(isNumber, desc="Width of the border color of the swatches"), swatchMarker = AttrMapValue(NoneOr(AutoOr(isSymbol)), desc="None, Auto() or makeMarker('Diamond') ...",advancedUsage=1), callout = AttrMapValue(None, desc="a user callout(self,g,x,y,(color,text))",advancedUsage=1), boxAnchor = AttrMapValue(isBoxAnchor,'Anchor point for the legend area'), variColumn = AttrMapValue(isBoolean,'If true column widths may vary (default is false)',advancedUsage=1), dividerLines = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),'If 1 we have dividers between the rows | 2 for extra top | 4 for bottom',advancedUsage=1), dividerWidth = AttrMapValue(isNumber, desc="dividerLines width",advancedUsage=1), dividerColor = AttrMapValue(isColorOrNone, desc="dividerLines color",advancedUsage=1), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.',advancedUsage=1), dividerOffsX = AttrMapValue(SequenceOf(isNumber,emptyOK=0,lo=2,hi=2), desc='divider lines X offsets',advancedUsage=1), dividerOffsY = AttrMapValue(isNumber, desc="dividerLines Y offset",advancedUsage=1), colEndCallout = AttrMapValue(None, desc="a user callout(self,g, x, xt, y,width, lWidth)",advancedUsage=1), subCols = AttrMapValue(None,desc="subColumn properties"), swatchCallout = AttrMapValue(None, desc="a user swatch callout(self,g,x,y,i,(col,name),swatch)",advancedUsage=1), swdx = AttrMapValue(isNumber, desc="x position adjustment for the swatch"), swdy = AttrMapValue(isNumber, desc="y position adjustment for the swatch"), ) def __init__(self): # Upper-left reference point. self.x = 0 self.y = 0 # Alginment of text with respect to swatches. self.alignment = "left" # x- and y-distances between neighbouring swatches. self.deltax = 75 self.deltay = 20 self.autoXPadding = 5 self.autoYPadding = 2 # Size of swatch rectangle. self.dx = 10 self.dy = 10 self.swdx = 0 self.swdy = 0 # Distance between swatch rectangle and text. self.dxTextSpace = 10 # Max. number of items per column. self.columnMaximum = 3 # Color/name pairs. self.colorNamePairs = [ (colors.red, "red"), (colors.blue, "blue"), (colors.green, "green"), (colors.pink, "pink"), (colors.yellow, "yellow") ] # Font name and size of the labels. self.fontName = STATE_DEFAULTS['fontName'] self.fontSize = STATE_DEFAULTS['fontSize'] self.leading = None #will be used as 1.2*fontSize self.fillColor = STATE_DEFAULTS['fillColor'] self.strokeColor = STATE_DEFAULTS['strokeColor'] self.strokeWidth = STATE_DEFAULTS['strokeWidth'] self.swatchMarker = None self.boxAnchor = 'nw' self.yGap = 0 self.variColumn = 0 self.dividerLines = 0 self.dividerWidth = 0.5 self.dividerDashArray = None self.dividerColor = colors.black self.dividerOffsX = (0,0) self.dividerOffsY = 0 self.colEndCallout = None self._init_subCols() def _init_subCols(self): sc = self.subCols = TypedPropertyCollection(SubColProperty) sc.rpad = 1 sc.dx = sc.dy = sc.minWidth = 0 sc.align = 'right' sc[0].align = 'left' sc.vAlign = 'top' #that's current sc.leading = None def _getChartStyleName(self,chart): for a in 'lines', 'bars', 'slices', 'strands': if hasattr(chart,a): return a return None def _getChartStyle(self,chart): return getattr(chart,self._getChartStyleName(chart),None) def _getTexts(self,colorNamePairs): if not isAuto(colorNamePairs): texts = [_getStr(p[1]) for p in colorNamePairs] else: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) texts = [chart.getSeriesName(i,'series %d' % i) for i in range(chart._seriesCount)] return texts def _calculateMaxBoundaries(self, colorNamePairs): "Calculate the maximum width of some given strings." fontName = self.fontName fontSize = self.fontSize subCols = self.subCols M = [_getWidths(i, m, fontName, fontSize, subCols) for i,m in enumerate(self._getTexts(colorNamePairs))] if not M: return [0,0] n = max([len(m) for m in M]) if self.variColumn: columnMaximum = self.columnMaximum return [_transMax(n,M[r:r+columnMaximum]) for r in range(0,len(M),self.columnMaximum)] else: return _transMax(n,M) def _calcHeight(self): dy = self.dy yGap = self.yGap thisy = upperlefty = self.y - dy fontSize = self.fontSize fontName = self.fontName ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 deltay = self.deltay if not deltay: deltay = max(dy,leading)+self.autoYPadding columnCount = 0 count = 0 lowy = upperlefty lim = self.columnMaximum - 1 for name in self._getTexts(self.colorNamePairs): y0 = thisy+(dy-ascent)*0.5 y = y0 - _getLineCount(name)*leading leadingMove = 2*y0-y-thisy newy = thisy-max(deltay,leadingMove)-yGap lowy = min(y,newy,lowy) if count==lim: count = 0 thisy = upperlefty columnCount += 1 else: thisy = newy count = count+1 return upperlefty - lowy def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): return Rect(x, thisy, dx, dy, fillColor = fillColor, strokeColor = strokeColor, strokeWidth = strokeWidth, ) def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = sum([m[-1] for m in maxWidth])+xW*nCols else: deltax = max(maxWidth[-1]+xW,deltax) width = nCols*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) scallout = getattr(self,'swatchCallout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in range(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i/(columnMaximum*1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": x = thisx xn = thisx+jOffs[-1]+dxTextSpace elif alignment == "right": x = thisx+dx+dxTextSpace xn = thisx else: raise ValueError("bad alignment") if not isSeq(name): T = [T] lineCount = _getLineCount(name) yd = y for k,lines in enumerate(T): y = y0 kk = k*2 x1 = x+jOffs[kk] x2 = x+jOffs[kk+1] sc = subCols[k,i] anchor = sc.align scdx = sc.dx scdy = sc.dy fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) fC = getattr(sc,'fillColor',fillColor) fL = sc.leading or 1.2*fontSize if fN==fontName: fA = (ascent*fS)/fontSize else: fA = getFont(fontName).face.ascent/1000. if fA==0: fA=0.718 fA *= fS vA = sc.vAlign if vA=='top': vAdy = 0 else: vAdy = -fL * (lineCount - len(lines)) if vA=='middle': vAdy *= 0.5 if anchor=='left': anchor = 'start' xoffs = x1 elif anchor=='right': anchor = 'end' xoffs = x2 elif anchor=='numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5*(x1+x2) for t in lines: aS(String(xoffs+scdx,y+scdy+vAdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) y -= fL yd = min(yd,y) y += fL for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): il = getattr(sc,a,None) if il: if not isinstance(il,(tuple,list)): il = (il,) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... swatchX = x + getattr(self,'swdx',0) swatchY = thisy + getattr(self,'swdy',0) if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) else: c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = swatchX c.y = swatchY c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self,g,thisx,y0,i,(col,name),c) for s in S: g.add(s) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += jOffs[-1]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g def demo(self): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'left' legend.x = 0 legend.y = 100 legend.dxTextSpace = 5 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d class TotalAnnotator(LegendColEndCallout): def __init__(self, lText='Total', rText='0.0', fontName=_baseGFontName, fontSize=10, fillColor=colors.black, strokeWidth=0.5, strokeColor=colors.black, strokeDashArray=None, dx=0, dy=0, dly=0, dlx=(0,0)): self.lText = lText self.rText = rText self.fontName = fontName self.fontSize = fontSize self.fillColor = fillColor self.dy = dy self.dx = dx self.dly = dly self.dlx = dlx self.strokeWidth = strokeWidth self.strokeColor = strokeColor self.strokeDashArray = strokeDashArray def __call__(self,legend, g, x, xt, y, width, lWidth): from reportlab.graphics.shapes import String, Line fontSize = self.fontSize fontName = self.fontName fillColor = self.fillColor strokeColor = self.strokeColor strokeWidth = self.strokeWidth ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 yt = y+self.dy-ascent*1.3 if self.lText and fillColor: g.add(String(xt,yt,self.lText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "start")) if self.rText: g.add(String(xt+width,yt,self.rText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "end")) if strokeWidth and strokeColor: yL = y+self.dly-leading g.add(Line(x+self.dlx[0],yL,x+self.dlx[1]+lWidth,yL, strokeColor=strokeColor, strokeWidth=strokeWidth, strokeDashArray=self.strokeDashArray)) class LineSwatch(Widget): """basically a Line with properties added so it can be used in a LineLegend""" _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate for swatch line start point"), y = AttrMapValue(isNumber, desc="y-coordinate for swatch line start point"), width = AttrMapValue(isNumber, desc="length of swatch line"), height = AttrMapValue(isNumber, desc="used for line strokeWidth"), strokeColor = AttrMapValue(isColorOrNone, desc="color of swatch line"), strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc="dash array for swatch line"), ) def __init__(self): from reportlab.lib.colors import red self.x = 0 self.y = 0 self.width = 20 self.height = 1 self.strokeColor = red self.strokeDashArray = None def draw(self): l = Line(self.x,self.y,self.x+self.width,self.y) l.strokeColor = self.strokeColor l.strokeDashArray = self.strokeDashArray l.strokeWidth = self.height return l class LineLegend(Legend): """A subclass of Legend for drawing legends with lines as the swatches rather than rectangles. Useful for lineCharts and linePlots. Should be similar in all other ways the the standard Legend class. """ def __init__(self): Legend.__init__(self) # Size of swatch rectangle. self.dx = 10 self.dy = 2 def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): l = LineSwatch() l.x = x l.y = thisy l.width = dx l.height = dy l.strokeColor = fillColor return l
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/legends.py
0.778018
0.232898
legends.py
pypi
from reportlab.graphics.shapes import Drawing, Polygon, Line def _getShaded(col,shd=None,shading=0.1): if shd is None: from reportlab.lib.colors import Blacker if col: shd = Blacker(col,1-shading) return shd def _getLit(col,shd=None,lighting=0.1): if shd is None: from reportlab.lib.colors import Whiter if col: shd = Whiter(col,1-lighting) return shd def _draw_3d_bar(G, x1, x2, y0, yhigh, xdepth, ydepth, fillColor=None, fillColorShaded=None, strokeColor=None, strokeWidth=1, shading=0.1): fillColorShaded = _getShaded(fillColor,None,shading) fillColorShadedTop = _getShaded(fillColor,None,shading/2.0) def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): G.add(Polygon((x1,y1, x1+xoff,y1+yoff, x2+xoff,y2+yoff, x2,y2), strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor,strokeLineJoin=1)) usd = max(y0, yhigh) if xdepth or ydepth: if y0!=yhigh: #non-zero height _add_3d_bar( x2, x2, y0, yhigh, xdepth, ydepth, fillColor=fillColorShaded) #side _add_3d_bar(x1, x2, usd, usd, xdepth, ydepth, fillColor=fillColorShadedTop) #top G.add(Polygon((x1,y0,x2,y0,x2,yhigh,x1,yhigh), strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor,strokeLineJoin=1)) #front if xdepth or ydepth: G.add(Line( x1, usd, x2, usd, strokeWidth=strokeWidth, strokeColor=strokeColor or fillColorShaded)) class _YStrip: def __init__(self,y0,y1, slope, fillColor, fillColorShaded, shading=0.1): self.y0 = y0 self.y1 = y1 self.slope = slope self.fillColor = fillColor self.fillColorShaded = _getShaded(fillColor,fillColorShaded,shading) def _ystrip_poly( x0, x1, y0, y1, xoff, yoff): return [x0,y0,x0+xoff,y0+yoff,x1+xoff,y1+yoff,x1,y1] def _make_3d_line_info( G, x0, x1, y0, y1, z0, z1, theta_x, theta_y, fillColor, fillColorShaded=None, tileWidth=1, strokeColor=None, strokeWidth=None, strokeDashArray=None, shading=0.1): zwidth = abs(z1-z0) xdepth = zwidth*theta_x ydepth = zwidth*theta_y depth_slope = xdepth==0 and 1e150 or -ydepth/float(xdepth) x = float(x1-x0) slope = x==0 and 1e150 or (y1-y0)/x c = slope>depth_slope and _getShaded(fillColor,fillColorShaded,shading) or fillColor zy0 = z0*theta_y zx0 = z0*theta_x tileStrokeWidth = 0.6 if tileWidth is None: D = [(x1,y1)] else: T = ((y1-y0)**2+(x1-x0)**2)**0.5 tileStrokeWidth *= tileWidth if T<tileWidth: D = [(x1,y1)] else: n = int(T/float(tileWidth))+1 dx = float(x1-x0)/n dy = float(y1-y0)/n D = [] a = D.append for i in range(1,n): a((x0+dx*i,y0+dy*i)) a = G.add x_0 = x0+zx0 y_0 = y0+zy0 for x,y in D: x_1 = x+zx0 y_1 = y+zy0 P = Polygon(_ystrip_poly(x_0, x_1, y_0, y_1, xdepth, ydepth), fillColor = c, strokeColor=c, strokeWidth=tileStrokeWidth) a((0,z0,z1,x_0,y_0,P)) x_0 = x_1 y_0 = y_1 from math import pi _pi_2 = pi*0.5 _2pi = 2*pi _180_pi=180./pi def _2rad(angle): return angle/_180_pi def mod_2pi(radians): radians = radians % _2pi if radians<-1e-6: radians += _2pi return radians def _2deg(o): return o*_180_pi def _360(a): a %= 360 if a<-1e-6: a += 360 return a _ZERO = 1e-8 _ONE = 1-_ZERO class _Segment: def __init__(self,s,i,data): S = data[s] x0 = S[i-1][0] y0 = S[i-1][1] x1 = S[i][0] y1 = S[i][1] if x1<x0: x0,y0,x1,y1 = x1,y1,x0,y0 # (y-y0)*(x1-x0) = (y1-y0)*(x-x0) # (x1-x0)*y + (y0-y1)*x = y0*(x1-x0)+x0*(y0-y1) # a*y+b*x = c self.a = float(x1-x0) self.b = float(y1-y0) self.x0 = x0 self.x1 = x1 self.y0 = y0 self.y1 = y1 self.series = s self.i = i self.s = s def __str__(self): return '[(%s,%s),(%s,%s)]' % (self.x0,self.y0,self.x1,self.y1) __repr__ = __str__ def intersect(self,o,I): '''try to find an intersection with _Segment o ''' x0 = self.x0 ox0 = o.x0 assert x0<=ox0 if ox0>self.x1: return 1 if o.s==self.s and o.i in (self.i-1,self.i+1): return a = self.a b = self.b oa = o.a ob = o.b det = ob*a - oa*b if -1e-8<det<1e-8: return dx = x0 - ox0 dy = self.y0 - o.y0 u = (oa*dy - ob*dx)/det ou = (a*dy - b*dx)/det if u<0 or u>1 or ou<0 or ou>1: return x = x0 + u*a y = self.y0 + u*b if _ZERO<u<_ONE: t = self.s,self.i,x,y if t not in I: I.append(t) if _ZERO<ou<_ONE: t = o.s,o.i,x,y if t not in I: I.append(t) def _segKey(a): return (a.x0,a.x1,a.y0,a.y1,a.s,a.i) def find_intersections(data,small=0): ''' data is a sequence of series each series is a list of (x,y) coordinates where x & y are ints or floats find_intersections returns a sequence of 4-tuples i, j, x, y where i is a data index j is an insertion position for data[i] and x, y are coordinates of an intersection of series data[i] with some other series. If correctly implemented we get all such intersections. We don't count endpoint intersections and consider parallel lines as non intersecting (even when coincident). We ignore segments that have an estimated size less than small. ''' #find all line segments S = [] a = S.append for s in range(len(data)): ds = data[s] if not ds: continue n = len(ds) if n==1: continue for i in range(1,n): seg = _Segment(s,i,data) if seg.a+abs(seg.b)>=small: a(seg) S.sort(key=_segKey) I = [] n = len(S) for i in range(0,n-1): s = S[i] for j in range(i+1,n): if s.intersect(S[j],I)==1: break I.sort() return I if __name__=='__main__': from reportlab.graphics.shapes import Drawing from reportlab.lib.colors import lightgrey, pink D = Drawing(300,200) _draw_3d_bar(D, 10, 20, 10, 50, 5, 5, fillColor=lightgrey, strokeColor=pink) _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) D.save(formats=['pdf'],outDir='.',fnRoot='_draw_3d_bar') print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]])) print(find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]])) print(find_intersections([[(0,0),(1,1)],[(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(0,0),(1,1)],[(0.1,0.8),(0.4,0.1),(1,0.1)]]))
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/utils3d.py
0.493164
0.432603
utils3d.py
pypi
__version__='3.3.0' from reportlab.lib import colors from reportlab.lib.utils import simpleSplit from reportlab.lib.validators import isNumber, isNumberOrNone, OneOf, isColorOrNone, isString, \ isTextAnchor, isBoxAnchor, isBoolean, NoneOr, isInstanceOf, isNoneOrString, isNoneOrCallable, \ isSubclassOf from reportlab.lib.attrmap import * from reportlab.pdfbase.pdfmetrics import stringWidth, getAscentDescent from reportlab.graphics.shapes import Drawing, Group, Circle, Rect, String, STATE_DEFAULTS from reportlab.graphics.widgetbase import Widget, PropHolder from reportlab.graphics.shapes import DirectDraw from reportlab.platypus import XPreformatted, Flowable from reportlab.lib.styles import ParagraphStyle, PropertySet from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER _ta2al = dict(start=TA_LEFT,end=TA_RIGHT,middle=TA_CENTER) from ..utils import text2Path as _text2Path #here for continuity _A2BA= { 'x': {0:'n', 45:'ne', 90:'e', 135:'se', 180:'s', 225:'sw', 270:'w', 315: 'nw', -45: 'nw'}, 'y': {0:'e', 45:'se', 90:'s', 135:'sw', 180:'w', 225:'nw', 270:'n', 315: 'ne', -45: 'ne'}, } try: from rlextra.graphics.canvasadapter import DirectDrawFlowable except ImportError: DirectDrawFlowable = None _BA2TA={'w':'start','nw':'start','sw':'start','e':'end', 'ne': 'end', 'se':'end', 'n':'middle','s':'middle','c':'middle'} class Label(Widget): """A text label to attach to something else, such as a chart axis. This allows you to specify an offset, angle and many anchor properties relative to the label's origin. It allows, for example, angled multiline axis labels. """ # fairly straight port of Robin Becker's textbox.py to new widgets # framework. _attrMap = AttrMap( x = AttrMapValue(isNumber,desc=''), y = AttrMapValue(isNumber,desc=''), dx = AttrMapValue(isNumber,desc='delta x - offset'), dy = AttrMapValue(isNumber,desc='delta y - offset'), angle = AttrMapValue(isNumber,desc='angle of label: default (0), 90 is vertical, 180 is upside down, etc'), boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), boxStrokeColor = AttrMapValue(isColorOrNone,desc='border color of the box'), boxStrokeWidth = AttrMapValue(isNumber,desc='border width'), boxFillColor = AttrMapValue(isColorOrNone,desc='the filling color of the box'), boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi'),desc="one of ('normal','anti','lo','hi')"), fillColor = AttrMapValue(isColorOrNone,desc='label text color'), strokeColor = AttrMapValue(isColorOrNone,desc='label text border color'), strokeWidth = AttrMapValue(isNumber,desc='label text border width'), text = AttrMapValue(isString,desc='the actual text to display'), fontName = AttrMapValue(isString,desc='the name of the font used'), fontSize = AttrMapValue(isNumber,desc='the size of the font'), leading = AttrMapValue(isNumberOrNone,desc=''), width = AttrMapValue(isNumberOrNone,desc='the width of the label'), maxWidth = AttrMapValue(isNumberOrNone,desc='maximum width the label can grow to'), height = AttrMapValue(isNumberOrNone,desc='the height of the text'), textAnchor = AttrMapValue(isTextAnchor,desc='the anchoring point of the text inside the label'), visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), topPadding = AttrMapValue(isNumber,desc='padding at top of box'), leftPadding = AttrMapValue(isNumber,desc='padding at left of box'), rightPadding = AttrMapValue(isNumber,desc='padding at right of box'), bottomPadding = AttrMapValue(isNumber,desc='padding at bottom of box'), useAscentDescent = AttrMapValue(isBoolean,desc="If True then the font's Ascent & Descent will be used to compute default heights and baseline."), customDrawChanger = AttrMapValue(isNoneOrCallable,desc="An instance of CustomDrawChanger to modify the behavior at draw time", _advancedUsage=1), ddf = AttrMapValue(NoneOr(isSubclassOf(DirectDraw),'NoneOrDirectDraw'),desc="A DirectDrawFlowable instance", _advancedUsage=1), ddfKlass = AttrMapValue(NoneOr(isSubclassOf(Flowable),'NoneOrDirectDraw'),desc="A Flowable class for direct drawing (default is XPreformatted", _advancedUsage=1), ddfStyle = AttrMapValue(NoneOr((isSubclassOf(PropertySet),isInstanceOf(PropertySet))),desc="A style or style class for a ddfKlass or None", _advancedUsage=1), ) def __init__(self,**kw): self._setKeywords(**kw) self._setKeywords( _text = 'Multi-Line\nString', boxAnchor = 'c', angle = 0, x = 0, y = 0, dx = 0, dy = 0, topPadding = 0, leftPadding = 0, rightPadding = 0, bottomPadding = 0, boxStrokeWidth = 0.5, boxStrokeColor = None, boxTarget = 'normal', strokeColor = None, boxFillColor = None, leading = None, width = None, maxWidth = None, height = None, fillColor = STATE_DEFAULTS['fillColor'], fontName = STATE_DEFAULTS['fontName'], fontSize = STATE_DEFAULTS['fontSize'], strokeWidth = 0.1, textAnchor = 'start', visible = 1, useAscentDescent = False, ddf = DirectDrawFlowable, ddfKlass = None, ddfStyle = None, ) def setText(self, text): """Set the text property. May contain embedded newline characters. Called by the containing chart or axis.""" self._text = text def setOrigin(self, x, y): """Set the origin. This would be the tick mark or bar top relative to which it is defined. Called by the containing chart or axis.""" self.x = x self.y = y def demo(self): """This shows a label positioned with its top right corner at the top centre of the drawing, and rotated 45 degrees.""" d = Drawing(200, 100) # mark the origin of the label d.add(Circle(100,90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(100,90) lab.boxAnchor = 'ne' lab.angle = 45 lab.dx = 0 lab.dy = -20 lab.boxStrokeColor = colors.green lab.setText('Another\nMulti-Line\nString') d.add(lab) return d def _getBoxAnchor(self): '''hook for allowing special box anchor effects''' ba = self.boxAnchor if ba in ('autox', 'autoy'): angle = self.angle na = (int((angle%360)/45.)*45)%360 if not (na % 90): # we have a right angle case da = (angle - na) % 360 if abs(da)>5: na = na + (da>0 and 45 or -45) ba = _A2BA[ba[-1]][na] return ba def _getBaseLineRatio(self): if self.useAscentDescent: self._ascent, self._descent = getAscentDescent(self.fontName,self.fontSize) self._baselineRatio = self._ascent/(self._ascent-self._descent) else: self._baselineRatio = 1/1.2 def _computeSizeEnd(self,objH): self._height = self.height or (objH + self.topPadding + self.bottomPadding) self._ewidth = (self._width-self.leftPadding-self.rightPadding) self._eheight = (self._height-self.topPadding-self.bottomPadding) boxAnchor = self._getBoxAnchor() if boxAnchor in ['n','ne','nw']: self._top = -self.topPadding elif boxAnchor in ['s','sw','se']: self._top = self._height-self.topPadding else: self._top = 0.5*self._eheight self._bottom = self._top - self._eheight if boxAnchor in ['ne','e','se']: self._left = self.leftPadding - self._width elif boxAnchor in ['nw','w','sw']: self._left = self.leftPadding else: self._left = -self._ewidth*0.5 self._right = self._left+self._ewidth def computeSize(self): # the thing will draw in its own coordinate system ddfKlass = getattr(self,'ddfKlass',None) if not ddfKlass: self._lineWidths = [] self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) if not self.width: self._width = self.leftPadding+self.rightPadding if self._lines: self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width self._getBaseLineRatio() if self.leading: self._leading = self.leading elif self.useAscentDescent: self._leading = self._ascent - self._descent else: self._leading = self.fontSize*1.2 objH = self._leading*len(self._lines) else: if self.ddf is None: raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') sty = dict( name='xlabel-generated', fontName=self.fontName, fontSize=self.fontSize, fillColor=self.fillColor, strokeColor=self.strokeColor, ) if not self.ddfStyle: sty = ParagraphStyle(**sty) elif issubclass(self.ddfStyle,PropertySet): sty = self.ddfStyle(**sty) else: sty = self.ddfStyle.clone() self._style = sty self._getBaseLineRatio() if self.useAscentDescent: sty.autoLeading = True sty.leading = self._ascent - self._descent else: sty.leading = self.leading if self.leading else self.fontSize*1.2 self._leading = sty.leading ta = self._getTextAnchor() aW = self.maxWidth or 0x7fffffff if ta!='start': sty.alignment = TA_LEFT obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) aW = self.maxWidth or obj._width_max sty.alignment = _ta2al[ta] self._ddfObj = obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) if not self.width: self._width = self.leftPadding+self.rightPadding self._width += obj._width_max else: self._width = self.width self._computeSizeEnd(objH) def _getTextAnchor(self): '''This can be overridden to allow special effects''' ta = self.textAnchor if ta=='boxauto': ta = _BA2TA[self._getBoxAnchor()] return ta def _rawDraw(self): _text = self._text self._text = _text or '' self.computeSize() self._text = _text g = Group() g.translate(self.x + self.dx, self.y + self.dy) g.rotate(self.angle) ddfKlass = getattr(self,'ddfKlass',None) if ddfKlass: x = self._left else: y = self._top - self._leading*self._baselineRatio textAnchor = self._getTextAnchor() if textAnchor == 'start': x = self._left elif textAnchor == 'middle': x = self._left + self._ewidth*0.5 else: x = self._right # paint box behind text just in case they # fill it if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): g.add(Rect( self._left-self.leftPadding, self._bottom-self.bottomPadding, self._width, self._height, strokeColor=self.boxStrokeColor, strokeWidth=self.boxStrokeWidth, fillColor=self.boxFillColor) ) if ddfKlass: g1 = Group() g1.translate(x,self._top-self._eheight) g1.add(self.ddf(self._ddfObj)) g.add(g1) else: fillColor, fontName, fontSize = self.fillColor, self.fontName, self.fontSize strokeColor, strokeWidth, leading = self.strokeColor, self.strokeWidth, self._leading svgAttrs=getattr(self,'_svgAttrs',{}) if strokeColor: for line in self._lines: s = _text2Path(line, x, y, fontName, fontSize, textAnchor) s.fillColor = fillColor s.strokeColor = strokeColor s.strokeWidth = strokeWidth g.add(s) y -= leading else: for line in self._lines: s = String(x, y, line, _svgAttrs=svgAttrs) s.textAnchor = textAnchor s.fontName = fontName s.fontSize = fontSize s.fillColor = fillColor g.add(s) y -= leading return g def draw(self): customDrawChanger = getattr(self,'customDrawChanger',None) if customDrawChanger: customDrawChanger(True,self) try: return self._rawDraw() finally: customDrawChanger(False,self) else: return self._rawDraw() class LabelDecorator: _attrMap = AttrMap( x = AttrMapValue(isNumberOrNone,desc=''), y = AttrMapValue(isNumberOrNone,desc=''), dx = AttrMapValue(isNumberOrNone,desc=''), dy = AttrMapValue(isNumberOrNone,desc=''), angle = AttrMapValue(isNumberOrNone,desc=''), boxAnchor = AttrMapValue(isBoxAnchor,desc=''), boxStrokeColor = AttrMapValue(isColorOrNone,desc=''), boxStrokeWidth = AttrMapValue(isNumberOrNone,desc=''), boxFillColor = AttrMapValue(isColorOrNone,desc=''), fillColor = AttrMapValue(isColorOrNone,desc=''), strokeColor = AttrMapValue(isColorOrNone,desc=''), strokeWidth = AttrMapValue(isNumberOrNone),desc='', fontName = AttrMapValue(isNoneOrString,desc=''), fontSize = AttrMapValue(isNumberOrNone,desc=''), leading = AttrMapValue(isNumberOrNone,desc=''), width = AttrMapValue(isNumberOrNone,desc=''), maxWidth = AttrMapValue(isNumberOrNone,desc=''), height = AttrMapValue(isNumberOrNone,desc=''), textAnchor = AttrMapValue(isTextAnchor,desc=''), visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), ) def __init__(self): self.textAnchor = 'start' self.boxAnchor = 'w' for a in self._attrMap.keys(): if not hasattr(self,a): setattr(self,a,None) def decorate(self,l,L): chart,g,rowNo,colNo,x,y,width,height,x00,y00,x0,y0 = l._callOutInfo L.setText(chart.categoryAxis.categoryNames[colNo]) g.add(L) def __call__(self,l): L = Label() for a,v in self.__dict__.items(): if v is None: v = getattr(l,a,None) setattr(L,a,v) self.decorate(l,L) isOffsetMode=OneOf('high','low','bar','axis') class LabelOffset(PropHolder): _attrMap = AttrMap( posMode = AttrMapValue(isOffsetMode,desc="Where to base +ve offset"), pos = AttrMapValue(isNumber,desc='Value for positive elements'), negMode = AttrMapValue(isOffsetMode,desc="Where to base -ve offset"), neg = AttrMapValue(isNumber,desc='Value for negative elements'), ) def __init__(self): self.posMode=self.negMode='axis' self.pos = self.neg = 0 def _getValue(self, chart, val): flipXY = chart._flipXY A = chart.categoryAxis jA = A.joinAxis if val>=0: mode = self.posMode delta = self.pos else: mode = self.negMode delta = self.neg if flipXY: v = A._x else: v = A._y if jA: if flipXY: _v = jA._x else: _v = jA._y if mode=='high': v = _v + jA._length elif mode=='low': v = _v elif mode=='bar': v = _v+val return v+delta NoneOrInstanceOfLabelOffset=NoneOr(isInstanceOf(LabelOffset)) class PMVLabel(Label): _attrMap = AttrMap( BASE=Label, ) def __init__(self, **kwds): Label.__init__(self, **kwds) self._pmv = 0 def _getBoxAnchor(self): a = Label._getBoxAnchor(self) if self._pmv<0: a = {'nw':'se','n':'s','ne':'sw','w':'e','c':'c','e':'w','sw':'ne','s':'n','se':'nw'}[a] return a def _getTextAnchor(self): a = Label._getTextAnchor(self) if self._pmv<0: a = {'start':'end', 'middle':'middle', 'end':'start'}[a] return a class BarChartLabel(PMVLabel): """ An extended Label allowing for nudging, lines visibility etc """ _attrMap = AttrMap( BASE=PMVLabel, lineStrokeWidth = AttrMapValue(isNumberOrNone, desc="Non-zero for a drawn line"), lineStrokeColor = AttrMapValue(isColorOrNone, desc="Color for a drawn line"), fixedEnd = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw ends +/-"), fixedStart = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw starts +/-"), nudge = AttrMapValue(isNumber, desc="Non-zero sign dependent nudge"), boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi','mid'),desc="one of ('normal','anti','lo','hi','mid')"), ) def __init__(self, **kwds): PMVLabel.__init__(self, **kwds) self.lineStrokeWidth = 0 self.lineStrokeColor = None self.fixedStart = self.fixedEnd = None self.nudge = 0 class NA_Label(BarChartLabel): """ An extended Label allowing for nudging, lines visibility etc """ _attrMap = AttrMap( BASE=BarChartLabel, text = AttrMapValue(isNoneOrString, desc="Text to be used for N/A values"), ) def __init__(self): BarChartLabel.__init__(self) self.text = 'n/a' NoneOrInstanceOfNA_Label=NoneOr(isInstanceOf(NA_Label)) from reportlab.graphics.charts.utils import CustomDrawChanger class RedNegativeChanger(CustomDrawChanger): def __init__(self,fillColor=colors.red): CustomDrawChanger.__init__(self) self.fillColor = fillColor def _changer(self,obj): R = {} if obj._text.startswith('-'): R['fillColor'] = obj.fillColor obj.fillColor = self.fillColor return R class XLabel(Label): '''like label but uses XPreFormatted/Paragraph to draw the _text''' _attrMap = AttrMap(BASE=Label, ) def __init__(self,*args,**kwds): Label.__init__(self,*args,**kwds) self.ddfKlass = kwds.pop('ddfKlass',XPreformatted) self.ddf = kwds.pop('directDrawClass',self.ddf) if False: def __init__(self,*args,**kwds): self._flowableClass = kwds.pop('flowableClass',XPreformatted) ddf = kwds.pop('directDrawClass',DirectDrawFlowable) if ddf is None: raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') self._ddf = ddf Label.__init__(self,*args,**kwds) def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] sty = self._style = ParagraphStyle('xlabel-generated', fontName=self.fontName, fontSize=self.fontSize, fillColor=self.fillColor, strokeColor=self.strokeColor, ) self._getBaseLineRatio() if self.useAscentDescent: sty.autoLeading = True sty.leading = self._ascent - self._descent else: sty.leading = self.leading if self.leading else self.fontSize*1.2 self._leading = sty.leading ta = self._getTextAnchor() aW = self.maxWidth or 0x7fffffff if ta!='start': sty.alignment = TA_LEFT obj = self._flowableClass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) aW = self.maxWidth or obj._width_max sty.alignment = _ta2al[ta] self._obj = obj = self._flowableClass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) if not self.width: self._width = self.leftPadding+self.rightPadding self._width += self._obj._width_max else: self._width = self.width self._computeSizeEnd(objH) def _rawDraw(self): _text = self._text self._text = _text or '' self.computeSize() self._text = _text g = Group() g.translate(self.x + self.dx, self.y + self.dy) g.rotate(self.angle) x = self._left # paint box behind text just in case they # fill it if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): g.add(Rect( self._left-self.leftPadding, self._bottom-self.bottomPadding, self._width, self._height, strokeColor=self.boxStrokeColor, strokeWidth=self.boxStrokeWidth, fillColor=self.boxFillColor) ) g1 = Group() g1.translate(x,self._top-self._eheight) g1.add(self._ddf(self._obj)) g.add(g1) return g
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/charts/textlabels.py
0.567337
0.242026
textlabels.py
pypi
from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.lineplots import ScatterPlot from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class Bubble(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.lines.symbol.kind ='Circle' self.chart.lines.symbol.size = 15 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (350,450))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS Bubble().save(formats=['pdf'],outDir=None,fnRoot='bubble')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/samples/bubble.py
0.679285
0.153613
bubble.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.samples.excelcolors import * from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label class ExplodedPie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self.chart.startAngle = -90 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.Legend.columnMaximum = 10 self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 20 self.background.y = 20 self.chart.slices.popout = 5 self.background.height = 110 self.background.width = 110 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS ExplodedPie().save(formats=['pdf'],outDir=None,fnRoot='exploded_pie')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/samples/exploded_pie.py
0.634883
0.16896
exploded_pie.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class SimplePie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'),(color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 25 self.background.y = 25 self.Legend.columnMaximum = 10 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS SimplePie().save(formats=['pdf'],outDir=None,fnRoot=None)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/samples/simple_pie.py
0.627267
0.176069
simple_pie.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of widgets to produce some common signs and symbols. Widgets include: - ETriangle (an equilateral triangle), - RTriangle (a right angled triangle), - Octagon, - Crossbox, - Tickbox, - SmileyFace, - StopSign, - NoEntry, - NotAllowed (the red roundel from 'no smoking' signs), - NoSmoking, - DangerSign (a black exclamation point in a yellow triangle), - YesNo (returns a tickbox or a crossbox depending on a testvalue), - FloppyDisk, - ArrowOne, and - ArrowTwo - CrossHair """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.lib.utils import isStr, asUnicode from reportlab.graphics import shapes from reportlab.graphics.widgetbase import Widget from reportlab.graphics import renderPDF class _Symbol(Widget): """Abstract base widget possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _nodoc = 1 _attrMap = AttrMap( x = AttrMapValue(isNumber,desc='symbol x coordinate'), y = AttrMapValue(isNumber,desc='symbol y coordinate'), dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), size = AttrMapValue(isNumber), fillColor = AttrMapValue(isColorOrNone), strokeColor = AttrMapValue(isColorOrNone), strokeWidth = AttrMapValue(isNumber), ) def __init__(self): assert self.__class__.__name__!='_Symbol', 'Abstract class _Symbol instantiated' self.x = self.y = self.dx = self.dy = 0 self.size = 100 self.fillColor = colors.red self.strokeColor = None self.strokeWidth = 0.1 def demo(self): D = shapes.Drawing(200, 100) s = float(self.size) ob = self.__class__() ob.x=50 ob.y=0 ob.draw() D.add(ob) D.add(shapes.String(ob.x+(s/2),(ob.y-12), ob.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=10)) return D class ETriangle(_Symbol): """This draws an equilateral triangle.""" def __init__(self): _Symbol.__init__(self) def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class RTriangle(_Symbol): """This draws a right-angled triangle. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.green self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x,self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class Octagon(_Symbol): """This widget draws an Octagon. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Octagon specific bits athird=s/3 octagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = self.fillColor, strokeWidth=10) g.add(octagon) return g class Crossbox(_Symbol): """This draws a black box with a red cross in it - a 'checkbox'. possible attributes: 'x', 'y', 'size', 'crossColor', 'strokeColor', 'crosswidth' """ _attrMap = AttrMap(BASE=_Symbol, crossColor = AttrMapValue(isColorOrNone), crosswidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.white self.crossColor = colors.red self.strokeColor = colors.black self.crosswidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # crossbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) crossLine1 = shapes.Line(self.x+(s*0.15), self.y+(s*0.15), self.x+(s*0.85), self.y+(s*0.85), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine1) crossLine2 = shapes.Line(self.x+(s*0.15), self.y+(s*0.85), self.x+(s*0.85) ,self.y+(s*0.15), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine2) return g class Tickbox(_Symbol): """This draws a black box with a red tick in it - another 'checkbox'. possible attributes: 'x', 'y', 'size', 'tickColor', 'strokeColor', 'tickwidth' """ _attrMap = AttrMap(BASE=_Symbol, tickColor = AttrMapValue(isColorOrNone), tickwidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickColor = colors.red self.strokeColor = colors.black self.fillColor = colors.white self.tickwidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # tickbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) tickLine = shapes.PolyLine(points = [self.x+(s*0.15), self.y+(s*0.35), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.85) ,self.y+(s*0.85)], fillColor = self.tickColor, strokeColor = self.tickColor, strokeWidth = self.tickwidth) g.add(tickLine) return g class SmileyFace(_Symbol): """This draws a classic smiley face. possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): _Symbol.__init__(self) self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # SmileyFace specific bits g.add(shapes.Circle(cx=self.x+(s/2), cy=self.y+(s/2), r=s/2, fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) for i in (1,2): g.add(shapes.Ellipse(self.x+(s/3)*i,self.y+(s/3)*2, s/30, s/10, fillColor=self.strokeColor, strokeColor = self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) # calculate a pointslist for the mouth # THIS IS A HACK! - don't use if there is a 'shapes.Arc' centerx=self.x+(s/2) centery=self.y+(s/2) radius=s/3 yradius = radius xradius = radius startangledegrees=200 endangledegrees=340 degreedelta = 1 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta # make the mouth smile = shapes.PolyLine(pointslist, fillColor = self.strokeColor, strokeColor = self.strokeColor, strokeWidth = max(s/38.,self.strokeWidth)) g.add(smile) return g class StopSign(_Symbol): """This draws a (British) stop sign. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, stopColor = AttrMapValue(isColorOrNone,desc='color of the word stop'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.stopColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # stop-sign specific bits athird=s/3 outerOctagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = None, strokeWidth=1) g.add(outerOctagon) innerOctagon = shapes.Polygon(points=[self.x+athird+(s/75), self.y+(s/75), self.x+(s/75), self.y+athird+(s/75), self.x+(s/75), self.y+(athird*2)-(s/75), self.x+athird+(s/75), self.y+s-(s/75), self.x+(athird*2)-(s/75), (self.y+s)-(s/75), (self.x+s)-(s/75), self.y+(athird*2)-(s/75), (self.x+s)-(s/75), self.y+athird+(s/75), self.x+(athird*2)-(s/75), self.y+(s/75)], strokeColor = None, fillColor = self.fillColor, strokeWidth=0) g.add(innerOctagon) if self.stopColor: g.add(shapes.String(self.x+(s*0.5),self.y+(s*0.4), 'STOP', fillColor=self.stopColor, textAnchor='middle', fontSize=s/3, fontName="Helvetica-Bold")) return g class NoEntry(_Symbol): """This draws a (British) No Entry sign - a red circle with a white line on it. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, innerBarColor = AttrMapValue(isColorOrNone,desc='color of the inner bar'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.innerBarColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # no-entry-sign specific bits if self.strokeColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = s/2, fillColor = None, strokeColor = self.strokeColor, strokeWidth=1)) if self.fillColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy =(self.y+(s/2)), r = ((s/2)-(s/50)), fillColor = self.fillColor, strokeColor = None, strokeWidth=0)) innerBarColor = self.innerBarColor if innerBarColor: g.add(shapes.Rect(self.x+(s*0.1), self.y+(s*0.4), width=s*0.8, height=s*0.2, fillColor = innerBarColor, strokeColor = innerBarColor, strokeLineCap = 1, strokeWidth = 0)) return g class NotAllowed(_Symbol): """This draws a 'forbidden' roundel (as used in the no-smoking sign). possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.red self.fillColor = colors.white def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() strokeColor = self.strokeColor # not=allowed specific bits outerCircle = shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = (s/2)-(s/10), fillColor = self.fillColor, strokeColor = strokeColor, strokeWidth=s/10.) g.add(outerCircle) centerx=self.x+s centery=self.y+(s/2)-(s/6) radius=s-(s/6) yradius = radius/2 xradius = radius/2 startangledegrees=100 endangledegrees=-80 degreedelta = 90 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta crossbar = shapes.PolyLine(pointslist, fillColor = strokeColor, strokeColor = strokeColor, strokeWidth = s/10.) g.add(crossbar) return g class NoSmoking(NotAllowed): """This draws a no-smoking sign. possible attributes: 'x', 'y', 'size' """ def __init__(self): NotAllowed.__init__(self) def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = NotAllowed.draw(self) # no-smoking-sign specific bits newx = self.x+(s/2)-(s/3.5) newy = self.y+(s/2)-(s/32) cigarrette1 = shapes.Rect(x = newx, y = newy, width = (s/2), height =(s/16), fillColor = colors.ghostwhite, strokeColor = colors.gray, strokeWidth=0) newx=newx+(s/2)+(s/64) g.insert(-1,cigarrette1) cigarrette2 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette2) cigarrette3 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette3) cigarrette4 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette4) return g class DangerSign(_Symbol): """This draws a 'danger' sign: a yellow box with a black exclamation point. possible attributes: 'x', 'y', 'size', 'strokeColor', 'fillColor', 'strokeWidth' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.gold self.strokeWidth = self.size*0.125 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') # danger sign specific bits ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') outerTriangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = None, strokeColor = self.strokeColor, strokeWidth=0) g.add(outerTriangle) innerTriangle = shapes.Polygon(points = [ self.x+(s/50), self.y+(s/75), (self.x+s)-(s/50), self.y+(s/75), self.x+(s/2),(self.y+s)-(s/50)], fillColor = self.fillColor, strokeColor = None, strokeWidth=0) g.add(innerTriangle) exmark = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae*2.5, ((self.x+s/2)+ew/2), self.y+ae*2.5, ((self.x+s/2)+((ew/2))+(ew/6)), self.y+ae*5.5, ((self.x+s/2)-((ew/2))-(ew/6)), self.y+ae*5.5], fillColor = self.strokeColor, strokeColor = None) g.add(exmark) exdot = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae*2, ((self.x+s/2)-ew/2), self.y+ae*2], fillColor = self.strokeColor, strokeColor = None) g.add(exdot) return g class YesNo(_Symbol): """This widget draw a tickbox or crossbox depending on 'testValue'. If this widget is supplied with a 'True' or 1 as a value for testValue, it will use the tickbox widget. Otherwise, it will produce a crossbox. possible attributes: 'x', 'y', 'size', 'tickcolor', 'crosscolor', 'testValue' """ _attrMap = AttrMap(BASE=_Symbol, tickcolor = AttrMapValue(isColor), crosscolor = AttrMapValue(isColor), testValue = AttrMapValue(isBoolean), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickcolor = colors.green self.crosscolor = colors.red self.testValue = 1 def draw(self): if self.testValue: yn=Tickbox() yn.tickColor=self.tickcolor else: yn=Crossbox() yn.crossColor=self.crosscolor yn.x=self.x yn.y=self.y yn.size=self.size yn.draw() return yn def demo(self): D = shapes.Drawing(200, 100) yn = YesNo() yn.x = 15 yn.y = 25 yn.size = 70 yn.testValue = 0 yn.draw() D.add(yn) yn2 = YesNo() yn2.x = 120 yn2.y = 25 yn2.size = 70 yn2.testValue = 1 yn2.draw() D.add(yn2) labelFontSize = 8 D.add(shapes.String(yn.x+(yn.size/2),(yn.y-(1.2*labelFontSize)), 'testValue=0', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(yn2.x+(yn2.size/2),(yn2.y-(1.2*labelFontSize)), 'testValue=1', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = 10 D.add(shapes.String(yn.x+85,(yn.y-20), self.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D class FloppyDisk(_Symbol): """This widget draws an icon of a floppy disk. possible attributes: 'x', 'y', 'size', 'diskcolor' """ _attrMap = AttrMap(BASE=_Symbol, diskColor = AttrMapValue(isColor), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.diskColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # floppy disk specific bits diskBody = shapes.Rect(x=self.x, y=self.y+(s/100), width=s, height=s-(s/100), fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(diskBody) label = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.5), width=s*0.8, height=s*0.48, fillColor = colors.whitesmoke, strokeColor = None, strokeWidth=0) g.add(label) labelsplash = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.1), width=s*0.8, height=s*0.08, fillColor = colors.royalblue, strokeColor = None, strokeWidth=0) g.add(labelsplash) line1 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.6*s), x2=self.x+(s*0.85), y2=self.y+(0.6*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line1) line2 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.7*s), x2=self.x+(s*0.85), y2=self.y+(0.7*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line2) line3 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.8*s), x2=self.x+(s*0.85), y2=self.y+(0.8*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line3) metalcover = shapes.Rect(x=self.x+(s*0.2), y=(self.y), width=s*0.5, height=s*0.35, fillColor = colors.silver, strokeColor = None, strokeWidth=0) g.add(metalcover) coverslot = shapes.Rect(x=self.x+(s*0.28), y=(self.y)+(s*0.035), width=s*0.12, height=s*0.28, fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(coverslot) return g class ArrowOne(_Symbol): """This widget draws an arrow (style one). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.red self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 g.add(shapes.Polygon(points = [ x,y+s3, x,y+2*s3, x+s2,y+2*s3, x+s2,y+4*s5, x+s,y+s2, x+s2,y+s5, x+s2,y+s3, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth, ) ) return g class ArrowTwo(ArrowOne): """This widget draws an arrow (style two). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.blue self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # arrow specific bits x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 s24 = s/24 g.add(shapes.Polygon( points = [ x,y+11*s24, x,y+13*s24, x+18.75*s24, y+13*s24, x+2*s3, y+2*s3, x+s, y+s2, x+2*s3, y+s3, x+18.75*s24, y+11*s24, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth) ) return g class CrossHair(_Symbol): """This draws an equilateral triangle.""" _attrMap = AttrMap(BASE=_Symbol, innerGap = AttrMapValue(EitherOr((isString,isNumberOrNone)),desc=' gap at centre as "x%" or points or None'), ) def __init__(self): self.x = self.y = self.dx = self.dy = 0 self.size = 10 self.fillColor = None self.strokeColor = colors.black self.strokeWidth = 0.5 self.innerGap = '20%' def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() ig = self.innerGap x = self.x+self.dx y = self.y+self.dy hsize = 0.5*self.size if not ig: L = [(x-hsize,y,x+hsize,y), (x,y-hsize,x,y+hsize)] else: if isStr(ig): ig = asUnicode(ig) if ig.endswith(u'%'): gs = hsize*float(ig[:-1])/100.0 else: gs = float(ig)*0.5 else: gs = ig*0.5 L = [(x-hsize,y,x-gs,y), (x+gs,y,x+hsize,y), (x,y-hsize,x,y-gs), (x,y+gs,x,y+hsize)] P = shapes.Path(strokeWidth=self.strokeWidth,strokeColor=self.strokeColor) for x0,y0,x1,y1 in L: P.moveTo(x0,y0) P.lineTo(x1,y1) g.add(P) return g def test(): """This function produces a pdf with examples of all the signs and symbols from this file. """ labelFontSize = 10 D = shapes.Drawing(450,650) cb = Crossbox() cb.x = 20 cb.y = 530 D.add(cb) D.add(shapes.String(cb.x+(cb.size/2),(cb.y-(1.2*labelFontSize)), cb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) tb = Tickbox() tb.x = 170 tb.y = 530 D.add(tb) D.add(shapes.String(tb.x+(tb.size/2),(tb.y-(1.2*labelFontSize)), tb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) yn = YesNo() yn.x = 320 yn.y = 530 D.add(yn) tempstring = yn.__class__.__name__ + '*' D.add(shapes.String(yn.x+(tb.size/2),(yn.y-(1.2*labelFontSize)), tempstring, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(130,6, "(The 'YesNo' widget returns a tickbox if testvalue=1, and a crossbox if testvalue=0)", fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize*0.75)) ss = StopSign() ss.x = 20 ss.y = 400 D.add(ss) D.add(shapes.String(ss.x+(ss.size/2), ss.y-(1.2*labelFontSize), ss.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ne = NoEntry() ne.x = 170 ne.y = 400 D.add(ne) D.add(shapes.String(ne.x+(ne.size/2),(ne.y-(1.2*labelFontSize)), ne.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) sf = SmileyFace() sf.x = 320 sf.y = 400 D.add(sf) D.add(shapes.String(sf.x+(sf.size/2),(sf.y-(1.2*labelFontSize)), sf.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ds = DangerSign() ds.x = 20 ds.y = 270 D.add(ds) D.add(shapes.String(ds.x+(ds.size/2),(ds.y-(1.2*labelFontSize)), ds.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) na = NotAllowed() na.x = 170 na.y = 270 D.add(na) D.add(shapes.String(na.x+(na.size/2),(na.y-(1.2*labelFontSize)), na.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ns = NoSmoking() ns.x = 320 ns.y = 270 D.add(ns) D.add(shapes.String(ns.x+(ns.size/2),(ns.y-(1.2*labelFontSize)), ns.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a1 = ArrowOne() a1.x = 20 a1.y = 140 D.add(a1) D.add(shapes.String(a1.x+(a1.size/2),(a1.y-(1.2*labelFontSize)), a1.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a2 = ArrowTwo() a2.x = 170 a2.y = 140 D.add(a2) D.add(shapes.String(a2.x+(a2.size/2),(a2.y-(1.2*labelFontSize)), a2.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) fd = FloppyDisk() fd.x = 320 fd.y = 140 D.add(fd) D.add(shapes.String(fd.x+(fd.size/2),(fd.y-(1.2*labelFontSize)), fd.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) renderPDF.drawToFile(D, 'signsandsymbols.pdf', 'signsandsymbols.py') print('wrote file: signsandsymbols.pdf') if __name__=='__main__': test()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/signsandsymbols.py
0.908339
0.42483
signsandsymbols.py
pypi
__version__='3.3.0' from reportlab.lib import colors from reportlab.lib.validators import isNumber, isColorOrNone, isBoolean, isListOfNumbers, OneOf, isListOfColors, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.shapes import Drawing, Group, Line, Rect, LineShape, definePath, EmptyClipPath from reportlab.graphics.widgetbase import Widget def frange(start, end=None, inc=None): "A range function, that does accept float increments..." if end == None: end = start + 0.0 start = 0.0 if inc == None: inc = 1.0 L = [] end = end - inc*0.0001 #to avoid numrical problems while 1: next = start + len(L) * inc if inc > 0 and next >= end: break elif inc < 0 and next <= end: break L.append(next) return L def makeDistancesList(list): """Returns a list of distances between adjacent numbers in some input list. E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2] """ d = [] for i in range(len(list[:-1])): d.append(list[i+1] - list[i]) return d class Grid(Widget): """This makes a rectangular grid of equidistant stripes. The grid contains an outer border rectangle, and stripes inside which can be drawn with lines and/or as solid tiles. The drawing order is: outer rectangle, then lines and tiles. The stripes' width is indicated as 'delta'. The sequence of stripes can have an offset named 'delta0'. Both values need to be positive! """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), useLines = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with lines.'), useRects = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with solid rectangles.'), delta = AttrMapValue(isNumber, desc='Determines the width/height of the stripes.'), delta0 = AttrMapValue(isNumber, desc='Determines the stripes initial width/height offset.'), deltaSteps = AttrMapValue(isListOfNumbers, desc='List of deltas to be used cyclically.'), stripeColors = AttrMapValue(isListOfColors, desc='Colors applied cyclically in the right or upper direction.'), fillColor = AttrMapValue(isColorOrNone, desc='Background color for entire rectangle.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for lines.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), rectStrokeColor = AttrMapValue(isColorOrNone, desc='Color for outer rect stroke.'), rectStrokeWidth = AttrMapValue(isNumberOrNone, desc='Width for outer rect stroke.'), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.useLines = 0 self.useRects = 1 self.delta = 20 self.delta0 = 0 self.deltaSteps = [] self.fillColor = colors.white self.stripeColors = [colors.red, colors.green, colors.blue] self.strokeColor = colors.black self.strokeWidth = 2 def demo(self): D = Drawing(100, 100) g = Grid() D.add(g) return D def makeOuterRect(self): strokeColor = getattr(self,'rectStrokeColor',self.strokeColor) strokeWidth = getattr(self,'rectStrokeWidth',self.strokeWidth) if self.fillColor or (strokeColor and strokeWidth): rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = strokeColor rect.strokeWidth = strokeWidth return rect else: return None def makeLinePosList(self, start, isX=0): "Returns a list of positions where to place lines." w, h = self.width, self.height if isX: length = w else: length = h if self.deltaSteps: r = [start + self.delta0] i = 0 while 1: if r[-1] > start + length: del r[-1] break r.append(r[-1] + self.deltaSteps[i % len(self.deltaSteps)]) i = i + 1 else: r = frange(start + self.delta0, start + length, self.delta) r.append(start + length) if self.delta0 != 0: r.insert(0, start) #print 'Grid.makeLinePosList() -> %s' % r return r def makeInnerLines(self): # inner grid lines group = Group() w, h = self.width, self.height if self.useLines == 1: if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) for x in r: line = Line(x, self.y, x, self.y + h) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) for y in r: line = Line(self.x, y, self.x + w, y) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) return group def makeInnerTiles(self): # inner grid lines group = Group() w, h = self.width, self.height # inner grid stripes (solid rectangles) if self.useRects == 1: cols = self.stripeColors if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) dist = makeDistancesList(r) i = 0 for j in range(len(dist)): if self.orientation == 'vertical': x = r[j] stripe = Rect(x, self.y, dist[j], h) elif self.orientation == 'horizontal': y = r[j] stripe = Rect(self.x, y, w, dist[j]) stripe.fillColor = cols[i % len(cols)] stripe.strokeColor = None group.add(stripe) i = i + 1 return group def draw(self): # general widget bits group = Group() group.add(self.makeOuterRect()) group.add(self.makeInnerTiles()) group.add(self.makeInnerLines(),name='_gridLines') return group class DoubleGrid(Widget): """This combines two ordinary Grid objects orthogonal to each other. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), grid0 = AttrMapValue(None, desc="The first grid component."), grid1 = AttrMapValue(None, desc="The second grid component."), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 g0 = Grid() g0.x = self.x g0.y = self.y g0.width = self.width g0.height = self.height g0.orientation = 'vertical' g0.useLines = 1 g0.useRects = 0 g0.delta = 20 g0.delta0 = 0 g0.deltaSteps = [] g0.fillColor = colors.white g0.stripeColors = [colors.red, colors.green, colors.blue] g0.strokeColor = colors.black g0.strokeWidth = 1 g1 = Grid() g1.x = self.x g1.y = self.y g1.width = self.width g1.height = self.height g1.orientation = 'horizontal' g1.useLines = 1 g1.useRects = 0 g1.delta = 20 g1.delta0 = 0 g1.deltaSteps = [] g1.fillColor = colors.white g1.stripeColors = [colors.red, colors.green, colors.blue] g1.strokeColor = colors.black g1.strokeWidth = 1 self.grid0 = g0 self.grid1 = g1 ## # This gives an AttributeError: ## # DoubleGrid instance has no attribute 'grid0' ## def __setattr__(self, name, value): ## if name in ('x', 'y', 'width', 'height'): ## setattr(self.grid0, name, value) ## setattr(self.grid1, name, value) def demo(self): D = Drawing(100, 100) g = DoubleGrid() D.add(g) return D def draw(self): group = Group() g0, g1 = self.grid0, self.grid1 # Order groups to make sure both v and h lines # are visible (works only when there is only # one kind of stripes, v or h). G = g0.useRects == 1 and g1.useRects == 0 and (g0,g1) or (g1,g0) for g in G: group.add(g.makeOuterRect()) for g in G: group.add(g.makeInnerTiles()) group.add(g.makeInnerLines(),name='_gridLines') return group class ShadedRect(Widget): """This makes a rectangle with shaded colors between two colors. Colors are interpolated linearly between 'fillColorStart' and 'fillColorEnd', both of which appear at the margins. If 'numShades' is set to one, though, only 'fillColorStart' is used. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), fillColorStart = AttrMapValue(isColorOrNone, desc='Start value of the color shade.'), fillColorEnd = AttrMapValue(isColorOrNone, desc='End value of the color shade.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for border line.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), ) def __init__(self,**kw): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.numShades = 20 self.fillColorStart = colors.pink self.fillColorEnd = colors.black self.strokeColor = colors.black self.strokeWidth = 2 self.cylinderMode = 0 self.setProperties(kw) def demo(self): D = Drawing(100, 100) g = ShadedRect() D.add(g) return D def _flipRectCorners(self): "Flip rectangle's corners if width or height is negative." x, y, width, height, fillColorStart, fillColorEnd = self.x, self.y, self.width, self.height, self.fillColorStart, self.fillColorEnd if width < 0 and height > 0: x = x + width width = -width if self.orientation=='vertical': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height<0 and width>0: y = y + height height = -height if self.orientation=='horizontal': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height < 0 and height < 0: x = x + width width = -width y = y + height height = -height return x, y, width, height, fillColorStart, fillColorEnd def draw(self): # general widget bits group = Group() x, y, w, h, c0, c1 = self._flipRectCorners() numShades = self.numShades if self.cylinderMode: if not numShades%2: numShades = numShades+1 halfNumShades = int((numShades-1)/2) + 1 num = float(numShades) # must make it float! vertical = self.orientation == 'vertical' if vertical: if numShades == 1: V = [x] else: V = frange(x, x + w, w/num) else: if numShades == 1: V = [y] else: V = frange(y, y + h, h/num) for v in V: stripe = vertical and Rect(v, y, w/num, h) or Rect(x, v, w, h/num) if self.cylinderMode: if V.index(v)>=halfNumShades: col = colors.linearlyInterpolatedColor(c1,c0,V[halfNumShades],V[-1], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[halfNumShades], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[-1], v) stripe.fillColor = col stripe.strokeColor = col stripe.strokeWidth = 1 group.add(stripe) if self.strokeColor and self.strokeWidth>=0: rect = Rect(x, y, w, h) rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth rect.fillColor = None group.add(rect) return group def colorRange(c0, c1, n): "Return a range of intermediate colors between c0 and c1" if n==1: return [c0] C = [] if n>1: lim = n-1 for i in range(n): C.append(colors.linearlyInterpolatedColor(c0,c1,0,lim, i)) return C def centroid(P): '''compute average point of a set of points''' cx = 0 cy = 0 for x,y in P: cx+=x cy+=y n = float(len(P)) return cx/n, cy/n def rotatedEnclosingRect(P, angle, rect): ''' given P a sequence P of x,y coordinate pairs and an angle in degrees find the centroid of P and the axis at angle theta through it find the extreme points of P wrt axis parallel distance and axis orthogonal distance. Then compute the least rectangle that will still enclose P when rotated by angle. The class R ''' from math import pi, cos, sin x0, y0 = centroid(P) theta = (angle/180.)*pi s,c=sin(theta),cos(theta) def parallelAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (s*(y-y0)+c*(x-x0)) def orthogonalAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (c*(y-y0)+s*(x-x0)) L = list(map(parallelAxisDist,P)) L.sort() a0, a1 = L[0], L[-1] L = list(map(orthogonalAxisDist,P)) L.sort() b0, b1 = L[0], L[-1] rect.x, rect.width = a0, a1-a0 rect.y, rect.height = b0, b1-b0 g = Group(transform=(c,s,-s,c,x0,y0)) g.add(rect) return g class ShadedPolygon(Widget,LineShape): _attrMap = AttrMap(BASE=LineShape, angle = AttrMapValue(isNumber,desc="Shading angle"), fillColorStart = AttrMapValue(isColorOrNone), fillColorEnd = AttrMapValue(isColorOrNone), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), points = AttrMapValue(isListOfNumbers), ) def __init__(self,**kw): self.angle = 90 self.fillColorStart = colors.red self.fillColorEnd = colors.green self.cylinderMode = 0 self.numShades = 50 self.points = [-1,-1,2,2,3,-1] LineShape.__init__(self,kw) def draw(self): P = self.points P = list(map(lambda i, P=P:(P[i],P[i+1]),range(0,len(P),2))) path = definePath([('moveTo',)+P[0]]+[('lineTo',)+x for x in P[1:]]+['closePath'], fillColor=None, strokeColor=None) path.isClipPath = 1 g = Group() g.add(path) angle = self.angle orientation = 'vertical' if angle==180: angle = 0 elif angle in (90,270): orientation ='horizontal' angle = 0 rect = ShadedRect(strokeWidth=0,strokeColor=None,orientation=orientation) for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': setattr(rect,k,getattr(self,k)) g.add(rotatedEnclosingRect(P, angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__=='__main__': #noruntests angle=45 D = Drawing(120,120) D.add(ShadedPolygon(points=(10,10,60,60,110,10),strokeColor=None,strokeWidth=1,angle=90,numShades=50,cylinderMode=0)) D.save(formats=['gif'],fnRoot='shobj',outDir='/tmp')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/grids.py
0.609059
0.444324
grids.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of flag graphics as widgets. All flags are represented at the ratio of 1:2, even where the official ratio for the flag is something else (such as 3:5 for the German national flag). The only exceptions are for where this would look _very_ wrong, such as the Danish flag whose (ratio is 28:37), or the Swiss flag (which is square). Unless otherwise stated, these flags are all the 'national flags' of the countries, rather than their state flags, naval flags, ensigns or any other variants. (National flags are the flag flown by civilians of a country and the ones usually used to represent a country abroad. State flags are the variants used by the government and by diplomatic missions overseas). To check on how close these are to the 'official' representations of flags, check the World Flag Database at http://www.flags.ndirect.co.uk/ The flags this file contains are: EU Members: United Kingdom, Austria, Belgium, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Luxembourg, Holland (The Netherlands), Spain, Sweden Others: USA, Czech Republic, European Union, Switzerland, Turkey, Brazil (Brazilian flag contributed by Publio da Costa Melo [publio@planetarium.com.br]). """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Line, Rect, Polygon, Drawing, Group, String, Circle, Wedge from reportlab.graphics import renderPDF from reportlab.graphics.widgets.signsandsymbols import _Symbol import copy from math import sin, cos, pi validFlag=OneOf(None, 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'China', 'Cuba', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Japan', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Russia', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil' ) _size = 100. class Star(_Symbol): """This draws a 5-pointed star. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _attrMap = AttrMap(BASE=_Symbol, angle = AttrMapValue(isNumber, desc='angle in degrees'), ) _size = 100. def __init__(self): _Symbol.__init__(self) self.size = 100 self.fillColor = colors.yellow self.strokeColor = None self.angle = 0 def demo(self): D = Drawing(200, 100) et = Star() et.x=50 et.y=0 D.add(et) labelFontSize = 10 D.add(String(et.x+(et.size/2.0),(et.y-(1.2*labelFontSize)), et.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D def draw(self): s = float(self.size) #abbreviate as we will use this a lot g = Group() # new algorithm from markers.StarFive R = float(self.size)/2 r = R*sin(18*(pi/180.0))/cos(36*(pi/180.0)) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*(pi/180.0) P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 # star specific bits star = Polygon(P, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50) g.rotate(self.angle) g.shift(self.x+self.dx,self.y+self.dy) g.add(star) return g class Flag(_Symbol): """This is a generic flag class that all the flags in this file use as a basis. This class basically provides edges and a tidy-up routine to hide any bits of line that overlap the 'outside' of the flag possible attributes: 'x', 'y', 'size', 'fillColor' """ _attrMap = AttrMap(BASE=_Symbol, fillColor = AttrMapValue(isColor, desc='Background color'), border = AttrMapValue(isBoolean, 'Whether a background is drawn'), kind = AttrMapValue(validFlag, desc='Which flag'), ) _cache = {} def __init__(self,**kw): _Symbol.__init__(self) self.kind = None self.size = 100 self.fillColor = colors.white self.border=1 self.setProperties(kw) def availableFlagNames(self): '''return a list of the things we can display''' return [x for x in self._attrMap['kind'].validate._enum if x is not None] def _Flag_None(self): s = _size # abbreviate as we will use this a lot g = Group() g.add(Rect(0, 0, s*2, s, fillColor = colors.purple, strokeColor = colors.black, strokeWidth=0)) return g def _borderDraw(self,f): s = self.size # abbreviate as we will use this a lot g = Group() g.add(f) x, y, sW = self.x+self.dx, self.y+self.dy, self.strokeWidth/2. g.insert(0,Rect(-sW, -sW, width=getattr(self,'_width',2*s)+3*sW, height=getattr(self,'_height',s)+2*sW, fillColor = None, strokeColor = self.strokeColor, strokeWidth=sW*2)) g.shift(x,y) g.scale(s/_size, s/_size) return g def draw(self): kind = self.kind or 'None' f = self._cache.get(kind) if not f: f = getattr(self,'_Flag_'+kind)() self._cache[kind] = f._explode() return self._borderDraw(f) def clone(self): return copy.copy(self) def demo(self): D = Drawing(200, 100) name = self.availableFlagNames() import time name = name[int(time.time()) % len(name)] fx = Flag() fx.kind = name fx.x = 0 fx.y = 0 D.add(fx) labelFontSize = 10 D.add(String(fx.x+(fx.size/2.0),(fx.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = int(fx.size/4.0) D.add(String(fx.x+(fx.size),(fx.y+((fx.size/2.0))), "SAMPLE", fillColor=colors.gold, textAnchor='middle', fontSize=labelFontSize, fontName="Helvetica-Bold")) return D def _Flag_UK(self): s = _size g = Group() w = s*2 g.add(Rect(0, 0, w, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0)) g.add(Polygon([0,0, s*.225,0, w,s*(1-.1125), w,s, w-s*.225,s, 0, s*.1125], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0,s*(1-.1125), 0, s, s*.225,s, w, s*.1125, w,0, w-s*.225,0], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0, s-(s/15.0), (s-((s/10.0)*4)), (s*0.65), (s-(s/10.0)*3), (s*0.65), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([0, 0, (s-((s/10.0)*3)), (s*0.35), (s-((s/10.0)*2)), (s*0.35), (s/10.0), 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, s, (s+((s/10.0)*3)), (s*0.65), (s+((s/10.0)*2)), (s*0.65), w-(s/10.0), s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, (s/15.0), (s+((s/10.0)*4)), (s*0.35), (s+((s/10.0)*3)), (s*0.35), w, 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.42)*2), 0, width=(0.16*s)*2, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.35), width=w, height=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.45)*2), 0, width=(0.1*s)*2, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.4), width=w, height=s*0.2, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_USA(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (13,0, -1): stripeheight = s/13.0 if not (stripecounter%2 == 0): stripecolor = colors.red else: stripecolor = colors.mintcream redorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(redorwhiteline) bluebox = Rect(0, (s-(stripeheight*7)), width=0.8*s, height=stripeheight*7, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) lss = s*0.045 lss2 = lss/2.0 s9 = s/9.0 s7 = s/7.0 for starxcounter in range(5): for starycounter in range(4): ls = Star() ls.size = lss ls.x = 0-s/22.0+lss/2.0+s7+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+lss2 g.add(ls) for starxcounter in range(6): for starycounter in range(5): ls = Star() ls.size = lss ls.x = 0-(s/22.0)+lss/2.0+s/14.0+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+(s/18.0)+lss2 g.add(ls) return g def _Flag_Afghanistan(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) greenbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) return g def _Flag_Austria(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox1 = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox1) redbox2 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox2) return g def _Flag_Belgium(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(0, 0, width=(s/3.0)*2.0, height=s, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(((s/3.0)*2.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) box3 = Rect(((s/3.0)*4.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(box3) return g def _Flag_China(self): s = _size g = Group() self._width = w = s*1.5 g.add(Rect(0, 0, w, s, fillColor=colors.red, strokeColor=None, strokeWidth=0)) def addStar(x,y,size,angle,g=g,w=s/20.0,x0=0,y0=s/2.0): s = Star() s.fillColor=colors.yellow s.angle = angle s.size = size*w*2 s.x = x*w+x0 s.y = y*w+y0 g.add(s) addStar(5,5,3, 0) addStar(10,1,1,36.86989765) addStar(12,3,1,8.213210702) addStar(12,6,1,16.60154960) addStar(10,8,1,53.13010235) return g def _Flag_Cuba(self): s = _size g = Group() for i in range(5): stripe = Rect(0, i*s/5.0, width=s*2, height=s/5.0, fillColor = [colors.darkblue, colors.mintcream][i%2], strokeColor = None, strokeWidth=0) g.add(stripe) redwedge = Polygon(points = [ 0, 0, 4*s/5.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) star = Star() star.x = 2.5*s/10.0 star.y = s/2.0 star.size = 3*s/10.0 star.fillColor = colors.white g.add(star) box = Rect(0, 0, s*2, s, fillColor = None, strokeColor = colors.black, strokeWidth=0) g.add(box) return g def _Flag_Denmark(self): s = _size g = Group() self._width = w = s*1.4 box = Rect(0, 0, w, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox1) whitebox2 = Rect(0, ((s/2.0)-(s/12.0)), width=w, height=s/6.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox2) return g def _Flag_Finland(self): s = _size g = Group() # crossbox specific bits box = Rect(0, 0, s*2, s, fillColor = colors.ghostwhite, strokeColor = colors.black, strokeWidth=0) g.add(box) blueline1 = Rect((s*0.6), 0, width=0.3*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.4), width=s*2, height=s*0.3, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_France(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0) g.add(box) bluebox = Rect(0, 0, width=((s/3.0)*2.0), height=s, fillColor = colors.blue, strokeColor = None, strokeWidth=0) g.add(bluebox) whitebox = Rect(((s/3.0)*2.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) redbox = Rect(((s/3.0)*4.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) return g def _Flag_Germany(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) blackbox1 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox1) redbox1 = Rect(0, (s/3.0), width=s*2.0, height=s/3.0, fillColor = colors.orangered, strokeColor = None, strokeWidth=0) g.add(redbox1) return g def _Flag_Greece(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (9,0, -1): stripeheight = s/9.0 if not (stripecounter%2 == 0): stripecolor = colors.deepskyblue else: stripecolor = colors.mintcream blueorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(blueorwhiteline) bluebox1 = Rect(0, ((s)-stripeheight*5), width=(stripeheight*5), height=stripeheight*5, fillColor = colors.deepskyblue, strokeColor = None, strokeWidth=0) g.add(bluebox1) whiteline1 = Rect(0, ((s)-stripeheight*3), width=stripeheight*5, height=stripeheight, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect((stripeheight*2), ((s)-stripeheight*5), width=stripeheight, height=stripeheight*5, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline2) return g def _Flag_Ireland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.forestgreen, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox = Rect(((s*2.0)/3.0), 0, width=(2.0*(s*2.0)/3.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) orangebox = Rect(((2.0*(s*2.0)/3.0)), 0, width=(s*2.0)/3.0, height=s, fillColor = colors.darkorange, strokeColor = None, strokeWidth=0) g.add(orangebox) return g def _Flag_Italy(self): s = _size g = Group() g.add(Rect(0,0,s*2,s,fillColor=colors.forestgreen,strokeColor=None, strokeWidth=0)) g.add(Rect((2*s)/3.0, 0, width=(s*4)/3.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect((4*s)/3.0, 0, width=(s*2)/3.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_Japan(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0,0,w,s,fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Circle(cx=w/2.0,cy=s/2.0,r=0.3*w,fillColor=colors.red,strokeColor=None, strokeWidth=0)) return g def _Flag_Luxembourg(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.dodgerblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Holland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Portugal(self): return Group() def _Flag_Russia(self): s = _size g = Group() w = self._width = s*1.5 t = s/3.0 g.add(Rect(0, 0, width=w, height=t, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, t, width=w, height=t, fillColor = colors.blue, strokeColor = None, strokeWidth=0)) g.add(Rect(0, 2*t, width=w, height=t, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) return g def _Flag_Spain(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0, 0, width=w, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s/4.0), width=w, height=s/2.0, fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) return g def _Flag_Sweden(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.dodgerblue, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(0, ((s/2.0)-(s/12.0)), width=self._width, height=s/6.0, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) return g def _Flag_Norway(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whiteline1 = Rect(((s*0.2)*2), 0, width=s*0.2, height=s, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect(0, (s*0.4), width=self._width, height=s*0.2, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline2) blueline1 = Rect(((s*0.225)*2), 0, width=0.1*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.45), width=self._width, height=s*0.1, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_CzechRepublic(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, 0, width=s*2, height=s/2.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluewedge = Polygon(points = [ 0, 0, s, (s/2.0), 0, s], fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluewedge) return g def _Flag_Palestine(self): s = _size g = Group() box = Rect(0, s/3.0, s*2, s/3.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(box) greenbox = Rect(0, 0, width=s*2, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 2*s/3.0, width=s*2, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) redwedge = Polygon(points = [ 0, 0, 2*s/3.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) return g def _Flag_Turkey(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitecircle = Circle(cx=((s*0.35)*2), cy=s/2.0, r=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitecircle) redcircle = Circle(cx=((s*0.39)*2), cy=s/2.0, r=s*0.24, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redcircle) ws = Star() ws.angle = 15 ws.size = s/5.0 ws.x = (s*0.5)*2+ws.size/2.0 ws.y = (s*0.5) ws.fillColor = colors.mintcream ws.strokeColor = None g.add(ws) return g def _Flag_Switzerland(self): s = _size g = Group() self._width = s g.add(Rect(0, 0, s, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0)) g.add(Line((s/2.0), (s/5.5), (s/2), (s-(s/5.5)), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=(s/5.0))) g.add(Line((s/5.5), (s/2.0), (s-(s/5.5)), (s/2.0), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=s/5.0)) return g def _Flag_EU(self): s = _size g = Group() w = self._width = 1.5*s g.add(Rect(0, 0, w, s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0)) centerx=w/2.0 centery=s/2.0 radius=s/3.0 yradius = radius xradius = radius nStars = 12 delta = 2*pi/nStars for i in range(nStars): rad = i*delta gs = Star() gs.x=cos(rad)*radius+centerx gs.y=sin(rad)*radius+centery gs.size=s/10.0 gs.fillColor=colors.gold g.add(gs) return g def _Flag_Brazil(self): s = _size # abbreviate as we will use this a lot g = Group() m = s/14.0 self._width = w = (m * 20) def addStar(x,y,size, g=g, w=w, s=s, m=m): st = Star() st.fillColor=colors.mintcream st.size = size*m st.x = (w/2.0) + (x * (0.35 * m)) st.y = (s/2.0) + (y * (0.35 * m)) g.add(st) g.add(Rect(0, 0, w, s, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m, (s/2.0), (w/2.0), s-(1.7*m), w-(1.7*m),(s/2.0),(w/2.0), 1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Circle(cx=w/2.0, cy=s/2.0, r=3.5*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8.5*m, 50, 98.1, 8.5*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0), (s/2.0), 3.501*m, 156, 352, 3.501*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8*m, 48.1, 100, 8*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Rect(0, 0, w, (s/4.0) + 1.7*m, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m,(s/2.0), (w/2.0),s/2.0 - 2*m, w-(1.7*m),(s/2.0) , (w/2.0),1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Wedge(w/2.0, s/2.0, 3.502*m, 166, 342.1, 3.502*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) addStar(3.2,3.5,0.3) addStar(-8.5,1.5,0.3) addStar(-7.5,-3,0.3) addStar(-4,-5.5,0.3) addStar(0,-4.5,0.3) addStar(7,-3.5,0.3) addStar(-3.5,-0.5,0.25) addStar(0,-1.5,0.25) addStar(1,-2.5,0.25) addStar(3,-7,0.25) addStar(5,-6.5,0.25) addStar(6.5,-5,0.25) addStar(7,-4.5,0.25) addStar(-5.5,-3.2,0.25) addStar(-6,-4.2,0.25) addStar(-1,-2.75,0.2) addStar(2,-5.5,0.2) addStar(4,-5.5,0.2) addStar(5,-7.5,0.2) addStar(5,-5.5,0.2) addStar(6,-5.5,0.2) addStar(-8.8,-3.2,0.2) addStar(2.5,0.5,0.2) addStar(-0.2,-3.2,0.14) addStar(-7.2,-2,0.14) addStar(0,-8,0.1) sTmp = "ORDEM E PROGRESSO" nTmp = len(sTmp) delta = 0.850848010347/nTmp radius = 7.9 *m centerx = (w/2.0)-(2*m) centery = 0 for i in range(nTmp): rad = 2*pi - i*delta -4.60766922527 x=cos(rad)*radius+centerx y=sin(rad)*radius+centery if i == 6: z = 0.35*m else: z= 0.45*m g2 = Group(String(x, y, sTmp[i], fontName='Helvetica-Bold', fontSize = z,strokeColor=None,fillColor=colors.green)) g2.rotate(rad) g.add(g2) return g def makeFlag(name): flag = Flag() flag.kind = name return flag def test(): """This function produces three pdf files with examples of all the signs and symbols from this file. """ # page 1 labelFontSize = 10 X = (20,245) flags = [ 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'Denmark', 'Cuba', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil', ] y = Y0 = 530 f = 0 D = None for name in flags: if not D: D = Drawing(450,650) flag = makeFlag(name) i = flags.index(name) flag.x = X[i%2] flag.y = y D.add(flag) D.add(String(flag.x+(flag.size/2.0),(flag.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) if i%2: y = y - 125 if (i%2 and y<0) or name==flags[-1]: renderPDF.drawToFile(D, 'flags%02d.pdf'%f, 'flags.py - Page #%d'%(f+1)) y = Y0 f = f+1 D = None if __name__=='__main__': test()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/flags.py
0.764276
0.523664
flags.py
pypi
__version__='3.3.0' __doc__="""This modules defines a collection of markers used in charts. """ from reportlab.graphics.shapes import Rect, Circle, Polygon, Drawing, Group from reportlab.graphics.widgets.signsandsymbols import SmileyFace from reportlab.graphics.widgetbase import Widget from reportlab.lib.validators import isNumber, isColorOrNone, OneOf, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import isClass from reportlab.graphics.widgets.flags import Flag, _Symbol from math import sin, cos, pi _toradians = pi/180.0 class Marker(Widget): '''A polymorphic class of markers''' _attrMap = AttrMap(BASE=Widget, kind = AttrMapValue( OneOf(None, 'Square', 'Diamond', 'Circle', 'Cross', 'Triangle', 'StarSix', 'Pentagon', 'Hexagon', 'Heptagon', 'Octagon', 'StarFive', 'FilledSquare', 'FilledCircle', 'FilledDiamond', 'FilledCross', 'FilledTriangle','FilledStarSix', 'FilledPentagon', 'FilledHexagon', 'FilledHeptagon', 'FilledOctagon', 'FilledStarFive', 'Smiley','ArrowHead', 'FilledArrowHead'), desc='marker type name'), size = AttrMapValue(isNumber,desc='marker size'), x = AttrMapValue(isNumber,desc='marker x coordinate'), y = AttrMapValue(isNumber,desc='marker y coordinate'), dx = AttrMapValue(isNumber,desc='marker x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='marker y coordinate adjustment'), angle = AttrMapValue(isNumber,desc='marker rotation'), fillColor = AttrMapValue(isColorOrNone, desc='marker fill colour'), strokeColor = AttrMapValue(isColorOrNone, desc='marker stroke colour'), strokeWidth = AttrMapValue(isNumber, desc='marker stroke width'), arrowBarbDx = AttrMapValue(isNumber, desc='arrow only the delta x for the barbs'), arrowHeight = AttrMapValue(isNumber, desc='arrow only height'), ) def __init__(self,*args,**kw): self.setProperties(kw) self._setKeywords( kind = None, strokeColor = black, strokeWidth = 0.1, fillColor = None, size = 5, x = 0, y = 0, dx = 0, dy = 0, angle = 0, arrowBarbDx = -1.25, arrowHeight = 1.875, ) def clone(self,**kwds): n = self.__class__(**self.__dict__) if kwds: n.__dict__.update(kwds) return n def _Smiley(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = SmileyFace() s.fillColor = self.fillColor s.strokeWidth = self.strokeWidth s.strokeColor = self.strokeColor s.x = x-d s.y = y-d s.size = d*2 return s def _Square(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = Rect(x-d,y-d,2*d,2*d,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Diamond(self): d = self.size/2.0 return self._doPolygon((-d,0,0,d,d,0,0,-d)) def _Circle(self): x, y = self.x+self.dx, self.y+self.dy s = Circle(x,y,self.size/2.0,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Cross(self): x, y = self.x+self.dx, self.y+self.dy s = float(self.size) h, s = s/2, s/6 return self._doPolygon((-s,-h,-s,-s,-h,-s,-h,s,-s,s,-s,h,s,h,s,s,h,s,h,-s,s,-s,s,-h)) def _Triangle(self): x, y = self.x+self.dx, self.y+self.dy r = float(self.size)/2 c = 30*_toradians s = sin(30*_toradians)*r c = cos(c)*r return self._doPolygon((0,r,-c,-s,c,-s)) def _StarSix(self): r = float(self.size)/2 c = 30*_toradians s = sin(c)*r c = cos(c)*r z = s/2 g = c/2 return self._doPolygon((0,r,-z,s,-c,s,-s,0,-c,-s,-z,-s,0,-r,z,-s,c,-s,s,0,c,s,z,s)) def _StarFive(self): R = float(self.size)/2 r = R*sin(18*_toradians)/cos(36*_toradians) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*_toradians P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 return self._doPolygon(P) def _Pentagon(self): return self._doNgon(5) def _Hexagon(self): return self._doNgon(6) def _Heptagon(self): return self._doNgon(7) def _Octagon(self): return self._doNgon(8) def _ArrowHead(self): s = self.size h = self.arrowHeight b = self.arrowBarbDx return self._doPolygon((0,0,b,-h,s,0,b,h)) def _doPolygon(self,P): x, y = self.x+self.dx, self.y+self.dy if x or y: P = list(map(lambda i,P=P,A=[x,y]: P[i] + A[i&1], list(range(len(P))))) return Polygon(P, strokeWidth =self.strokeWidth, strokeColor=self.strokeColor, fillColor=self.fillColor) def _doFill(self): old = self.fillColor if old is None: self.fillColor = self.strokeColor r = (self.kind and getattr(self,'_'+self.kind[6:]) or Group)() self.fillColor = old return r def _doNgon(self,n): P = [] size = float(self.size)/2 for i in range(n): r = (2.*i/n+0.5)*pi P.append(size*cos(r)) P.append(size*sin(r)) return self._doPolygon(P) _FilledCircle = _doFill _FilledSquare = _doFill _FilledDiamond = _doFill _FilledCross = _doFill _FilledTriangle = _doFill _FilledStarSix = _doFill _FilledPentagon = _doFill _FilledHexagon = _doFill _FilledHeptagon = _doFill _FilledOctagon = _doFill _FilledStarFive = _doFill _FilledArrowHead = _doFill def draw(self): if self.kind: m = getattr(self,'_'+self.kind) if self.angle: _x, _dx, _y, _dy = self.x, self.dx, self.y, self.dy self.x, self.dx, self.y, self.dy = 0,0,0,0 try: m = m() finally: self.x, self.dx, self.y, self.dy = _x, _dx, _y, _dy if not isinstance(m,Group): _m, m = m, Group() m.add(_m) if self.angle: m.rotate(self.angle) x, y = _x+_dx, _y+_dy if x or y: m.shift(x,y) else: m = m() else: m = Group() return m def uSymbol2Symbol(uSymbol,x,y,color): if isClass(uSymbol) and issubclass(uSymbol,Widget): size = 10. symbol = uSymbol() symbol.x = x - (size/2) symbol.y = y - (size/2) try: symbol.size = size symbol.color = color except: pass elif isinstance(uSymbol,Marker) or isinstance(uSymbol,_Symbol): symbol = uSymbol.clone() if isinstance(uSymbol,Marker): symbol.fillColor = symbol.fillColor or color symbol.x, symbol.y = x, y elif callable(uSymbol): symbol = uSymbol(x, y, 5, color) else: symbol = None return symbol class _isSymbol(Validator): def test(self,x): return hasattr(x,'__call__') or isinstance(x,Marker) or isinstance(x,_Symbol) or (isClass(x) and issubclass(x,Widget)) isSymbol = _isSymbol() def makeMarker(name,**kw): if Marker._attrMap['kind'].validate(name): m = Marker(**kw) m.kind = name elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError("Invalid marker name %s" % name) return m if __name__=='__main__': D = Drawing() D.add(Marker()) D.save(fnRoot='Marker',formats=['pdf'], outDir='/tmp')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/markers.py
0.869361
0.342819
markers.py
pypi
__version__='3.3.0' from reportlab.graphics.widgetbase import Widget from reportlab.graphics import shapes from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing class TableWidget(Widget): """A two dimensions table of labels """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x position of left edge of table"), y = AttrMapValue(isNumber, desc="y position of bottom edge of table"), width = AttrMapValue(isNumber, desc="table width"), height = AttrMapValue(isNumber, desc="table height"), borderStrokeColor = AttrMapValue(isColorOrNone, desc="table border color"), fillColor = AttrMapValue(isColorOrNone, desc="table fill color"), borderStrokeWidth = AttrMapValue(isNumber, desc="border line width"), horizontalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner horizontal lines color"), verticalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner vertical lines color"), horizontalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner horizontal lines width"), verticalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner vertical lines width"), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.'), data = AttrMapValue(None, desc="a list of list of strings to be displayed in the cells"), boxAnchor = AttrMapValue(isBoxAnchor, desc="location of the table anchoring point"), fontName = AttrMapValue(isString, desc="text font in the table"), fontSize = AttrMapValue(isNumber, desc="font size of the table"), fontColor = AttrMapValue(isColorOrNone, desc="font color"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text within cells"), textAnchor = AttrMapValue(OneOf('start','middle','end','numeric'), desc="Alignment of text within cells"), ) def __init__(self, x=10, y=10, **kw): self.x = x self.y = y self.width = 200 self.height = 100 self.borderStrokeColor = colors.black self.fillColor = None self.borderStrokeWidth = 0.5 self.horizontalDividerStrokeColor = colors.black self.verticalDividerStrokeColor = colors.black self.horizontalDividerStrokeWidth = 0.5 self.verticalDividerStrokeWidth = 0.25 self.dividerDashArray = None self.data = [['North','South','East','West'],[100,110,120,130],['A','B','C','D']] # list of rows each row is a list of columns self.boxAnchor = 'nw' #self.fontName = None self.fontSize = 8 self.fontColor = colors.black self.alignment = 'right' self.textAnchor = 'start' for k, v in kw.items(): if k in list(self.__class__._attrMap.keys()): setattr(self, k, v) else: raise ValueError('invalid argument supplied for class %s'%self.__class__) def demo(self): """ returns a sample of this widget with data """ d = Drawing(400, 200) t = TableWidget() d.add(t, name='table') d.table.dividerDashArray = (1, 3, 2) d.table.verticalDividerStrokeColor = None d.table.borderStrokeWidth = 0 d.table.borderStrokeColor = colors.red return d def draw(self): """ returns a group of shapes """ g = shapes.Group() #overall border and fill if self.borderStrokeColor or self.fillColor: # adds border and filling color rect = shapes.Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.borderStrokeColor rect.strokeWidth = self.borderStrokeWidth g.add(rect) #special case - for an empty table we want to avoid divide-by-zero data = self.preProcessData(self.data) rows = len(self.data) cols = len(self.data[0]) #print "(rows,cols)=(%s, %s)"%(rows,cols) row_step = self.height / float(rows) col_step = self.width / float(cols) #print "(row_step,col_step)=(%s, %s)"%(row_step,col_step) # draw the grid if self.horizontalDividerStrokeColor: for i in range(rows): # make horizontal lines x1 = self.x x2 = self.x + self.width y = self.y + row_step*i #print 'line (%s, %s), (%s, %s)'%(x1, y, x2, y) line = shapes.Line(x1, y, x2, y) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.horizontalDividerStrokeWidth line.strokeColor = self.horizontalDividerStrokeColor g.add(line) if self.verticalDividerStrokeColor: for i in range(cols): # make vertical lines x = self.x+col_step*i y1 = self.y y2 = self.y + self.height #print 'line (%s, %s), (%s, %s)'%(x, y1, x, y2) line = shapes.Line(x, y1, x, y2) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.verticalDividerStrokeWidth line.strokeColor = self.verticalDividerStrokeColor g.add(line) # since we plot data from down up, we reverse the list self.data.reverse() for (j, row) in enumerate(self.data): y = self.y + j*row_step + 0.5*row_step - 0.5 * self.fontSize for (i, datum) in enumerate(row): if datum: x = self.x + i*col_step + 0.5*col_step s = shapes.String(x, y, str(datum), textAnchor=self.textAnchor) s.fontName = self.fontName s.fontSize = self.fontSize s.fillColor = self.fontColor g.add(s) return g def preProcessData(self, data): """preprocess and return a new array with at least one row and column (use a None) if needed, and all rows the same length (adding Nones if needed) """ if not data: return [[None]] #make all rows have similar number of cells, append None when needed max_row = max( [len(x) for x in data] ) for rowNo, row in enumerate(data): if len(row) < max_row: row.extend([None]*(max_row-len(row))) return data #test if __name__ == '__main__': d = TableWidget().demo() import os d.save(formats=['pdf'],outDir=os.getcwd(),fnRoot=None)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/table.py
0.5144
0.35883
table.py
pypi
from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, Group, Polygon from reportlab.graphics.widgetbase import Widget class AdjustableArrow(Widget): """This widget draws an arrow (style one). possible attributes: 'x', 'y', 'size', 'fillColor' """ _attrMap = AttrMap( x = AttrMapValue(isNumber,desc='symbol x coordinate'), y = AttrMapValue(isNumber,desc='symbol y coordinate'), dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), stemThickness = AttrMapValue(isNumber, 'width of the stem'), stemLength = AttrMapValue(isNumber, 'length of the stem'), headProjection = AttrMapValue(isNumber, 'how much the head projects from the stem'), headLength = AttrMapValue(isNumber, 'length of the head'), headSweep = AttrMapValue(isNumber, 'howmuch the head sweeps back (-ve) or forwards (+ve)'), scale = AttrMapValue(isNumber, 'scaling factor'), fillColor = AttrMapValue(isColorOrNone), strokeColor = AttrMapValue(isColorOrNone), strokeWidth = AttrMapValue(isNumber), boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), right =AttrMapValue(isBoolean,desc='If True (default) the arrow is horizontal pointing right\nFalse means it points up'), angle = AttrMapValue(isNumber, desc='angle of arrow default (0), right True 0 is horizontal to right else vertical up'), ) def __init__(self,**kwds): self._setKeywords(**kwds) self._setKeywords(**dict( x = 0, y = 0, fillColor = colors.red, strokeWidth = 0, strokeColor = None, boxAnchor = 'c', angle = 0, stemThickness = 33, stemLength = 50, headProjection = 15, headLength = 50, headSweep = 0, scale = 1., right=True, )) def draw(self): # general widget bits g = Group() x = self.x y = self.y scale = self.scale stemThickness = self.stemThickness*scale stemLength = self.stemLength*scale headProjection = self.headProjection*scale headLength = self.headLength*scale headSweep = self.headSweep*scale w = stemLength+headLength h = 2*headProjection+stemThickness # shift to the boxAnchor boxAnchor = self.boxAnchor if self.right: if boxAnchor in ('sw','w','nw'): dy = -h elif boxAnchor in ('s','c','n'): dy = -h*0.5 else: dy = 0 if boxAnchor in ('w','c','e'): dx = -w*0.5 elif boxAnchor in ('nw','n','ne'): dx = -w else: dx = 0 points = [ dx, dy+headProjection+stemThickness, dx+stemLength, dy+headProjection+stemThickness, dx+stemLength+headSweep, dy+2*headProjection+stemThickness, dx+stemLength+headLength, dy+0.5*stemThickness+headProjection, dx+stemLength+headSweep, dy, dx+stemLength, dy+headProjection, dx, dy+headProjection, ] else: w,h = h,w if boxAnchor in ('nw','n','ne'): dy = -h elif boxAnchor in ('w','c','e'): dy = -h*0.5 else: dy = 0 if boxAnchor in ('ne','e','se'): dx = -w elif boxAnchor in ('n','c','s'): dx = -w*0.5 else: dx = 0 points = [ dx+headProjection, dy, #sw dx+headProjection+stemThickness, dy, #se dx+headProjection+stemThickness, dy+stemLength, dx+w, dy+stemLength+headSweep, dx+headProjection+0.5*stemThickness, dy+h, dx, dy+stemLength+headSweep, dx+headProjection, dy+stemLength, ] g.add(Polygon( points = points, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth, )) g.translate(x,y) g.rotate(self.angle) return g class AdjustableArrowDrawing(_DrawingEditorMixin,Drawing): def __init__(self,width=100,height=63,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,AdjustableArrow(),name='adjustableArrow',validate=None,desc=None)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/graphics/widgets/adjustableArrow.py
0.506347
0.235757
adjustableArrow.py
pypi
__version__='3.4.34' __doc__='''Utility functions to position and resize boxes within boxes''' def rectCorner(x, y, width, height, anchor='sw', dims=False): '''given rectangle controlled by x,y width and height return the corner corresponding to the anchor''' if anchor not in ('nw','w','sw'): if anchor in ('n','c','s'): x += width/2. else: x += width if anchor not in ('sw','s','se'): if anchor in ('w','c','e'): y += height/2. else: y += height return (x,y,width,height) if dims else (x,y) def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight,anchorAtXY=False): """This function helps position an image within a box. It first normalizes for two cases: - if the width is None, it assumes imWidth - ditto for height - if width or height is negative, it adjusts x or y and makes them positive Given (a) the enclosing box (defined by x,y,width,height where x,y is the \ lower left corner) which you wish to position the image in, and (b) the image size (imWidth, imHeight), and (c) the 'anchor point' as a point of the compass - n,s,e,w,ne,se etc \ and c for centre, this should return the position at which the image should be drawn, as well as a scale factor indicating what scaling has happened. It returns the parameters which would be used to draw the image without any adjustments: x,y, width, height, scale used in canvas.drawImage and drawInlineImage """ scale = 1.0 if width is None: width = imWidth if height is None: height = imHeight if width<0: width = -width x -= width if height<0: height = -height y -= height if preserve: imWidth = abs(imWidth) imHeight = abs(imHeight) scale = min(width/float(imWidth),height/float(imHeight)) owidth = width oheight = height width = scale*imWidth-1e-8 height = scale*imHeight-1e-8 if not anchorAtXY: # if anchor not in ('nw','w','sw'): # dx = owidth-width # if anchor in ('n','c','s'): # x += dx/2. # else: # x += dx # if anchor not in ('sw','s','se'): # dy = oheight-height # if anchor in ('w','c','e'): # y += dy/2. # else: # y += dy x, y = rectCorner(x,y,owidth-width,oheight-height,anchor) if anchorAtXY: if anchor not in ('sw','s','se'): y -= height/2. if anchor in ('e','c','w') else height if anchor not in ('nw','w','sw'): x -= width/2. if anchor in ('n','c','s') else width return x,y, width, height, scale
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/lib/boxstuff.py
0.459076
0.482307
boxstuff.py
pypi
__version__='3.3.0' __doc__=""" Module to analyze Python source code; for syntax coloring tools. Interface:: tags = fontify(pytext, searchfrom, searchto) - The 'pytext' argument is a string containing Python source code. - The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext. - The returned value is a list of tuples, formatted like this:: [('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ] - The tuple contents are always like this:: (tag, startindex, endindex, sublist) - tag is one of 'keyword', 'string', 'comment' or 'identifier' - sublist is not used, hence always None. """ # Based on FontText.py by Mitchell S. Chapman, # which was modified by Zachary Roadhouse, # then un-Tk'd by Just van Rossum. # Many thanks for regular expression debugging & authoring are due to: # Tim (the-incredib-ly y'rs) Peters and Cristian Tismer # So, who owns the copyright? ;-) How about this: # Copyright 1996-2001: # Mitchell S. Chapman, # Zachary Roadhouse, # Tim Peters, # Just van Rossum __version__ = "0.4" import re # First a little helper, since I don't like to repeat things. (Tismer speaking) def replace(src, sep, rep): return rep.join(src.split(sep)) # This list of keywords is taken from ref/node13.html of the # Python 1.3 HTML documentation. ("access" is intentionally omitted.) keywordsList = [ "as", "assert", "exec", "del", "from", "lambda", "return", "and", "elif", "global", "not", "try", "break", "else", "if", "or", "while", "class", "except", "import", "pass", "continue", "finally", "in", "print", "def", "for", "is", "raise", "yield", "with"] # Build up a regular expression which will match anything # interesting, including multi-line triple-quoted strings. commentPat = r"#[^\n]*" pat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q" quotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Way to go, Tim! pat = r""" qqq [^\\q]* ( ( \\[\000-\377] | q ( \\[\000-\377] | [^\q] | q ( \\[\000-\377] | [^\\q] ) ) ) [^\\q]* )* qqq """ pat = ''.join(pat.split()) # get rid of whitespace tripleQuotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Build up a regular expression which matches all and only # Python keywords. This will let us skip the uninteresting # identifier references. # nonKeyPat identifies characters which may legally precede # a keyword pattern. nonKeyPat = r"(^|[^a-zA-Z0-9_.\"'])" keyPat = nonKeyPat + "(" + "|".join(keywordsList) + ")" + nonKeyPat matchPat = commentPat + "|" + keyPat + "|" + tripleQuotePat + "|" + quotePat matchRE = re.compile(matchPat) idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace. idRE = re.compile(idKeyPat) def fontify(pytext, searchfrom = 0, searchto = None): if searchto is None: searchto = len(pytext) # Cache a few attributes for quicker reference. search = matchRE.search idSearch = idRE.search tags = [] tags_append = tags.append commentTag = 'comment' stringTag = 'string' keywordTag = 'keyword' identifierTag = 'identifier' start = 0 end = searchfrom while 1: m = search(pytext, end) if m is None: break # EXIT LOOP start = m.start() if start >= searchto: break # EXIT LOOP match = m.group(0) end = start + len(match) c = match[0] if c not in "#'\"": # Must have matched a keyword. if start != searchfrom: # there's still a redundant char before and after it, strip! match = match[1:-1] start = start + 1 else: # this is the first keyword in the text. # Only a space at the end. match = match[:-1] end = end - 1 tags_append((keywordTag, start, end, None)) # If this was a defining keyword, look ahead to the # following identifier. if match in ["def", "class"]: m = idSearch(pytext, end) if m is not None: start = m.start() if start == end: match = m.group(0) end = start + len(match) tags_append((identifierTag, start, end, None)) elif c == "#": tags_append((commentTag, start, end, None)) else: tags_append((stringTag, start, end, None)) return tags def test(path): f = open(path) text = f.read() f.close() tags = fontify(text) for tag, start, end, sublist in tags: print(tag, repr(text[start:end]))
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/lib/PyFontify.py
0.577495
0.361475
PyFontify.py
pypi
__version__='3.5.33' __doc__="""Standard verifying functions used by attrmap.""" import codecs, re from reportlab.lib.utils import isSeq, isBytes, isStr from reportlab.lib import colors try: _re_Pattern = re.Pattern except AttributeError: _re_Pattern = re._pattern_type class Percentage(float): pass class Validator: "base validator class" def __call__(self,x): return self.test(x) def __str__(self): return getattr(self,'_str',self.__class__.__name__) def normalize(self,x): return x def normalizeTest(self,x): try: self.normalize(x) return True except: return False class _isAnything(Validator): def test(self,x): return True class _isNothing(Validator): def test(self,x): return False class _isBoolean(Validator): def test(self,x): if isinstance(int,bool): return x in (0,1) return self.normalizeTest(x) def normalize(self,x): if x in (0,1): return x try: S = x.upper() except: raise ValueError('Must be boolean not %s' % ascii(s)) if S in ('YES','TRUE'): return True if S in ('NO','FALSE',None): return False raise ValueError('Must be boolean not %s' % ascii(s)) class _isString(Validator): def test(self,x): return isStr(x) class _isCodec(Validator): def test(self,x): if not isStr(x): return False try: a,b,c,d = codecs.lookup(x) return True except LookupError: return False class _isNumber(Validator): def test(self,x): if isinstance(x,(float,int)): return True return self.normalizeTest(x) def normalize(self,x): try: return float(x) except: return int(x) class _isInt(Validator): def test(self,x): if not isinstance(x,int) and not isStr(x): return False return self.normalizeTest(x) def normalize(self,x): return int(x.decode('utf8') if isBytes(x) else x) class _isNumberOrNone(_isNumber): def test(self,x): return x is None or isNumber(x) def normalize(self,x): if x is None: return x return _isNumber.normalize(x) class _isListOfNumbersOrNone(Validator): "ListOfNumbersOrNone validator class." def test(self, x): if x is None: return True return isListOfNumbers(x) class isNumberInRange(_isNumber): def __init__(self, min, max): self.min = min self.max = max def test(self, x): try: n = self.normalize(x) if self.min <= n <= self.max: return True except ValueError: pass return False class _isListOfShapes(Validator): "ListOfShapes validator class." def test(self, x): from reportlab.graphics.shapes import Shape if isSeq(x): answer = 1 for e in x: if not isinstance(e, Shape): answer = 0 return answer else: return False class _isListOfStringsOrNone(Validator): "ListOfStringsOrNone validator class." def test(self, x): if x is None: return True return isListOfStrings(x) class _isTransform(Validator): "Transform validator class." def test(self, x): if isSeq(x): if len(x) == 6: for element in x: if not isNumber(element): return False return True else: return False else: return False class _isColor(Validator): "Color validator class." def test(self, x): return isinstance(x, colors.Color) class _isColorOrNone(Validator): "ColorOrNone validator class." def test(self, x): if x is None: return True return isColor(x) from reportlab.lib.normalDate import NormalDate class _isNormalDate(Validator): def test(self,x): if isinstance(x,NormalDate): return True return x is not None and self.normalizeTest(x) def normalize(self,x): return NormalDate(x) class _isValidChild(Validator): "ValidChild validator class." def test(self, x): """Is this child allowed in a drawing or group? I.e. does it descend from Shape or UserNode? """ from reportlab.graphics.shapes import UserNode, Shape return isinstance(x, UserNode) or isinstance(x, Shape) class _isValidChildOrNone(_isValidChild): def test(self,x): return _isValidChild.test(self,x) or x is None class _isCallable(Validator): def test(self, x): return hasattr(x,'__call__') class OneOf(Validator): """Make validator functions for list of choices. Usage: f = reportlab.lib.validators.OneOf('happy','sad') or f = reportlab.lib.validators.OneOf(('happy','sad')) f('sad'),f('happy'), f('grumpy') (1,1,0) """ def __init__(self, enum,*args): if isSeq(enum): if args!=(): raise ValueError("Either all singleton args or a single sequence argument") self._enum = tuple(enum)+args else: self._enum = (enum,)+args self._patterns = tuple((_ for _ in self._enum if isinstance(_,_re_Pattern))) if self._patterns: self._enum = tuple((_ for _ in self._enum if not isinstance(_,_re_Pattern))) self.test = self._test_patterns def test(self, x): return x in self._enum def _test_patterns(self, x): v = x in self._enum #print(f'{x=} {self._enum=!r} {self._patterns=!r} {v=}') if v: return True for p in self._patterns: v = p.match(x) if v: return True return False class SequenceOf(Validator): def __init__(self,elemTest,name=None,emptyOK=1, NoneOK=0, lo=0,hi=0x7fffffff): self._elemTest = elemTest self._emptyOK = emptyOK self._NoneOK = NoneOK self._lo, self._hi = lo, hi if name: self._str = name def test(self, x): if not isSeq(x): if x is None: return self._NoneOK return False if x==[] or x==(): return self._emptyOK elif not self._lo<=len(x)<=self._hi: return False for e in x: if not self._elemTest(e): return False return True class EitherOr(Validator): def __init__(self,tests,name=None): if not isSeq(tests): tests = (tests,) self._tests = tests if name: self._str = name def test(self, x): for t in self._tests: if t(x): return True return False class NoneOr(EitherOr): def test(self, x): return x is None or super().test(x) class NotSetOr(EitherOr): _not_set = object() def test(self, x): return x is NotSetOr._not_set or super().test(x) @staticmethod def conditionalValue(v,a): return a if v is NotSetOr._not_set else v class _isNotSet(Validator): def test(self,x): return x is NotSetOr._not_set class Auto(Validator): def __init__(self,**kw): self.__dict__.update(kw) def test(self,x): return x is self.__class__ or isinstance(x,self.__class__) class AutoOr(EitherOr): def test(self,x): return isAuto(x) or super().test(x) class isInstanceOf(Validator): def __init__(self,klass=None): self._klass = klass def test(self,x): return isinstance(x,self._klass) class isSubclassOf(Validator): def __init__(self,klass=None): self._klass = klass def test(self,x): return issubclass(x,self._klass) class matchesPattern(Validator): """Matches value, or its string representation, against regex""" def __init__(self, pattern): self._pattern = re.compile(pattern) def test(self,x): x = str(x) print('testing %s against %s' % (x, self._pattern)) return (self._pattern.match(x) != None) class DerivedValue: """This is used for magic values which work themselves out. An example would be an "inherit" property, so that one can have drawing.chart.categoryAxis.labels.fontName = inherit and pick up the value from the top of the drawing. Validators will permit this provided that a value can be pulled in which satisfies it. And the renderer will have special knowledge of these so they can evaluate themselves. """ def getValue(self, renderer, attr): """Override this. The renderers will pass the renderer, and the attribute name. Algorithms can then backtrack up through all the stuff the renderer provides, including a correct stack of parent nodes.""" return None class Inherit(DerivedValue): def __repr__(self): return "inherit" def getValue(self, renderer, attr): return renderer.getStateValue(attr) inherit = Inherit() class NumericAlign(str): '''for creating the numeric string value for anchors etc etc dp is the character to align on (the last occurrence will be used) dpLen is the length of characters after the dp ''' def __new__(cls,dp='.',dpLen=0): self = str.__new__(cls,'numeric') self._dp=dp self._dpLen = dpLen return self isAuto = Auto() isBoolean = _isBoolean() isString = _isString() isCodec = _isCodec() isNumber = _isNumber() isInt = _isInt() isNoneOrInt = NoneOr(isInt,'isNoneOrInt') isNumberOrNone = _isNumberOrNone() isTextAnchor = OneOf('start','middle','end','boxauto') isListOfNumbers = SequenceOf(isNumber,'isListOfNumbers') isListOfNoneOrNumber = SequenceOf(isNumberOrNone,'isListOfNoneOrNumber') isListOfListOfNoneOrNumber = SequenceOf(isListOfNoneOrNumber,'isListOfListOfNoneOrNumber') isListOfNumbersOrNone = _isListOfNumbersOrNone() isListOfShapes = _isListOfShapes() isListOfStrings = SequenceOf(isString,'isListOfStrings') isListOfStringsOrNone = _isListOfStringsOrNone() isTransform = _isTransform() isColor = _isColor() isListOfColors = SequenceOf(isColor,'isListOfColors') isColorOrNone = _isColorOrNone() isShape = isValidChild = _isValidChild() isNoneOrShape = isValidChildOrNone = _isValidChildOrNone() isAnything = _isAnything() isNothing = _isNothing() isXYCoord = SequenceOf(isNumber,lo=2,hi=2,emptyOK=0) isBoxAnchor = OneOf('nw','n','ne','w','c','e','sw','s','se', 'autox', 'autoy') isNoneOrString = NoneOr(isString,'NoneOrString') isNoneOrListOfNoneOrStrings=SequenceOf(isNoneOrString,'isNoneOrListOfNoneOrStrings',NoneOK=1) isListOfNoneOrString=SequenceOf(isNoneOrString,'isListOfNoneOrString',NoneOK=0) isNoneOrListOfNoneOrNumbers=SequenceOf(isNumberOrNone,'isNoneOrListOfNoneOrNumbers',NoneOK=1) isCallable = _isCallable() isNoneOrCallable = NoneOr(isCallable) isStringOrCallable=EitherOr((isString,isCallable),'isStringOrCallable') isStringOrCallableOrNone=NoneOr(isStringOrCallable,'isStringOrCallableNone') isStringOrNone=NoneOr(isString,'isStringOrNone') isNormalDate=_isNormalDate() isNotSet=_isNotSet()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/src/reportlab/lib/validators.py
0.518546
0.237068
validators.py
pypi
from tools.docco.rl_doc_utils import * #begin chapter oon paragraphs heading1("Paragraphs") disc(""" The $reportlab.platypus.Paragraph$ class is one of the most useful of the Platypus $Flowables$; it can format fairly arbitrary text and provides for inline font style and colour changes using an XML style markup. The overall shape of the formatted text can be justified, right or left ragged or centered. The XML markup can even be used to insert greek characters or to do subscripts. """) disc("""The following text creates an instance of the $Paragraph$ class:""") eg("""Paragraph(text, style, bulletText=None)""") disc("""The $text$ argument contains the text of the paragraph; excess white space is removed from the text at the ends and internally after linefeeds. This allows easy use of indented triple quoted text in <b>Python</b> scripts. The $bulletText$ argument provides the text of a default bullet for the paragraph. The font and other properties for the paragraph text and bullet are set using the style argument. """) disc(""" The $style$ argument should be an instance of class $ParagraphStyle$ obtained typically using""") eg(""" from reportlab.lib.styles import ParagraphStyle """) disc(""" this container class provides for the setting of multiple default paragraph attributes in a structured way. The styles are arranged in a dictionary style object called a $stylesheet$ which allows for the styles to be accessed as $stylesheet['BodyText']$. A sample style sheet is provided. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet stylesheet=getSampleStyleSheet() normalStyle = stylesheet['Normal'] """) disc(""" The options which can be set for a $Paragraph$ can be seen from the $ParagraphStyle$ defaults. The values with leading underscore ('_') are derived from the defaults in module $reportlab.rl_config$ which are derived from module $reportlab.rl_settings$. """) heading4("$class ParagraphStyle$") eg(""" class ParagraphStyle(PropertySet): defaults = { 'fontName':_baseFontName, 'fontSize':10, 'leading':12, 'leftIndent':0, 'rightIndent':0, 'firstLineIndent':0, 'alignment':TA_LEFT, 'spaceBefore':0, 'spaceAfter':0, 'bulletFontName':_baseFontName, 'bulletFontSize':10, 'bulletIndent':0, 'textColor': black, 'backColor':None, 'wordWrap':None, 'borderWidth': 0, 'borderPadding': 0, 'borderColor': None, 'borderRadius': None, 'allowWidows': 1, 'allowOrphans': 0, 'textTransform':None, 'endDots':None, 'splitLongWords':1, 'underlineWidth': _baseUnderlineWidth, 'bulletAnchor': 'start', 'justifyLastLine': 0, 'justifyBreaks': 0, 'spaceShrinkage': _spaceShrinkage, 'strikeWidth': _baseStrikeWidth, #stroke width 'underlineOffset': _baseUnderlineOffset, #fraction of fontsize to offset underlines 'underlineGap': _baseUnderlineGap, #gap for double/triple underline 'strikeOffset': _baseStrikeOffset, #fraction of fontsize to offset strikethrough 'strikeGap': _baseStrikeGap, #gap for double/triple strike 'linkUnderline': _platypus_link_underline, #'underlineColor': None, #'strikeColor': None, 'hyphenationLang': _hyphenationLang, 'uriWasteReduce': _uriWasteReduce, 'embeddedHyphenation': _embeddedHyphenation, } """) heading2("Using Paragraph Styles") #this will be used in the ParaBox demos. sample = """You are hereby charged that on the 28th day of May, 1970, you did willfully, unlawfully, and with malice of forethought, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""" disc("""The $Paragraph$ and $ParagraphStyle$ classes together handle most common formatting needs. The following examples draw paragraphs in various styles, and add a bounding box so that you can see exactly what space is taken up.""") s1 = ParagraphStyle('Normal') parabox(sample, s1, 'The default $ParagraphStyle$') disc("""The two attributes $spaceBefore$ and $spaceAfter$ do what they say, except at the top or bottom of a frame. At the top of a frame, $spaceBefore$ is ignored, and at the bottom, $spaceAfter$ is ignored. This means that you could specify that a 'Heading2' style had two inches of space before when it occurs in mid-page, but will not get acres of whitespace at the top of a page. These two attributes should be thought of as 'requests' to the Frame and are not part of the space occupied by the Paragraph itself.""") disc("""The $fontSize$ and $fontName$ tags are obvious, but it is important to set the $leading$. This is the spacing between adjacent lines of text; a good rule of thumb is to make this 20% larger than the point size. To get double-spaced text, use a high $leading$. If you set $autoLeading$(default $"off"$) to $"min"$(use observed leading even if smaller than specified) or $"max"$(use the larger of observed and specified) then an attempt is made to determine the leading on a line by line basis. This may be useful if the lines contain different font sizes etc.""") disc("""The figure below shows space before and after and an increased leading:""") parabox(sample, ParagraphStyle('Spaced', spaceBefore=6, spaceAfter=6, leading=16), 'Space before and after and increased leading' ) disc("""The attribute $borderPadding$ adjusts the padding between the paragraph and the border of its background. This can either be a single value or a tuple containing 2 to 4 values. These values are applied the same way as in Cascading Style Sheets (CSS). If a single value is given, that value is applied to all four sides. If more than one value is given, they are applied in clockwise order to the sides starting at the top. If two or three values are given, the missing values are taken from the opposite side(s). Note that in the following example the yellow box is drawn by the paragraph itself.""") parabox(sample, ParagraphStyle('padded', borderPadding=(7, 2, 20), borderColor='#000000', borderWidth=1, backColor='#FFFF00'), 'Variable padding' ) disc("""The $leftIndent$ and $rightIndent$ attributes do exactly what you would expect; $firstLineIndent$ is added to the $leftIndent$ of the first line. If you want a straight left edge, remember to set $firstLineIndent$ equal to 0.""") parabox(sample, ParagraphStyle('indented', firstLineIndent=+24, leftIndent=24, rightIndent=24), 'one third inch indents at left and right, two thirds on first line' ) disc("""Setting $firstLineIndent$ equal to a negative number, $leftIndent$ much higher, and using a different font (we'll show you how later!) can give you a definition list:.""") parabox('<b><i>Judge Pickles: </i></b>' + sample, ParagraphStyle('dl', leftIndent=36), 'Definition Lists' ) disc("""There are four possible values of $alignment$, defined as constants in the module <i>reportlab.lib.enums</i>. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.""") disc("""Set $wordWrap$ to $'CJK'$ to get Asian language linewrapping. For normal western text you can change the way the line breaking algorithm handles <i>widows</i> and <i>orphans</i> with the $allowWidows$ and $allowOrphans$ values. Both should normally be set to $0$, but for historical reasons we have allowed <i>widows</i>. The default color of the text can be set with $textColor$ and the paragraph background colour can be set with $backColor$. The paragraph's border properties may be changed using $borderWidth$, $borderPadding$, $borderColor$ and $borderRadius$.""") disc("""The $textTransform$ attribute can be <b><i>None</i></b>, <i>'uppercase'</i> or <i>'lowercase'</i> to get the obvious result and <i>'capitalize'</i> to get initial letter capitalization.""") disc("""Attribute $endDots$ can be <b><i>None</i></b>, a string, or an object with attributes text and optional fontName, fontSize, textColor, backColor and dy(y offset) to specify trailing matter on the last line of left/right justified paragraphs.""") disc("""The $splitLongWords$ attribute can be set to a false value to avoid splitting very long words.""") disc("""Attribute $bulletAnchor$ can be <i>'start'</i>, <i>'middle'</i>, <i>'end'</i> or <i>'numeric'</i> to control where the bullet is anchored.""") disc("""The $justifyBreaks$ attribute controls whether lines deliberately broken with a $&lt;br/&gt;$ tag should be justified""") disc("""Attribute $spaceShrinkage$ is a fractional number specifiying by how much the space of a paragraph line may be shrunk in order to make it fit; typically it is something like 0.05""") disc("""The $underlineWidth$, $underlineOffset$, $underlineGap$ &amp; $underlineColor$ attributes control the underline behaviour when the $&lt;u&gt;$ or a linking tag is used. Those tags can have override values of these attributes. The attribute value for width &amp; offset is a $fraction * Letter$ where letter can be one of $P$, $L$, $f$ or $F$ representing fontSize proportions. $P$ uses the fontsize at the tag, $F$ is the maximum fontSize in the tag, $f$ is the initial fontsize inside the tag. $L$ means the global (paragrpah style) font size. $strikeWidth$, $strikeOffset$, $strikeGap$ &amp; $strikeColor$ attributes do the same for strikethrough lines. """) disc("""Attribute $linkUnderline$ controls whether link tags are automatically underlined.""") disc("""If the $pyphen$ python module is installed attribute $hyphenationLang$ controls which language will be used to hyphenate words without explicit embedded hyphens.""") disc("""If $embeddedHyphenation$ is set then attempts will be made to split words with embedded hyphens.""") disc("""Attribute $uriWasteReduce$ controls how we attempt to split long uri's. It is the fraction of a line that we regard as too much waste. The default in module $reportlab.rl_settings$ is <i>0.5</i> which means that we will try and split a word that looks like a uri if we would waste at least half of the line.""") disc("""Currently the hyphenation and uri splitting are turned off by default. You need to modify the default settings by using the file $~/.rl_settings$ or adding a module $reportlab_settings.py$ to the python path. Suitable values are""") eg(""" hyphenationLanguage='en_GB' embeddedHyphenation=1 uriWasteReduce=0.3 """) heading2("Paragraph XML Markup Tags") disc("""XML markup can be used to modify or specify the overall paragraph style, and also to specify intra- paragraph markup.""") heading3("The outermost &lt; para &gt; tag") disc(""" The paragraph text may optionally be surrounded by &lt;para attributes....&gt; &lt;/para&gt; tags. The attributes if any of the opening &lt;para&gt; tag affect the style that is used with the $Paragraph$ $text$ and/or $bulletText$. """) disc(" ") from reportlab.platypus.paraparser import _addAttributeNames, _paraAttrMap, _bulletAttrMap def getAttrs(A): _addAttributeNames(A) S={} for k, v in A.items(): a = v[0] if a not in S: S[a] = [k] else: S[a].append(k) K = list(sorted(S.keys())) K.sort() D=[('Attribute','Synonyms')] for k in K: D.append((k,", ".join(list(sorted(S[k]))))) cols=2*[None] rows=len(D)*[None] return D,cols,rows t=Table(*getAttrs(_paraAttrMap)) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Synonyms for style attributes""") disc("""Some useful synonyms have been provided for our Python attribute names, including lowercase versions, and the equivalent properties from the HTML standard where they exist. These additions make it much easier to build XML-printing applications, since much intra-paragraph markup may not need translating. The table below shows the allowed attributes and synonyms in the outermost paragraph tag.""") CPage(1) heading2("Intra-paragraph markup") disc("""<![CDATA[Within each paragraph, we use a basic set of XML tags to provide markup. The most basic of these are bold (<b>...</b>), italic (<i>...</i>) and underline (<u>...</u>). Other tags which are allowed are strong (<strong>...</strong>), and strike through (<strike>...</strike>). The <link> and <a> tags may be used to refer to URIs, documents or bookmarks in the current document. The a variant of the <a> tag can be used to mark a position in a document. A break (<br/>) tag is also allowed.]]> """) parabox2("""<b>You are hereby charged</b> that on the 28th day of May, 1970, you did willfully, unlawfully, and <i>with malice of forethought</i>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. <u>How do you plead</u>?""", "Simple bold and italic tags") parabox2("""This <a href="#MYANCHOR" color="blue">is a link to</a> an anchor tag ie <a name="MYANCHOR"/><font color="green">here</font>. This <link href="#MYANCHOR" color="blue" fontName="Helvetica">is another link to</link> the same anchor tag.""", "anchors and links") disc("""The <b>link</b> tag can be used as a reference, but not as an anchor. The a and link hyperlink tags have additional attributes <i>fontName</i>, <i>fontSize</i>, <i>color</i> &amp; <i>backColor</i> attributes. The hyperlink reference can have a scheme of <b>http:</b><i>(external webpage)</i>, <b>pdf:</b><i>(different pdf document)</i> or <b>document:</b><i>(same pdf document)</i>; a missing scheme is treated as <b>document</b> as is the case when the reference starts with # (in which case the anchor should omit it). Any other scheme is treated as some kind of URI. """) parabox2("""<strong>You are hereby charged</strong> that on the 28th day of May, 1970, you did willfully, unlawfully, <strike>and with malice of forethought</strike>, <br/>publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "Strong, strike, and break tags") heading3("The $&lt;font&gt;$ tag") disc("""The $&lt;font&gt;$ tag can be used to change the font name, size and text color for any substring within the paragraph. Legal attributes are $size$, $face$, $name$ (which is the same as $face$), $color$, and $fg$ (which is the same as $color$). The $name$ is the font family name, without any 'bold' or 'italic' suffixes. Colors may be HTML color names or a hex string encoded in a variety of ways; see ^reportlab.lib.colors^ for the formats allowed.""") parabox2("""<font face="times" color="red">You are hereby charged</font> that on the 28th day of May, 1970, you did willfully, unlawfully, and <font size=14>with malice of forethought</font>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "The $font$ tag") heading3("Superscripts and Subscripts") disc("""Superscripts and subscripts are supported with the <![CDATA[<super>/<sup> and <sub> tags, which work exactly as you might expect. Additionally these three tags have attributes rise and size to optionally set the rise/descent and font size for the superscript/subscript text. In addition, most greek letters can be accessed by using the <greek></greek> tag, or with mathML entity names.]]>""") ##parabox2("""<greek>epsilon</greek><super><greek>iota</greek> ##<greek>pi</greek></super> = -1""", "Greek letters and subscripts") parabox2("""Equation (&alpha;): <greek>e</greek> <super rise=9 size=6><greek>ip</greek></super> = -1""", "Greek letters and superscripts") heading3("Inline Images") disc("""We can embed images in a paragraph with the &lt;img/&gt; tag which has attributes $src$, $width$, $height$ whose meanings are obvious. The $valign$ attribute may be set to a css like value from "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom"; the value may also be a numeric percentage or an absolute value. """) parabox2("""<para autoLeading="off" fontSize=12>This &lt;img/&gt; <img src="../images/testimg.gif" valign="top"/> is aligned <b>top</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="bottom"/> is aligned <b>bottom</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="middle"/> is aligned <b>middle</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="-4"/> is aligned <b>-4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="+4"/> is aligned <b>+4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" width="10"/> has width <b>10</b>.<br/><br/> </para>""","Inline images") disc("""The $src$ attribute can refer to a remote location eg $src="https://www.reportlab.com/images/logo.gif"$. By default we set $rl_config.trustedShemes$ to $['https','http', 'file', 'data', 'ftp']$ and $rl_config.trustedHosts=None$ the latter meaning no-restriction. You can modify these variables using one of the override files eg $reportlab_settings.py$ or $~/.reportlab_settings$. Or as comma separated strings in the environment variables $RL_trustedSchemes$ &amp; $RL_trustedHosts$. Note that the $trustedHosts$ values may contain <b>glob</b> wild cars so <i>*.reportlab.com</i> will match the obvious domains. <br/><span color="red"><b>*NB*</b></span> use of <i>trustedHosts</i> and or <i>trustedSchemes</i> may not control behaviour &amp; actions when $URI$ patterns are detected by the viewer application.""") heading3("The $&lt;u&gt;$ &amp; $&lt;strike&gt;$ tags") disc("""These tags can be used to carry out explicit underlineing or strikethroughs. These tags have attributes $width$, $offset$, $color$, $gap$ &amp; $kind$. The $kind$ attribute controls how many lines will be drawn (default $kind=1$) and when $kind>1$ the $gap$ attribute controls the disatnce between lines.""") heading3("The $&lt;nobr&gt;$ tag") disc("""If hyphenation is in operation the $&lt;nobr&gt;$ tag suppresses it so $&lt;nobr&gt;averylongwordthatwontbebroken&lt;/nobr&gt;$ won't be broken.""") heading3("Numbering Paragraphs and Lists") disc("""The $&lt;seq&gt;$ tag provides comprehensive support for numbering lists, chapter headings and so on. It acts as an interface to the $Sequencer$ class in ^reportlab.lib.sequencer^. These are used to number headings and figures throughout this document. You may create as many separate 'counters' as you wish, accessed with the $id$ attribute; these will be incremented by one each time they are accessed. The $seqreset$ tag resets a counter. If you want it to resume from a number other than 1, use the syntax &lt;seqreset id="mycounter" base="42"&gt;. Let's have a go:""") parabox2("""<seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>. Reset<seqreset id="spam"/>. <seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>.""", "Basic sequences") disc("""You can save specifying an ID by designating a counter ID as the <i>default</i> using the &lt;seqdefault id="Counter"&gt; tag; it will then be used whenever a counter ID is not specified. This saves some typing, especially when doing multi-level lists; you just change counter ID when stepping in or out a level.""") parabox2("""<seqdefault id="spam"/>Continued... <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>.""", "The default sequence") disc("""Finally, one can access multi-level sequences using a variation of Python string formatting and the $template$ attribute in a &lt;seq&gt; tags. This is used to do the captions in all of the figures, as well as the level two headings. The substring $%(counter)s$ extracts the current value of a counter without incrementing it; appending a plus sign as in $%(counter)s$ increments the counter. The figure captions use a pattern like the one below:""") parabox2("""Figure <seq template="%(Chapter)s-%(FigureNo+)s"/> - Multi-level templates""", "Multi-level templates") disc("""We cheated a little - the real document used 'Figure', but the text above uses 'FigureNo' - otherwise we would have messed up our numbering!""") heading2("Bullets and Paragraph Numbering") disc("""In addition to the three indent properties, some other parameters are needed to correctly handle bulleted and numbered lists. We discuss this here because you have now seen how to handle numbering. A paragraph may have an optional ^bulletText^ argument passed to its constructor; alternatively, bullet text may be placed in a $<![CDATA[<bullet>..</bullet>]]>$ tag at its head. This text will be drawn on the first line of the paragraph, with its x origin determined by the $bulletIndent$ attribute of the style, and in the font given in the $bulletFontName$ attribute. The "bullet" may be a single character such as (doh!) a bullet, or a fragment of text such as a number in some numbering sequence, or even a short title as used in a definition list. Fonts may offer various bullet characters but we suggest first trying the Unicode bullet ($&bull;$), which may be written as $&amp;bull;$, $&amp;#x2022;$ or (in utf8) $\\xe2\\x80\\xa2$):""") t=Table(*getAttrs(_bulletAttrMap)) t.setStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - &lt;bullet&gt; attributes &amp; synonyms""") disc("""The &lt;bullet&gt; tag is only allowed once in a given paragraph and its use overrides the implied bullet style and ^bulletText^ specified in the ^Paragraph^ creation. """) parabox("""<bullet>&bull;</bullet>this is a bullet point. Spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam """, styleSheet['Bullet'], 'Basic use of bullet points') disc("""Exactly the same technique is used for numbers, except that a sequence tag is used. It is also possible to put a multi-character string in the bullet; with a deep indent and bold bullet font, you can make a compact definition list.""")
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/ch5_paragraphs.py
0.651577
0.467089
ch5_paragraphs.py
pypi
from tools.docco.rl_doc_utils import * Appendix1("ReportLab Demos") disc("""In the subdirectories of $reportlab/demos$ there are a number of working examples showing almost all aspects of reportlab in use.""") heading2("""Odyssey""") disc(""" The three scripts odyssey.py, dodyssey.py and fodyssey.py all take the file odyssey.txt and produce PDF documents. The included odyssey.txt is short; a longer and more testing version can be found at ftp://ftp.reportlab.com/odyssey.full.zip. """) eg(""" Windows cd reportlab\\demos\\odyssey python odyssey.py start odyssey.pdf Linux cd reportlab/demos/odyssey python odyssey.py acrord odyssey.pdf """) disc("""Simple formatting is shown by the odyssey.py script. It runs quite fast, but all it does is gather the text and force it onto the canvas pages. It does no paragraph manipulation at all so you get to see the XML &lt; &amp; &gt; tags. """) disc("""The scripts fodyssey.py and dodyssey.py handle paragraph formatting so you get to see colour changes etc. Both scripts use the document template class and the dodyssey.py script shows the ability to do dual column layout and uses multiple page templates. """) heading2("""Standard Fonts and Colors""") disc("""In $reportlab/demos/stdfonts$ the script stdfonts.py can be used to illustrate ReportLab's standard fonts. Run the script using""") eg(""" cd reportlab\\demos\\stdfonts python stdfonts.py """) disc(""" to produce two PDF documents, StandardFonts_MacRoman.pdf &amp; StandardFonts_WinAnsi.pdf which show the two most common built in font encodings. """) disc("""The colortest.py script in $reportlab/demos/colors$ demonstrates the different ways in which reportlab can set up and use colors.""") disc("""Try running the script and viewing the output document, colortest.pdf. This shows different color spaces and a large selection of the colors which are named in the $reportlab.lib.colors$ module. """) heading2("""Py2pdf""") disc("""Dinu Gherman contributed this useful script which uses reportlab to produce nicely colorized PDF documents from Python scripts including bookmarks for classes, methods and functions. To get a nice version of the main script try""") eg(""" cd reportlab/demos/py2pdf python py2pdf.py py2pdf.py acrord py2pdf.pdf """) disc("""i.e. we used py2pdf to produce a nice version of py2pdf.py in the document with the same rootname and a .pdf extension. """) disc(""" The py2pdf.py script has many options which are beyond the scope of this simple introduction; consult the comments at the start of the script. """) heading2("Gadflypaper") disc(""" The Python script, gfe.py, in $reportlab/demos/gadflypaper$ uses an inline style of document preparation. The script almost entirely produced by Aaron Watters produces a document describing Aaron's $gadfly$ in memory database for Python. To generate the document use """) eg(""" cd reportlab\\gadflypaper python gfe.py start gfe.pdf """) disc(""" everything in the PDF document was produced by the script which is why this is an inline style of document production. So, to produce a header followed by some text the script uses functions $header$ and $p$ which take some text and append to a global story list. """) eg(''' header("Conclusion") p("""The revamped query engine design in Gadfly 2 supports .......... and integration.""") ''') heading2("""Pythonpoint""") disc("""Andy Robinson has refined the pythonpoint.py script (in $reportlab\\demos\\pythonpoint$) until it is a really useful script. It takes an input file containing an XML markup and uses an xmllib style parser to map the tags into PDF slides. When run in its own directory pythonpoint.py takes as a default input the file pythonpoint.xml and produces pythonpoint.pdf which is documentation for Pythonpoint! You can also see it in action with an older paper """) eg(""" cd reportlab\\demos\\pythonpoint python pythonpoint.py monterey.xml start monterey.pdf """) disc(""" Not only is pythonpoint self documenting, but it also demonstrates reportlab and PDF. It uses many features of reportlab (document templates, tables etc). Exotic features of PDF such as fadeins and bookmarks are also shown to good effect. The use of an XML document can be contrasted with the <i>inline</i> style of the gadflypaper demo; the content is completely separate from the formatting """)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/app_demos.py
0.613121
0.332825
app_demos.py
pypi
__version__='3.3.0' from tools.docco.rl_doc_utils import * from reportlab.graphics.shapes import * from reportlab.graphics.widgets import signsandsymbols heading2("Widgets") disc(""" We now describe widgets and how they relate to shapes. Using many examples it is shown how widgets make reusable graphics components. """) heading3("Shapes vs. Widgets") disc("""Up until now, Drawings have been 'pure data'. There is no code in them to actually do anything, except assist the programmer in checking and inspecting the drawing. In fact, that's the cornerstone of the whole concept and is what lets us achieve portability - a renderer only needs to implement the primitive shapes.""") disc("""We want to build reusable graphic objects, including a powerful chart library. To do this we need to reuse more tangible things than rectangles and circles. We should be able to write objects for other to reuse - arrows, gears, text boxes, UML diagram nodes, even fully fledged charts.""") disc(""" The Widget standard is a standard built on top of the shapes module. Anyone can write new widgets, and we can build up libraries of them. Widgets support the $getProperties()$ and $setProperties()$ methods, so you can inspect and modify as well as document them in a uniform way. """) bullet("A widget is a reusable shape ") bullet("""it can be initialized with no arguments when its $draw()$ method is called it creates a primitive Shape or a Group to represent itself""") bullet("""It can have any parameters you want, and they can drive the way it is drawn""") bullet("""it has a $demo()$ method which should return an attractively drawn example of itself in a 200x100 rectangle. This is the cornerstone of the automatic documentation tools. The $demo()$ method should also have a well written docstring, since that is printed too!""") disc("""Widgets run contrary to the idea that a drawing is just a bundle of shapes; surely they have their own code? The way they work is that a widget can convert itself to a group of primitive shapes. If some of its components are themselves widgets, they will get converted too. This happens automatically during rendering; the renderer will not see your chart widget, but just a collection of rectangles, lines and strings. You can also explicitly 'flatten out' a drawing, causing all widgets to be converted to primitives.""") heading3("Using a Widget") disc(""" Let's imagine a simple new widget. We will use a widget to draw a face, then show how it was implemented.""") eg(""" >>> from reportlab.lib import colors >>> from reportlab.graphics import shapes >>> from reportlab.graphics import widgetbase >>> from reportlab.graphics import renderPDF >>> d = shapes.Drawing(200, 100) >>> f = widgetbase.Face() >>> f.skinColor = colors.yellow >>> f.mood = "sad" >>> d.add(f) >>> renderPDF.drawToFile(d, 'face.pdf', 'A Face') """) from reportlab.graphics import widgetbase d = Drawing(200, 120) f = widgetbase.Face() f.x = 50 f.y = 10 f.skinColor = colors.yellow f.mood = "sad" d.add(f) draw(d, 'A sample widget') disc(""" Let's see what properties it has available, using the $setProperties()$ method we have seen earlier: """) eg(""" >>> f.dumpProperties() eyeColor = Color(0.00,0.00,1.00) mood = sad size = 80 skinColor = Color(1.00,1.00,0.00) x = 10 y = 10 >>> """) disc(""" One thing which seems strange about the above code is that we did not set the size or position when we made the face. This is a necessary trade-off to allow a uniform interface for constructing widgets and documenting them - they cannot require arguments in their $__init__()$ method. Instead, they are generally designed to fit in a 200 x 100 window, and you move or resize them by setting properties such as x, y, width and so on after creation. """) disc(""" In addition, a widget always provides a $demo()$ method. Simple ones like this always do something sensible before setting properties, but more complex ones like a chart would not have any data to plot. The documentation tool calls $demo()$ so that your fancy new chart class can create a drawing showing what it can do. """) disc(""" Here are a handful of simple widgets available in the module <i>signsandsymbols.py</i>: """) from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) draw(d, 'A few samples from signsandsymbols.py') disc(""" And this is the code needed to generate them as seen in the drawing above: """) eg(""" from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) """) heading3("Compound Widgets") disc("""Let's imagine a compound widget which draws two faces side by side. This is easy to build when you have the Face widget.""") eg(""" >>> tf = widgetbase.TwoFaces() >>> tf.faceOne.mood 'happy' >>> tf.faceTwo.mood 'sad' >>> tf.dumpProperties() faceOne.eyeColor = Color(0.00,0.00,1.00) faceOne.mood = happy faceOne.size = 80 faceOne.skinColor = None faceOne.x = 10 faceOne.y = 10 faceTwo.eyeColor = Color(0.00,0.00,1.00) faceTwo.mood = sad faceTwo.size = 80 faceTwo.skinColor = None faceTwo.x = 100 faceTwo.y = 10 >>> """) disc("""The attributes 'faceOne' and 'faceTwo' are deliberately exposed so you can get at them directly. There could also be top-level attributes, but there aren't in this case.""") heading3("Verifying Widgets") disc("""The widget designer decides the policy on verification, but by default they work like shapes - checking every assignment - if the designer has provided the checking information.""") heading3("Implementing Widgets") disc("""We tried to make it as easy to implement widgets as possible. Here's the code for a Face widget which does not do any type checking:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes, mouth and nose.\"\"\" def __init__(self): self.x = 10 self.y = 10 self.size = 80 self.skinColor = None self.eyeColor = colors.blue self.mood = 'happy' def draw(self): s = self.size # abbreviate as we will use this a lot g = shapes.Group() g.transform = [1,0,0,1,self.x, self.y] # background g.add(shapes.Circle(s * 0.5, s * 0.5, s * 0.5, fillColor=self.skinColor)) # CODE OMITTED TO MAKE MORE SHAPES return g """) disc("""We left out all the code to draw the shapes in this document, but you can find it in the distribution in $widgetbase.py$.""") disc("""By default, any attribute without a leading underscore is returned by setProperties. This is a deliberate policy to encourage consistent coding conventions.""") disc("""Once your widget works, you probably want to add support for verification. This involves adding a dictionary to the class called $_verifyMap$, which map from attribute names to 'checking functions'. The $widgetbase.py$ module defines a bunch of checking functions with names like $isNumber$, $isListOfShapes$ and so on. You can also simply use $None$, which means that the attribute must be present but can have any type. And you can and should write your own checking functions. We want to restrict the "mood" custom attribute to the values "happy", "sad" or "ok". So we do this:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes. It exposes a couple of properties to configure itself and hides all other details\"\"\" def checkMood(moodName): return (moodName in ('happy','sad','ok')) _verifyMap = { 'x': shapes.isNumber, 'y': shapes.isNumber, 'size': shapes.isNumber, 'skinColor':shapes.isColorOrNone, 'eyeColor': shapes.isColorOrNone, 'mood': checkMood } """) disc("""This checking will be performed on every attribute assignment; or, if $config.shapeChecking$ is off, whenever you call $myFace.verify()$.""") heading3("Documenting Widgets") disc(""" We are working on a generic tool to document any Python package or module; this is already checked into ReportLab and will be used to generate a reference for the ReportLab package. When it encounters widgets, it adds extra sections to the manual including:""") bullet("the doc string for your widget class ") bullet("the code snippet from your <i>demo()</i> method, so people can see how to use it") bullet("the drawing produced by the <i>demo()</i> method ") bullet("the property dump for the widget in the drawing. ") disc(""" This tool will mean that we can have guaranteed up-to-date documentation on our widgets and charts, both on the web site and in print; and that you can do the same for your own widgets, too! """) heading3("Widget Design Strategies") disc("""We could not come up with a consistent architecture for designing widgets, so we are leaving that problem to the authors! If you do not like the default verification strategy, or the way $setProperties/getProperties$ works, you can override them yourself.""") disc("""For simple widgets it is recommended that you do what we did above: select non-overlapping properties, initialize every property on $__init__$ and construct everything when $draw()$ is called. You can instead have $__setattr__$ hooks and have things updated when certain attributes are set. Consider a pie chart. If you want to expose the individual slices, you might write code like this:""") eg(""" from reportlab.graphics.charts import piecharts pc = piecharts.Pie() pc.defaultColors = [navy, blue, skyblue] #used in rotation pc.data = [10,30,50,25] pc.slices[7].strokeWidth = 5 """) #removed 'pc.backColor = yellow' from above code example disc("""The last line is problematic as we have only created four slices - in fact we might not have created them yet. Does $pc.slices[7]$ raise an error? Is it a prescription for what should happen if a seventh wedge is defined, used to override the default settings? We dump this problem squarely on the widget author for now, and recommend that you get a simple one working before exposing 'child objects' whose existence depends on other properties' values :-)""") disc("""We also discussed rules by which parent widgets could pass properties to their children. There seems to be a general desire for a global way to say that 'all slices get their lineWidth from the lineWidth of their parent' without a lot of repetitive coding. We do not have a universal solution, so again leave that to widget authors. We hope people will experiment with push-down, pull-down and pattern-matching approaches and come up with something nice. In the meantime, we certainly can write monolithic chart widgets which work like the ones in, say, Visual Basic and Delphi.""") disc("""For now have a look at the following sample code using an early version of a pie chart widget and the output it generates:""") eg(""" from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') """) # Hack to force a new paragraph before the todo() :-( disc("") from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') draw(d, 'Some sample Pies')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/graph_widgets.py
0.767603
0.555978
graph_widgets.py
pypi
from tools.docco.rl_doc_utils import * heading1("Writing your own $Flowable$ Objects") disc(""" Flowables are intended to be an open standard for creating reusable report content, and you can easily create your own objects. We hope that over time we will build up a library of contributions, giving reportlab users a rich selection of charts, graphics and other "report widgets" they can use in their own reports. This section shows you how to create your own flowables.""") todo("""we should put the Figure class in the standard library, as it is a very useful base.""") heading2("A very simple $Flowable$") disc(""" Recall the $hand$ function from the $pdfgen$ section of this user guide which generated a drawing of a hand as a closed figure composed from Bezier curves. """) illust(examples.hand, "a hand") disc(""" To embed this or any other drawing in a Platypus flowable we must define a subclass of $Flowable$ with at least a $wrap$ method and a $draw$ method. """) eg(examples.testhandannotation) disc(""" The $wrap$ method must provide the size of the drawing -- it is used by the Platypus mainloop to decide whether this element fits in the space remaining on the current frame. The $draw$ method performs the drawing of the object after the Platypus mainloop has translated the $(0,0)$ origin to an appropriate location in an appropriate frame. """) disc(""" Below are some example uses of the $HandAnnotation$ flowable. """) from reportlab.lib.colors import blue, pink, yellow, cyan, brown from reportlab.lib.units import inch handnote() disc("""The default.""") handnote(size=inch) disc("""Just one inch high.""") handnote(xoffset=3*inch, size=inch, strokecolor=blue, fillcolor=cyan) disc("""One inch high and shifted to the left with blue and cyan.""") heading2("Modifying a Built in $Flowable$") disc("""To modify an existing flowable, you should create a derived class and override the methods you need to change to get the desired behaviour""") disc("""As an example to create a rotated image you need to override the wrap and draw methods of the existing Image class""") import os from reportlab.platypus import * I = '../images/replogo.gif' EmbeddedCode(""" class RotatedImage(Image): def wrap(self,availWidth,availHeight): h, w = Image.wrap(self,availHeight,availWidth) return w, h def draw(self): self.canv.rotate(90) Image.draw(self) I = RotatedImage('%s') I.hAlign = 'CENTER' """ % I,'I')
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/ch7_custom.py
0.63114
0.513851
ch7_custom.py
pypi
from tools.docco.rl_doc_utils import * heading1("Exposing PDF Special Capabilities") disc("""PDF provides a number of features to make electronic document viewing more efficient and comfortable, and our library exposes a number of these.""") heading2("Forms") disc("""The Form feature lets you create a block of graphics and text once near the start of a PDF file, and then simply refer to it on subsequent pages. If you are dealing with a run of 5000 repetitive business forms - for example, one-page invoices or payslips - you only need to store the backdrop once and simply draw the changing text on each page. Used correctly, forms can dramatically cut file size and production time, and apparently even speed things up on the printer. """) disc("""Forms do not need to refer to a whole page; anything which might be repeated often should be placed in a form.""") disc("""The example below shows the basic sequence used. A real program would probably define the forms up front and refer to them from another location.""") eg(examples.testforms) heading2("Links and Destinations") disc("""PDF supports internal hyperlinks. There is a very wide range of link types, destination types and events which can be triggered by a click. At the moment we just support the basic ability to jump from one part of a document to another, and to control the zoom level of the window after the jump. The bookmarkPage method defines a destination that is the endpoint of a jump.""") #todo("code example here...") eg(""" canvas.bookmarkPage(name, fit="Fit", left=None, top=None, bottom=None, right=None, zoom=None ) """) disc(""" By default the $bookmarkPage$ method defines the page itself as the destination. After jumping to an endpoint defined by bookmarkPage, the PDF browser will display the whole page, scaling it to fit the screen:""") eg("""canvas.bookmarkPage(name)""") disc("""The $bookmarkPage$ method can be instructed to display the page in a number of different ways by providing a $fit$ parameter.""") eg("") t = Table([ ['fit','Parameters Required','Meaning'], ['Fit',None,'Entire page fits in window (the default)'], ['FitH','top','Top coord at top of window, width scaled to fit'], ['FitV','left','Left coord at left of window, height scaled to fit'], ['FitR','left bottom right top','Scale window to fit the specified rectangle'], ['XYZ','left top zoom','Fine grained control. If you omit a parameter\nthe PDF browser interprets it as "leave as is"'] ]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Required attributes for different fit types""") disc(""" Note : $fit$ settings are case-sensitive so $fit="FIT"$ is invalid """) disc(""" Sometimes you want the destination of a jump to be some part of a page. The $FitR$ fit allows you to identify a particular rectangle, scaling the area to fit the entire page. """) disc(""" To set the display to a particular x and y coordinate of the page and to control the zoom directly use fit="XYZ". """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200) """) disc(""" This destination is at the leftmost of the page with the top of the screen at position 200. Because $zoom$ was not set the zoom remains at whatever the user had it set to. """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200,zoom=2) """) disc("""This time zoom is set to expand the page 2X its normal size.""") disc(""" Note : Both $XYZ$ and $FitR$ fit types require that their positional parameters ($top, bottom, left, right$) be specified in terms of the default user space. They ignore any geometric transform in effect in the canvas graphic state. """) pencilnote() disc(""" <i>Note:</i> Two previous bookmark methods are supported but deprecated now that bookmarkPage is so general. These are $bookmarkHorizontalAbsolute$ and $bookmarkHorizontal$. """) heading3("Defining internal links") eg(""" canvas.linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None, thickness=0, color=None, dashArray=None, **kw) """) disc(""" The $linkAbsolute$ method defines a starting point for a jump. When the user is browsing the generated document using a dynamic viewer (such as Acrobat Reader) when the mouse is clicked when the pointer is within the rectangle specified by $Rect$ the viewer will jump to the endpoint associated with $destinationname$. As in the case with $bookmarkHorizontalAbsolute$ the rectangle $Rect$ must be specified in terms of the default user space. The $contents$ parameter specifies a chunk of text which displays in the viewer if the user left-clicks on the region. """) disc(""" The rectangle $Rect$ must be specified in terms of a tuple ^(x1,y1,x2,y2)^ identifying the lower left and upper right points of the rectangle in default user space. """) disc(""" For example the code """) eg(""" canvas.bookmarkPage("Meaning_of_life") """) disc(""" defines a location as the whole of the current page with the identifier $Meaning_of_life$. To create a rectangular link to it while drawing a possibly different page, we would use this code: """) eg(""" canvas.linkAbsolute("Find the Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch)) """) disc(""" By default during interactive viewing a rectangle appears around the link. Use the keyword argument $Border='[0 0 0]'$ to suppress the visible rectangle around the during viewing link. For example """) eg(""" canvas.linkAbsolute("Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch), Border='[0 0 0]') """) disc("""The $thickness$, $color$ and $dashArray$ arguments may be used alternately to specify a border if no Border argument is specified. If Border is specified it must be either a string representation of a PDF array or a $PDFArray$ (see the pdfdoc module). The $color$ argument (which should be a $Color$ instance) is equivalent to a keyword argument $C$ which should resolve to a PDF color definition (Normally a three entry PDF array). """) disc("""The $canvas.linkRect$ method is similar in intent to the $linkAbsolute$ method, but has an extra argument $relative=1$ so is intended to obey the local userspace transformation.""") heading2("Outline Trees") disc("""Acrobat Reader has a navigation page which can hold a document outline; it should normally be visible when you open this guide. We provide some simple methods to add outline entries. Typically, a program to make a document (such as this user guide) will call the method $canvas.addOutlineEntry(^self, title, key, level=0, closed=None^)$ as it reaches each heading in the document. """) disc("""^title^ is the caption which will be displayed in the left pane. The ^key^ must be a string which is unique within the document and which names a bookmark, as with the hyperlinks. The ^level^ is zero - the uppermost level - unless otherwise specified, and it is an error to go down more than one level at a time (for example to follow a level 0 heading by a level 2 heading). Finally, the ^closed^ argument specifies whether the node in the outline pane is closed or opened by default.""") disc("""The snippet below is taken from the document template that formats this user guide. A central processor looks at each paragraph in turn, and makes a new outline entry when a new chapter occurs, taking the chapter heading text as the caption text. The key is obtained from the chapter number (not shown here), so Chapter 2 has the key 'ch2'. The bookmark to which the outline entry points aims at the whole page, but it could as easily have been an individual paragraph. """) eg(""" #abridged code from our document template if paragraph.style == 'Heading1': self.chapter = paragraph.getPlainText() key = 'ch%d' % self.chapterNo self.canv.bookmarkPage(key) self.canv.addOutlineEntry(paragraph.getPlainText(), key, 0, 0) """) heading2("Page Transition Effects") eg(""" canvas.setPageTransition(self, effectname=None, duration=1, direction=0,dimension='H',motion='I') """) disc(""" The $setPageTransition$ method specifies how one page will be replaced with the next. By setting the page transition effect to "dissolve" for example the current page will appear to melt away when it is replaced by the next page during interactive viewing. These effects are useful in spicing up slide presentations, among other places. Please see the reference manual for more detail on how to use this method. """) heading2("Internal File Annotations") eg(""" canvas.setAuthor(name) canvas.setTitle(title) canvas.setSubject(subj) """) disc(""" These methods have no automatically seen visible effect on the document. They add internal annotations to the document. These annotations can be viewed using the "Document Info" menu item of the browser and they also can be used as a simple standard way of providing basic information about the document to archiving software which need not parse the entire file. To find the annotations view the $*.pdf$ output file using a standard text editor (such as $notepad$ on MS/Windows or $vi$ or $emacs$ on unix) and look for the string $/Author$ in the file contents. """) eg(examples.testannotations) disc(""" If you want the subject, title, and author to automatically display in the document when viewed and printed you must paint them onto the document like any other text. """) illust(examples.annotations, "Setting document internal annotations") heading2("Encryption") heading3("About encrypting PDF files") disc(""" Adobe's PDF standard allows you to do three related things to a PDF file when you encrypt it: """) bullet("""Apply password protection to it, so a user must supply a valid password before being able to read it, """) bullet("""Encrypt the contents of the file to make it useless until it is decrypted, and """) bullet("""Control whether the user can print, copy and paste or modify the document while viewing it. """) disc(""" The PDF security handler allows two different passwords to be specified for a document: """) bullet("""The 'owner' password (aka the 'security password' or 'master password') """) bullet("""The 'user' password (aka the 'open password') """) disc(""" When a user supplies either one of these passwords, the PDF file will be opened, decrypted and displayed on screen. """) disc(""" If the owner password is supplied, then the file is opened with full control - you can do anything to it, including changing the security settings and passwords, or re-encrypting it with a new password. """) disc(""" If the user password was the one that was supplied, you open it up in a more restricted mode. The restrictions were put in place when the file was encrypted, and will either allow or deny the user permission to do the following: """) bullet(""" Modifying the document's contents """) bullet(""" Copying text and graphics from the document """) bullet(""" Adding or modifying text annotations and interactive form fields """) bullet(""" Printing the document """) disc(""" Note that all password protected PDF files are encrypted, but not all encrypted PDFs are password protected. If a document's user password is an empty string, there will be no prompt for the password when the file is opened. If you only secure a document with the owner password, there will also not be a prompt for the password when you open the file. If the owner and user passwords are set to the same string when encrypting the PDF file, the document will always open with the user access privileges. This means that it is possible to create a file which, for example, is impossible for anyone to print out, even the person who created it. """) t = Table([ ['Owner Password \nset?','User Password \nset?','Result'], ['Y','-','No password required when opening file. \nRestrictions apply to everyone.'], ['-','Y','User password required when opening file. \nRestrictions apply to everyone.'], ['Y','Y','A password required when opening file. \nRestrictions apply only if user password supplied.'], ],[90, 90, 260]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,0),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) disc(""" When a PDF file is encrypted, encryption is applied to all the strings and streams in the file. This prevents people who don't have the password from simply removing the password from the PDF file to gain access to it - it renders the file useless unless you actually have the password. """) disc(""" PDF's standard encryption methods use the MD5 message digest algorithm (as described in RFC 1321, The MD5 Message-Digest Algorithm) and an encryption algorithm known as RC4. RC4 is a symmetric stream cipher - the same algorithm is used both for encryption and decryption, and the algorithm does not change the length of the data. """) heading3("How To Use Encryption") disc(""" Documents can be encrypted by passing an argument to the canvas object. """) disc(""" If the argument is a string object, it is used as the User password to the PDF. """) disc(""" The argument can also be an instance of the class $reportlab.lib.pdfencrypt.StandardEncryption$, which allows more finegrained control over encryption settings. """) disc(""" The $StandardEncryption$ constructor takes the following arguments: """) eg(""" def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """) disc(""" The $userPassword$ and $ownerPassword$ parameters set the relevant password on the encrypted PDF. """) disc(""" The boolean flags $canPrint$, $canModify$, $canCopy$, $canAnnotate$ determine wether a user can perform the corresponding actions on the PDF when only a user password has been supplied. """) disc(""" If the user supplies the owner password while opening the PDF, all actions can be performed regardless of the flags. """) heading3("Example") disc(""" To create a document named hello.pdf with a user password of 'rptlab' on which printing is not allowed, use the following code: """) eg(""" from reportlab.pdfgen import canvas from reportlab.lib import pdfencrypt enc=pdfencrypt.StandardEncryption("rptlab",canPrint=0) def hello(c): c.drawString(100,100,"Hello World") c = canvas.Canvas("hello.pdf",encrypt=enc) hello(c) c.showPage() c.save() """) heading2("Interactive Forms") heading3("Overview of Interactive Forms") disc("""The PDF standard allows for various kinds of interactive elements, the ReportLab toolkit currently supports only a fraction of the possibilities and should be considered a work in progress. At present we allow choices with <i>checkbox</i>, <i>radio</i>, <i>choice</i> &amp; <i>listbox</i> widgets; text values can be entered with a <i>textfield</i> widget. All the widgets are created by calling methods on the <i>canvas.acroform</i> property.""" ) heading3("Example") disc("This shows the basic mechanism of creating an interactive element on the current page.") eg(""" canvas.acroform.checkbox( name='CB0', tooltip='Field CB0', checked=True, x=72,y=72+4*36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) """) alStyle=TableStyle([ ('SPAN',(0,0),(-1,0)), ('FONT',(0,0),(-1,0),'Helvetica-Bold',10,12), ('FONT',(0,1),(-1,1),'Helvetica-BoldOblique',8,9.6), ('FONT',(0,2),(0,-1),'Helvetica-Bold',7,8.4), ('FONT',(1,2),(1,-1),'Helvetica',7,8.4), ('FONT',(2,2),(2,-1),'Helvetica-Oblique',7,8.4), ('ALIGN',(0,0),(-1,0),'CENTER'), ('ALIGN',(1,1),(1,1),'CENTER'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) disc("""<b>NB</b> note that the <i>acroform</i> canvas property is created automatically on demand and that there is only one form allowd in a document.""") heading3("Checkbox Usage") disc("""The <i>canvas.acroform.checkbox</i> method creates a <i>checkbox</i> widget on the current page. The value of the checkbox is either <b>YES</b> or <b>OFF</b>. The arguments are""") t = Table([ ['canvas.acroform.checkbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the parameter's name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["checked","if True the checkbox is initially checked","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'required'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Radio Usage") disc("""The <i>canvas.acroform.radio</i> method creates a <i>radio</i> widget on the current page. The value of the radio is the value of the radio group's selected value or <b>OFF</b> if none are selected. The arguments are""") t = Table([ ['canvas.acroform.radio parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","the radio's group name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["selected","if True this radio is the selected one in its group","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'noToggleToOff required radio'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Listbox Usage") disc("""The <i>canvas.acroform.listbox</i> method creates a <i>listbox</i> widget on the current page. The listbox contains a list of options one or more of which (depending on fieldFlags) may be selected. """) t = Table([ ['canvas.acroform.listbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Choice Usage") disc("""The <i>canvas.acroform.choice</i> method creates a <i>dropdown</i> widget on the current page. The dropdown contains a list of options one or more of which (depending on fieldFlags) may be selected. If you add <i>edit</i> to the <i>fieldFlags</i> then the result may be edited. """) t = Table([ ['canvas.acroform.choice parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'combo'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ["maxlen ","None or maximum length of the widget value","None"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Textfield Usage") disc("""The <i>canvas.acroform.textfield</i> method creates a <i>textfield</i> entry widget on the current page. The textfield may be edited to change tha value of the widget """) t = Table([ ['canvas.acroform.textfield parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","Value of the text field","''"], ["maxlen ","None or maximum length of the widget value","100"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Button styles") disc("""The button style argument indicates what style of symbol should appear in the button when it is selected. There are several choices""") eg(""" check cross circle star diamond """) disc("""note that the document renderer can make some of these symbols wrong for their intended application. Acrobat reader prefers to use its own rendering on top of what the specification says should be shown (especially when the forms hihlighting features are used""") heading3("Widget shape") disc("""The shape argument describes how the outline of the checkbox or radio widget should appear you can use""") eg(""" circle square """) disc("""The renderer may make its own decisions about how the widget should look; so Acrobat Reader prefers circular outlines for radios.""") heading3("Border style") disc("""The borderStyle argument changes the 3D appearance of the widget on the page alternatives are""") eg(""" solid dashed inset bevelled underlined """) heading3("fieldFlags Argument") disc("""The fieldFlags arguments can be an integer or a string containing blank separate tokens the values are shown in the table below. For more information consult the PDF specification.""") t = Table([ ['Field Flag Tokens and values','',''], ['Token','Meaning','Value'], ["readOnly","The widget is read only","1<<0"], ["required","the widget is required","1<<1"], ["noExport","don't export the widget value","1<<2"], ["noToggleToOff","radios one only must be on","1<<14"], ["radio","added by the radio method","1<<15"], ["pushButton","if the button is a push button","1<<16"], ["radiosInUnison","radios with the same value toggle together","1<<25"], ["multiline","for multiline text widget","1<<12"], ["password","password textfield","1<<13"], ["fileSelect","file selection widget","1<<20"], #1.4 ["doNotSpellCheck","as it says","1<<22"], #1.4 ["doNotScroll","text fields do not scroll","1<<23"], #1.4 ["comb","make a comb style text based on the maxlen value","1<<24"], #1.5 ["richText","if rich text is used","1<<25"], #1.5 ["combo","for choice fields","1<<17"], ["edit","if the choice is editable","1<<18"], ["sort","if the values should be sorted","1<<19"], ["multiSelect","if the choice allows multi-select","1<<21"], #1.4 ["commitOnSelChange","not used by reportlab","1<<26"], #1.5 ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("annotationFlags Argument") disc("""PDF widgets are annotations and have annotation properties these are shown in the table below""") t = Table([ ['Annotation Flag Tokens and values','',''], ['Token','Meaning','Value'], ["invisible","The widget is not shown","1<<0"], ["hidden","The widget is hidden","1<<1"], ["print","The widget will print","1<<2"], ["nozoom","The annotation will notscale with the rendered page","1<<3"], ["norotate","The widget won't rotate with the page","1<<4"], ["noview","Don't render the widget","1<<5"], ["readonly","Widget cannot be interacted with","1<<6"], ["locked","The widget cannot be changed","1<<7"], #1.4 ["togglenoview","Teh widget may be viewed after some events","1<<8"], #1.9 ["lockedcontents","The contents of the widget are fixed","1<<9"], #1.7 ],[90, 260, 90],style=alStyle) getStory().append(t)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/ch3_pdffeatures.py
0.632389
0.535281
ch3_pdffeatures.py
pypi
from tools.docco.rl_doc_utils import * #####################################################################################################3 heading1("PLATYPUS - Page Layout and Typography Using Scripts") heading2("Design Goals") disc(""" Platypus stands for &quot;Page Layout and Typography Using Scripts&quot;. It is a high level page layout library which lets you programmatically create complex documents with a minimum of effort. """) disc(""" The design of Platypus seeks to separate "high level" layout decisions from the document content as much as possible. Thus, for example, paragraphs are constructed using paragraph styles and pages are constructed using page templates with the intention that hundreds of documents with thousands of pages can be reformatted to different style specifications with the modifications of a few lines in a single shared file which contains the paragraph styles and page layout specifications. """) disc(""" The overall design of Platypus can be thought of has having several layers, top down, these are""") disc("<b>$DocTemplates$</b> the outermost container for the document;") disc("<b>$PageTemplates$</b> specifications for layouts of pages of various kinds;") disc("<b>$Frames$</b> specifications of regions in pages that can contain flowing text or graphics.") disc("""<b>$Flowables$</b> text or graphic elements that should be "flowed into the document (i.e. things like images, paragraphs and tables, but not things like page footers or fixed page graphics).""") disc("""<b>$pdfgen.Canvas$</b> the lowest level which ultimately receives the painting of the document from the other layers.""") illust(examples.doctemplateillustration, "Illustration of DocTemplate structure") disc(""" The illustration above graphically illustrates the concepts of $DocTemplates$, $PageTemplates$ and $Flowables$. It is deceptive, however, because each of the $PageTemplates$ actually may specify the format for any number of pages (not just one as might be inferred from the diagram). """) disc(""" $DocTemplates$ contain one or more $PageTemplates$ each of which contain one or more $Frames$. $Flowables$ are things which can be <i>flowed</i> into a $Frame$ e.g. a $Paragraph$ or a $Table$. """) disc(""" To use platypus you create a document from a $DocTemplate$ class and pass a list of $Flowable$s to its $build$ method. The document $build$ method knows how to process the list of flowables into something reasonable. """) disc(""" Internally the $DocTemplate$ class implements page layout and formatting using various events. Each of the events has a corresponding handler method called $handle_XXX$ where $XXX$ is the event name. A typical event is $frameBegin$ which occurs when the machinery begins to use a frame for the first time. """) disc(""" A Platypus story consists of a sequence of basic elements called $Flowables$ and these elements drive the data driven Platypus formatting engine. To modify the behavior of the engine a special kind of flowable, $ActionFlowables$, tell the layout engine to, for example, skip to the next column or change to another $PageTemplate$. """) heading2("""Getting started""") disc("""Consider the following code sequence which provides a very simple "hello world" example for Platypus.""") eg(examples.platypussetup) disc("""First we import some constructors, some paragraph styles and other conveniences from other modules.""") eg(examples.platypusfirstpage) disc("""We define the fixed features of the first page of the document with the function above.""") eg(examples.platypusnextpage) disc("""Since we want pages after the first to look different from the first we define an alternate layout for the fixed features of the other pages. Note that the two functions above use the $pdfgen$ level canvas operations to paint the annotations for the pages. """) eg(examples.platypusgo) disc(""" Finally, we create a story and build the document. Note that we are using a "canned" document template here which comes pre-built with page templates. We are also using a pre-built paragraph style. We are only using two types of flowables here -- $Spacers$ and $Paragraphs$. The first $Spacer$ ensures that the Paragraphs skip past the title string. """) disc(""" To see the output of this example program run the module $tools/docco/examples.py$ (from the ReportLab $source$ distribution) as a "top level script". The script interpretation $python examples.py$ will generate the Platypus output $phello.pdf$. """) heading2("$Flowables$") disc(""" $Flowables$ are things which can be drawn and which have $wrap$, $draw$ and perhaps $split$ methods. $Flowable$ is an abstract base class for things to be drawn and an instance knows its size and draws in its own coordinate system (this requires the base API to provide an absolute coordinate system when the $Flowable.draw$ method is called). To get an instance use $f=Flowable()$. """) disc(""" It should be noted that the $Flowable$ class is an <i>abstract</i> class and is normally only used as a base class. """) k=startKeep() disc(""" To illustrate the general way in which $Flowables$ are used we show how a derived class $Paragraph$ is used and drawn on a canvas. $Paragraphs$ are so important they will get a whole chapter to themselves. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph from reportlab.pdfgen.canvas import Canvas styleSheet = getSampleStyleSheet() style = styleSheet['BodyText'] P=Paragraph('This is a very silly example',style) canv = Canvas('doc.pdf') aW = 460 # available width and height aH = 800 w,h = P.wrap(aW, aH) # find required space if w<=aW and h<=aH: P.drawOn(canv,0,aH) aH = aH - h # reduce the available height canv.save() else: raise ValueError, "Not enough room" """) endKeep(k) heading3("$Flowable$ User Methods") eg(""" Flowable.draw() """) disc("""This will be called to ask the flowable to actually render itself. The $Flowable$ class does not implement $draw$. The calling code should ensure that the flowable has an attribute $canv$ which is the $pdfgen.Canvas$ which should be drawn to an that the $Canvas$ is in an appropriate state (as regards translations rotations, etc). Normally this method will only be called internally by the $drawOn$ method. Derived classes must implement this method. """) eg(""" Flowable.drawOn(canvas,x,y) """) disc(""" This is the method which controlling programs use to render the flowable to a particular canvas. It handles the translation to the canvas coordinate (<i>x</i>,<i>y</i>) and ensuring that the flowable has a $canv$ attribute so that the $draw$ method (which is not implemented in the base class) can render in an absolute coordinate frame. """) eg(""" Flowable.wrap(availWidth, availHeight) """) disc("""This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.""") eg(""" Flowable.split(self, availWidth, availheight): """) disc("""This will be called by more sophisticated frames when wrap fails. Stupid flowables should return [] meaning that they are unable to split. Clever flowables should split themselves and return a list of flowables. It is up to the client code to ensure that repeated attempts to split are avoided. If the space is sufficient the split method should return [self]. Otherwise the flowable should rearrange itself and return a list $[f0,...]$ of flowables which will be considered in order. The implemented split method should avoid changing $self$ as this will allow sophisticated layout mechanisms to do multiple passes over a list of flowables. """) heading2("Guidelines for flowable positioning") disc("""Two methods, which by default return zero, provide guidance on vertical spacing of flowables: """) eg(""" Flowable.getSpaceAfter(self): Flowable.getSpaceBefore(self): """) disc("""These methods return how much space should follow or precede the flowable. The space doesn't belong to the flowable itself i.e. the flowable's $draw$ method shouldn't consider it when rendering. Controlling programs will use the values returned in determining how much space is required by a particular flowable in context. """) disc("""All flowables have an $hAlign$ property: $('LEFT', 'RIGHT', 'CENTER' or 'CENTRE')$. For paragraphs, which fill the full width of the frame, this has no effect. For tables, images or other objects which are less than the width of the frame, this determines their horizontal placement. """) disc("""The chapters which follow will cover the most important specific types of flowables: Paragraphs and Tables.""") heading2("Frames") disc(""" $Frames$ are active containers which are themselves contained in $PageTemplates$. $Frames$ have a location and size and maintain a concept of remaining drawable space. The command """) eg(""" Frame(x1, y1, width,height, leftPadding=6, bottomPadding=6, rightPadding=6, topPadding=6, id=None, showBoundary=0) """) disc("""creates a $Frame$ instance with lower left hand corner at coordinate $(x1,y1)$ (relative to the canvas at use time) and with dimensions $width$ x $height$. The $Padding$ arguments are positive quantities used to reduce the space available for drawing. The $id$ argument is an identifier for use at runtime e.g. 'LeftColumn' or 'RightColumn' etc. If the $showBoundary$ argument is non-zero then the boundary of the frame will get drawn at run time (this is useful sometimes). """) heading3("$Frame$ User Methods") eg(""" Frame.addFromList(drawlist, canvas) """) disc("""consumes $Flowables$ from the front of $drawlist$ until the frame is full. If it cannot fit one object, raises an exception.""") eg(""" Frame.split(flowable,canv) """) disc('''Asks the flowable to split using up the available space and return the list of flowables. ''') eg(""" Frame.drawBoundary(canvas) """) disc("draws the frame boundary as a rectangle (primarily for debugging).") heading3("Using $Frames$") disc(""" $Frames$ can be used directly with canvases and flowables to create documents. The $Frame.addFromList$ method handles the $wrap$ &amp; $drawOn$ calls for you. You don't need all of the Platypus machinery to get something useful into PDF. """) eg(""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import Paragraph, Frame styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) c = Canvas('mydoc.pdf') f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) c.save() """) heading2("Documents and Templates") disc(""" The $BaseDocTemplate$ class implements the basic machinery for document formatting. An instance of the class contains a list of one or more $PageTemplates$ that can be used to describe the layout of information on a single page. The $build$ method can be used to process a list of $Flowables$ to produce a <b>PDF</b> document. """) CPage(3.0) heading3("The $BaseDocTemplate$ class") eg(""" BaseDocTemplate(self, filename, pagesize=defaultPageSize, pageTemplates=[], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=1, title=None, author=None, _pageBreakQuick=1, encrypt=None) """) disc(""" creates a document template suitable for creating a basic document. It comes with quite a lot of internal machinery, but no default page templates. The required $filename$ can be a string, the name of a file to receive the created <b>PDF</b> document; alternatively it can be an object which has a $write$ method such as a $BytesIO$ or $file$ or $socket$. """) disc(""" The allowed arguments should be self explanatory, but $showBoundary$ controls whether or not $Frame$ boundaries are drawn which can be useful for debugging purposes. The $allowSplitting$ argument determines whether the builtin methods should try to <i>split</i> individual $Flowables$ across $Frames$. The $_pageBreakQuick$ argument determines whether an attempt to do a page break should try to end all the frames on the page or not, before ending the page. The encrypt argument determines wether or not and how the document is encrypted. By default, the document is not encrypted. If $encrypt$ is a string object, it is used as the user password for the pdf. If $encrypt$ is an instance of $reportlab.lib.pdfencrypt.StandardEncryption$, this object is used to encrypt the pdf. This allows more finegrained control over the encryption settings. """) heading4("User $BaseDocTemplate$ Methods") disc("""These are of direct interest to client programmers in that they are normally expected to be used. """) eg(""" BaseDocTemplate.addPageTemplates(self,pageTemplates) """) disc(""" This method is used to add one or a list of $PageTemplates$ to an existing documents. """) eg(""" BaseDocTemplate.build(self, flowables, filename=None, canvasmaker=canvas.Canvas) """) disc(""" This is the main method which is of interest to the application programmer. Assuming that the document instance is correctly set up the $build$ method takes the <i>story</i> in the shape of the list of flowables (the $flowables$ argument) and loops through the list forcing the flowables one at a time through the formatting machinery. Effectively this causes the $BaseDocTemplate$ instance to issue calls to the instance $handle_XXX$ methods to process the various events. """) heading4("User Virtual $BaseDocTemplate$ Methods") disc(""" These have no semantics at all in the base class. They are intended as pure virtual hooks into the layout machinery. Creators of immediately derived classes can override these without worrying about affecting the properties of the layout engine. """) eg(""" BaseDocTemplate.afterInit(self) """) disc(""" This is called after initialisation of the base class; a derived class could overide the method to add default $PageTemplates$. """) eg(""" BaseDocTemplate.afterPage(self) """) disc("""This is called after page processing, and immediately after the afterDrawPage method of the current page template. A derived class could use this to do things which are dependent on information in the page such as the first and last word on the page of a dictionary. """) eg(""" BaseDocTemplate.beforeDocument(self) """) disc("""This is called before any processing is done on the document, but after the processing machinery is ready. It can therefore be used to do things to the instance\'s $pdfgen.canvas$ and the like. """) eg(""" BaseDocTemplate.beforePage(self) """) disc("""This is called at the beginning of page processing, and immediately before the beforeDrawPage method of the current page template. It could be used to reset page specific information holders.""") eg(""" BaseDocTemplate.filterFlowables(self,flowables) """) disc("""This is called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns immediately. """) eg(""" BaseDocTemplate.afterFlowable(self, flowable) """) disc("""Called after a flowable has been rendered. An interested class could use this hook to gather information about what information is present on a particular page or frame.""") heading4("$BaseDocTemplate$ Event handler Methods") disc(""" These methods constitute the greater part of the layout engine. Programmers shouldn't have to call or override these methods directly unless they are trying to modify the layout engine. Of course, the experienced programmer who wants to intervene at a particular event, $XXX$, which does not correspond to one of the virtual methods can always override and call the base method from the drived class version. We make this easy by providing a base class synonym for each of the handler methods with the same name prefixed by an underscore '_'. """) eg(""" def handle_pageBegin(self): doStuff() BaseDocTemplate.handle_pageBegin(self) doMoreStuff() #using the synonym def handle_pageEnd(self): doStuff() self._handle_pageEnd() doMoreStuff() """) disc(""" Here we list the methods only as an indication of the events that are being handled. Interested programmers can take a look at the source. """) eg(""" handle_currentFrame(self,fx) handle_documentBegin(self) handle_flowable(self,flowables) handle_frameBegin(self,*args) handle_frameEnd(self) handle_nextFrame(self,fx) handle_nextPageTemplate(self,pt) handle_pageBegin(self) handle_pageBreak(self) handle_pageEnd(self) """) disc(""" Using document templates can be very easy; $SimpleDoctemplate$ is a class derived from $BaseDocTemplate$ which provides its own $PageTemplate$ and $Frame$ setup. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) doc = SimpleDocTemplate('mydoc.pdf',pagesize = letter) doc.build(story) """) heading3("$PageTemplates$") disc(""" The $PageTemplate$ class is a container class with fairly minimal semantics. Each instance contains a list of $Frames$ and has methods which should be called at the start and end of each page. """) eg("PageTemplate(id=None,frames=[],onPage=_doNothing,onPageEnd=_doNothing)") disc(""" is used to initialize an instance, the $frames$ argument should be a list of $Frames$ whilst the optional $onPage$ and $onPageEnd$ arguments are callables which should have signature $def XXX(canvas,document)$ where $canvas$ and $document$ are the canvas and document being drawn. These routines are intended to be used to paint non-flowing (i.e. standard) parts of pages. These attribute functions are exactly parallel to the pure virtual methods $PageTemplate.beforPage$ and $PageTemplate.afterPage$ which have signature $beforPage(self,canvas,document)$. The methods allow class derivation to be used to define standard behaviour, whilst the attributes allow instance changes. The $id$ argument is used at run time to perform $PageTemplate$ switching so $id='FirstPage'$ or $id='TwoColumns'$ are typical. """)
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/docs/userguide/ch4_platypus_concepts.py
0.741019
0.584538
ch4_platypus_concepts.py
pypi
from reportlab.platypus import PageTemplate, BaseDocTemplate, Frame, Paragraph from reportlab.lib.units import inch from reportlab.lib.sequencer import Sequencer from reportlab.rl_config import defaultPageSize class FrontCoverTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, 3*inch, self.pageWidth - 2*inch, self.pageHeight - 518, id='cover') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): canvas.saveState() canvas.drawImage('../images/replogo.gif',2*inch, 8*inch) canvas.setFont('Times-Roman', 10) canvas.line(inch, 120, self.pageWidth - inch, 120) canvas.drawString(inch, 100, 'ReportLab') canvas.drawString(inch, 88, 'Wimbletech') canvas.drawString(inch, 76, '35 Wimbledon Hill Road') canvas.drawString(inch, 64, 'London SW19 7NB, UK') canvas.restoreState() class OneColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TOCTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, 'Table of contents') canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TwoColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] colWidth = 0.5 * (self.pageWidth - 2.25*inch) frame1 = Frame(inch, inch, colWidth, self.pageHeight - 2*inch, id='leftCol') frame2 = Frame(0.5 * self.pageWidth + 0.125, inch, colWidth, self.pageHeight - 2*inch, id='rightCol') PageTemplate.__init__(self, id, [frame1, frame2]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y*inch) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class RLDocTemplate(BaseDocTemplate): def afterInit(self): self.addPageTemplates(FrontCoverTemplate('Cover', self.pagesize)) self.addPageTemplates(TOCTemplate('TOC', self.pagesize)) self.addPageTemplates(OneColumnTemplate('Normal', self.pagesize)) self.addPageTemplates(TwoColumnTemplate('TwoColumn', self.pagesize)) self.seq = Sequencer() def beforeDocument(self): self.canv.showOutline() self.title = "(Document Title Goes Here)" self.chapter = "(No chapter yet)" self.seq.reset('section') self.seq.reset('chapter') def afterFlowable(self, flowable): """Detect Level 1 and 2 headings, build outline, and track chapter title.""" if isinstance(flowable, Paragraph): style = flowable.style.name txt = flowable.getPlainText() if style == 'Title': self.title = txt elif style == 'Heading1': self.chapter = txt key = 'ch%s' % self.seq.nextf('chapter') self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 0, 0) self.seq.reset("section") self.notify('TOCEntry', (0, txt, self.page, key)) elif style == 'Heading2': self.section = flowable.text key = 'ch%ss%s' % (self.seq.thisf("chapter"), self.seq.nextf("section")) self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 1, 0) self.notify('TOCEntry', (1, txt, self.page, key))
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/tools/docco/rltemplate.py
0.400515
0.169784
rltemplate.py
pypi
__version__='3.3.0' # xml parser stuff for PythonPoint # PythonPoint Markup Language! __doc__=""" This demonstrates a custom shape for use with the <customshape> tag. The shape must fulfil a very simple interface, which may change in future. The XML tag currently has this form: <customshape module="customshapes.py" class = "MyShape" initargs="(100,200,3)" /> PythonPoint will look in the given module for the given class, evaluate the arguments string and pass it to the constructor. Then, it will call object.drawOn(canvas) Thus your object must be fully defined by the constructor. For this one, we pass three argumenyts: x, y and scale. This does a five-tile jigsaw over which words can be overlaid; based on work done for a customer's presentation. """ import reportlab.pdfgen.canvas from reportlab.lib import colors from reportlab.lib.corp import RL_CorpLogo from reportlab.graphics.shapes import Drawing ## custom shape for use with PythonPoint. class Jigsaw: """This draws a jigsaw patterm. By default it is centred on 0,0 and has dimensions of 200 x 140; use the x/y/scale attributes to move it around.""" #Using my usual bulldozer coding style - I am sure a mathematician could #derive an elegant way to draw this, but I just took a ruler, guessed at #the control points, and reflected a few lists at the interactive prompt. def __init__(self, x, y, scale=1): self.width = 200 self.height = 140 self.x = x self.y = y self.scale = scale def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(600, 100, 'A Custom Shape') canvas.translate(self.x, self.y) canvas.scale(self.scale, self.scale) self.drawBounds(canvas) self.drawCentre(canvas) self.drawTopLeft(canvas) self.drawBottomLeft(canvas) self.drawBottomRight(canvas) self.drawTopRight(canvas) canvas.restoreState() def curveThrough(self, path, pointlist): """Helper to curve through set of control points.""" assert len(pointlist) % 3 == 1, "No. of points must be 3n+1 for integer n" (x,y) = pointlist[0] path.moveTo(x, y) idx = 1 while idx < len(pointlist)-2: p1, p2, p3 = pointlist[idx:idx+3] path.curveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]) idx = idx + 3 def drawShape(self, canvas, controls, color): """Utlity to draw a closed shape through a list of control points; extends the previous proc""" canvas.setFillColor(color) p = canvas.beginPath() self.curveThrough(p, controls) p.close() canvas.drawPath(p, stroke=1, fill=1) def drawBounds(self, canvas): """Guidelines to help me draw - not needed in production""" canvas.setStrokeColor(colors.red) canvas.rect(-100,-70,200,140) canvas.line(-100,0,100,0) canvas.line(0,70,0,-70) canvas.setStrokeColor(colors.black) def drawCentre(self, canvas): controls = [ (0,50), #top #top right edge - duplicated for that corner piece (5,50),(10,45),(10,40), (10,35),(15,30),(20,30), (25,30),(30,25),(30,20), (30,15),(35,10),(40,10), (45,10),(50,5),(50,0), #bottom right edge (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), #bottom left (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #top left (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50) ] self.drawShape(canvas, controls, colors.yellow) def drawTopLeft(self, canvas): controls = [(-100,70), (-100,69),(-100,1),(-100,0), (-99,0),(-91,0),(-90,0), #jigsaw interlock - 4 sections (-90,5),(-92,5),(-92,10), (-92,15), (-85,15), (-80,15), (-75,15),(-68,15),(-68,10), (-68,5),(-70,5),(-70,0), (-69,0),(-51,0),(-50,0), #five distinct curves (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50), (0,51),(0,69),(0,70), (-1,70),(-99,70),(-100,70) ] self.drawShape(canvas, controls, colors.teal) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawBottomRight(self, canvas): controls = [ (100,-70), (100,-69),(100,-1),(100,0), (99,0),(91,0),(90,0), #jigsaw interlock - 4 sections (90, -5), (92, -5), (92, -10), (92, -15), (85, -15), (80, -15), (75, -15), (68, -15), (68, -10), (68, -5), (70, -5), (70, 0), (69, 0), (51, 0), (50, 0), #wavyline (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), (0,-51), (0,-69), (0,-70), (1,-70),(99,-70),(100,-70) ] self.drawShape(canvas, controls, colors.navy) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawTopRight(self, canvas): controls = [(100, 70), (99, 70), (1, 70), (0, 70), (0, 69), (0, 51), (0, 50), (5, 50), (10, 45), (10, 40), (10, 35), (15, 30), (20, 30), (25, 30), (30, 25), (30, 20), (30, 15), (35, 10), (40, 10), (45, 10), (50, 5), (50, 0), (51, 0), (69, 0), (70, 0), (70, -5), (68, -5), (68, -10), (68, -15), (75, -15), (80, -15), (85, -15), (92, -15), (92, -10), (92, -5), (90, -5), (90, 0), (91, 0), (99, 0), (100, 0) ] self.drawShape(canvas, controls, colors.magenta) class Logo: """This draws a ReportLab Logo.""" def __init__(self, x, y, width, height): logo = RL_CorpLogo() logo.x = x logo.y = y logo.width = width logo.height = height self.logo = logo def drawOn(self, canvas): logo = self.logo x, y = logo.x, logo.y w, h = logo.width, logo.height D = Drawing(w, h) D.add(logo) D.drawOn(canvas, 0, 0) def run(): c = reportlab.pdfgen.canvas.Canvas('customshape.pdf') J = Jigsaw(300, 540, 2) J.drawOn(c) c.save() if __name__ == '__main__': run()
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/tools/pythonpoint/customshapes.py
0.705379
0.647603
customshapes.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles, enums def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} para = styles.ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Courier' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = enums.TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Courier-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Courier-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 #para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Couruer-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/tools/pythonpoint/styles/horrible.py
0.573201
0.451871
horrible.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles from reportlab.lib.enums import TA_CENTER def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} ParagraphStyle = styles.ParagraphStyle para = ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Helvetica' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('Indent', stylesheet['Normal']) para.leftIndent = 36 para.firstLineIndent = 0 stylesheet['Indent'] = para para = ParagraphStyle('Centered', stylesheet['Normal']) para.alignment = TA_CENTER stylesheet['Centered'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Helvetica-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Helvetica' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Helvetica-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Bullet2', stylesheet['Bullet']) para.firstLineIndent = 0 para.bulletIndent = 72 para.leftIndent = 108 stylesheet['Bullet2'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Helvetica-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab-eh-3.6.11.tar.gz/reportlab-eh-3.6.11/tools/pythonpoint/styles/modern.py
0.516595
0.427277
modern.py
pypi
import array import itertools import math import operator import re from base64 import b64decode from copy import deepcopy from dataclasses import dataclass from typing import List, Union, Tuple import qrcode from reportlab.lib.units import toLength from reportlab.pdfgen.canvas import FILL_EVEN_ODD, Canvas DEFAULT_PARAMS = { 'version': None, 'error_correction': 'L', } FALSE_VALUES = {'off', 'false', 'False', '0', False, 0, None} QR_PARAMS = {'version', 'error_correction'} QR_ERROR_CORRECTIONS = { 'L': qrcode.ERROR_CORRECT_L, 'M': qrcode.ERROR_CORRECT_M, 'Q': qrcode.ERROR_CORRECT_Q, 'H': qrcode.ERROR_CORRECT_H, } DIRECTION = ( ( 1, 0), # right ( 0, 1), # down (-1, 0), # left ( 0, -1), # up ) DIRECTION_TURNS_CHECKS = ( ( 0, 0), # right (-1, 0), # down (-1, -1), # left ( 0, -1), # up ) LENGTH_ABSOLUTE = 0 LENGTH_PIXELS = 1 LENGTH_RELATIVE = 2 PARAMS_GLOBAL = 0 PARAMS_PART = 1 ALIGN_POSITION_TABLE = [ [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170], ] @dataclass class Length(object): __slots__ = ['kind', 'value'] kind: int value: int class Vector(tuple): def __add__(self, other): return self.__class__(map(operator.add, self, other)) class Transforms: @staticmethod def to_length(val: Union[str, int, float]) -> float: return toLength(val) if isinstance(val, str) else float(val) @staticmethod def to_bool(val: Union[str, bool]) -> bool: return val not in FALSE_VALUES @staticmethod def to_float(val: Union[str, float]) ->float: return float(val) @staticmethod def to_area(val: str) -> List[Tuple[Length, Length, Length, Length]]: """ Area string in form x:y:w:h:… to list of areas """ parts = val.split(':') if len(parts) % 4 != 0: raise ValueError(f"Wrong value `{val}`, expected coordinates: x:y:w:h") coordinates = [] for coordinate in parts: if coordinate[-1:] == '%': coordinates.append(Length(LENGTH_RELATIVE, float(coordinate[:-1]) / 100)) else: try: coordinates.append(Length(LENGTH_PIXELS, int(coordinate))) except ValueError: coordinates.append(Length(LENGTH_ABSOLUTE, Transforms.to_length(coordinate))) coordinates = [tuple(coordinates[i:i + 4]) for i in range(0, len(coordinates), 4)] for area in coordinates: if not all(coordinate.kind == area[0].kind for coordinate in area): raise ValueError(f"Mixed units in `{val}`") return coordinates class ReportlabImageBase(qrcode.image.base.BaseImage): PARAMS = { 'size': Transforms.to_length, 'padding': None, 'fg': None, 'bg': None, 'fg_alpha': Transforms.to_float, 'bg_alpha': Transforms.to_float, 'x': Transforms.to_length, 'y': Transforms.to_length, 'invert': Transforms.to_bool, 'negative': Transforms.to_bool, 'mask': Transforms.to_bool, 'radius': Transforms.to_float, 'enhanced_path': Transforms.to_bool, 'hole': Transforms.to_area, } DRAW_STATE_PROPERTIES = ['bitmap', 'fg', 'fg_alpha', 'enhanced_path', 'hole', 'radius'] size = toLength('5cm') padding = '2.5' bg = None fg = '#000000' bg_alpha = 1.0 fg_alpha = 1.0 bitmap = None x = 0 y = 0 invert = False negative = False mask = False enhanced_path = None radius = 0 hole = [] draw_parts = None draw_state_stack = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bitmap = array.array('B', [1 if self.invert else 0] * self.width * self.width) if isinstance(self.padding, str) and '%' in self.padding: self.padding = float(self.padding[:-1]) * self.size / 100 else: try: self.padding = float(self.padding) self.padding = (self.size / (self.width + self.padding * 2)) * self.padding except ValueError: self.padding = toLength(self.padding) if isinstance(self.padding, str) else float(self.padding) if self.enhanced_path is None: self.enhanced_path = self.radius == 0 self.hole = [self.convert_area_to_pixels(fragment) for fragment in self.hole] if not self.draw_parts: self.draw_parts = [{'draw': [('+', 'all')]}] def drawrect(self, row: int, col: int): self.bitmap_set((col, row), 0 if self.invert else 1) def save(self, stream: Canvas): if not self.mask: stream.saveState() a0, b0, c0, d0, e0, f0 = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) # current matrix self.clear_area() def transform(a, b, c, d, e, f): nonlocal a0, b0, c0, d0, e0, f0 matrix = (a0*a+c0*b, b0*a+d0*b, a0*c+c0*d, b0*c+d0*d, a0*e+c0*f+e0, b0*e+d0*f+f0) a0, b0, c0, d0, e0, f0 = matrix stream.transform(a, b, c, d, e, f) def restore_transform(): nonlocal a0, b0, c0, d0, e0, f0 det = a0*d0 - c0*b0 a = d0/det c = -c0/det e = (c0*f0 - d0*e0)/det d = a0/det b = -b0/det f = (e0*b0 - f0*a0)/det stream.transform(a, b, c, d, e, f) try: # Move to start transform(1.0, 0.0, 0.0, -1.0, self.x, self.y + self.size) if not self.mask: self.draw_background(stream) # Set transform matrix scale = (self.size - (self.padding * 2.0)) / self.width transform(scale, 0.0, 0.0, scale, self.padding, self.padding) for part in self.draw_parts: self.begin_part(part) if not self.mask: # Set foreground stream.setFillColor(self.fg) stream.setFillAlpha(self.fg_alpha) p = stream.beginPath() if self.negative: pad = self.padding / scale p.moveTo(-pad, -pad) p.lineTo(self.width + pad, -pad) p.lineTo(self.width + pad, self.width + pad) p.lineTo(-pad, self.width + pad) p.close() if self.radius == 0: p = self.draw_code(p) else: p = self.draw_rounded_code(p) if self.mask: stream.clipPath(p, stroke=0, fill=1, fillMode=FILL_EVEN_ODD) else: stream.drawPath(p, stroke=0, fill=1, fillMode=FILL_EVEN_ODD) self.finish_part() finally: if self.mask: restore_transform() stream.setFillAlpha(1.0) else: stream.restoreState() def draw_background(self, stream: Canvas): """ Draw rectangle on background if is not transparent """ if self.bg is not None: stream.setFillColor(self.bg) stream.setFillAlpha(self.bg_alpha) stream.rect(0, 0, self.size, self.size, fill=1, stroke=0) def draw_code(self, path): """ Draw QR code """ for segment in self.get_segments(): path.moveTo(segment[0][0], segment[0][1]) for coords in segment[1:-1]: path.lineTo(coords[0], coords[1]) path.close() return path def draw_rounded_code(self, path): """ Draw QR code using rounded paths """ for segment in self.get_segments(): segment = segment[:-1] for i in range(0, len(segment)): coords = segment[i] prev_coords = segment[i - 1] next_coords = segment[(i + 1) % len(segment)] prev_dir = self.__calc_round_direction(prev_coords, coords, self.radius) next_dir = self.__calc_round_direction(next_coords, coords, self.radius) if i == 0: path.moveTo(coords[0] + prev_dir[0], coords[1] + prev_dir[1]) else: path.lineTo(coords[0] + prev_dir[0], coords[1] + prev_dir[1]) c = 0.45 # 1 - (4/3)*tan(pi/8) path.curveTo( coords[0] + prev_dir[0] * c, coords[1] + prev_dir[1] * c, coords[0] + next_dir[0] * c, coords[1] + next_dir[1] * c, coords[0] + next_dir[0], coords[1] + next_dir[1], ) path.close() return path def addr(self, coords: Tuple[int, int]) -> int: """ Get index to bitmap """ col, row = coords if row < 0 or col < 0 or row >= self.width or col >= self.width: return None return row * self.width + col def coord(self, addr: int) -> Tuple[int, int]: """ Returns bitmap coordinates from address """ return Vector((addr % self.width, addr // self.width)) def bitmap_get(self, coords: Tuple[int, int]) -> int: """ Returns pixel value of bitmap """ addr = self.addr(coords) return 0 if addr is None else self.bitmap[addr] def bitmap_set(self, coords: Tuple[int, int], value: int): """ Set pixel value of bitmap """ addr = self.addr(coords) self.bitmap[addr] = value def bitmap_invert(self, coords): """ Invert value of pixel """ addr = self.addr(coords) self.bitmap[addr] = 0 if self.bitmap[addr] else 1 def get_segments(self) -> List[List[Tuple[int, int]]]: """ Return list of segments (vector shapes) """ segments = [] segment = self.__consume_segment() while segment: segments.append(segment) segment = self.__consume_segment() return segments def convert_absolute_to_relative(self, coordinate: Length) -> Length: if coordinate.kind == LENGTH_ABSOLUTE: return Length(LENGTH_RELATIVE, (coordinate.value - self.padding) / (self.size - self.padding * 2)) return coordinate def convert_coordinate_to_pixels(self, coordinate: Length, round_up: bool = False) -> int: if coordinate.kind == LENGTH_PIXELS: return coordinate.value else: value = coordinate.value * self.width return math.ceil(value) if round_up else math.floor(value) def convert_area_to_pixels(self, area: Tuple[Length, Length, Length, Length]) -> Tuple[int, int, int, int]: area = [self.convert_absolute_to_relative(coordinate) for coordinate in area] x, y, w, h = area x_px = max(self.convert_coordinate_to_pixels(x), 0) y_px = max(self.convert_coordinate_to_pixels(y), 0) x2 = Length(x.kind, x.value + w.value) y2 = Length(y.kind, y.value + h.value) w_px = max(min(self.convert_coordinate_to_pixels(x2, True) - x_px, self.width - x_px), 1) h_px = max(min(self.convert_coordinate_to_pixels(y2, True) - y_px, self.width - y_px), 1) return (x_px, y_px, w_px, h_px) def clear_area(self): for hole in self.hole: for x in range(hole[0], hole[0] + hole[2]): for y in range(hole[1], hole[1] + hole[3]): self.bitmap_set((x, y), 0) def __consume_segment(self) -> List[Tuple[int, int]]: """ Returns segment of qr image as path (pairs of x, y coordinates) """ line_intersections = [[] for __ in range(self.width)] try: # Find first pixel coords = self.coord(self.bitmap.index(1)) except ValueError: # Or no pixels left return def move(): nonlocal coords step = DIRECTION[direction] # Record intersection if step[1]: # Vertical move line = coords[1] if step[1] == -1: line -= 1 line_intersections[line].append(coords[0]) # Step coords += step # Accumulated path path = [] # Begin of line path.append(tuple(coords)) # Default direction to right direction = 0 # Default clockwiese direction clockwiese = 1 # Move to right move() # From shape begin to end while coords != path[0]: # Trun left val = self.bitmap_get(coords + DIRECTION_TURNS_CHECKS[(direction - max(0, clockwiese)) % 4]) if val: if self.enhanced_path: # Detect intersection pattern and change direction if not self.bitmap_get(coords + DIRECTION_TURNS_CHECKS[(direction + min(0, clockwiese)) % 4]): move() clockwiese = -clockwiese continue; path.append(tuple(coords)) direction = (direction - clockwiese) % 4 move() continue # Straight val = self.bitmap_get(coords + DIRECTION_TURNS_CHECKS[(direction + min(0, clockwiese)) % 4]) if val: move() continue # Trun right path.append(tuple(coords)) direction = (direction + clockwiese) % 4 move() path.append(tuple(coords)) # Remove shape from bitmap for row, line in enumerate(line_intersections): line = sorted(line) for start, end in zip(line[::2], line[1::2]): for col in range(start, end): self.bitmap_invert((col, row)) return path def begin_part(self, definition: dict): # save drawing state and mask bitmap self.draw_state_stack.append({prop: deepcopy(getattr(self, prop)) for prop in self.DRAW_STATE_PROPERTIES}) for prop, value in definition.items(): if prop in self.DRAW_STATE_PROPERTIES: setattr(self, prop, value) draw_mask = definition['draw'] mask = None for operation, area in draw_mask: if operation == '+' and area == 'all': # implicit operation, not needed continue if mask is None: base_value = 0 if operation == '+' else 1 mask = array.array('B', [base_value] * self.width * self.width) if operation == '+': def mask_action(x, y): mask[x + y*self.width] = mask[x + y*self.width] or 1 else: def mask_action(x, y): mask[x + y*self.width] = 0 for area in self.get_fragment_area(area): for x in range(area[0], area[0] + area[2]): for y in range(area[1], area[1] + area[3]): mask_action(x, y) if mask is not None: self.bitmap = array.array('B', [bit * mask for bit, mask in zip(self.bitmap, mask)]) def get_version(self) -> int: return (self.width - 21) // 4 + 1 def get_align_positions(self) -> List[Tuple[int, int]]: positions = [] version = self.get_version() for x in ALIGN_POSITION_TABLE[version - 1]: for y in ALIGN_POSITION_TABLE[version - 1]: # exclude eyes if x < 8 and y < 8 or x > self.width - 8 and y < 8 or x < 8 and y > self.width - 8: continue positions.append((x, y)) return positions def get_fragment_area(self, area_name: str) -> List[Tuple[int, int, int, int]]: if area_name == 'all': return [(0, 0, self.width, self.width)] elif area_name == 'eye1': return [(0, 0, 7, 7)] elif area_name == 'eye2': return [(self.width - 7, 0, 7, 7)] elif area_name == 'eye3': return [(0, self.width - 7, 7, 7)] elif area_name == 'eyes': return self.get_fragment_area('eye1') + self.get_fragment_area('eye2') + self.get_fragment_area('eye3') elif area_name == 'eyepupil1': return [(2, 2, 3, 3)] elif area_name == 'eyepupil2': return [(self.width - 5, 2, 3, 3)] elif area_name == 'eyepupil3': return [(2, self.width - 5, 3, 3)] elif area_name == 'eyepupils': return self.get_fragment_area('eyepupil1') + self.get_fragment_area('eyepupil2') + self.get_fragment_area('eyepupil3') elif area_name == 'eyeball1': return [(0, 0, 7, 1), (0, 6, 7, 1), (0, 1, 1, 5), (6, 1, 1, 5)] elif area_name == 'eyeball2': return [(self.width - 7, 0, 7, 1), (self.width - 7, 6, 7, 1), (self.width - 7, 1, 1, 5), (self.width - 1, 1, 1, 5)] elif area_name == 'eyeball3': return [(0, self.width - 7, 7, 1), (0, self.width - 1, 7, 1), (0, self.width - 6, 1, 5), (6, self.width - 6, 1, 5)] elif area_name == 'eyeballs': return self.get_fragment_area('eyeball1') + self.get_fragment_area('eyeball2') + self.get_fragment_area('eyeball3') elif area_name == 'align': return [(x - 2, y - 2, 5, 5) for x, y in self.get_align_positions()] elif area_name == 'alignpupils': return [(x, y, 1, 1) for x, y in self.get_align_positions()] elif area_name == 'alignballs': patterns = [[(x - 2, y - 2, 5, 1), (x - 2, y + 2, 5, 1), (x - 2, y - 1, 1, 3), (x + 2, y - 1, 1, 3)] for x, y in self.get_align_positions()] return list(itertools.chain(*patterns)) raise ValueError(f"Unknown area {area_name}") def finish_part(self): # restore drawing state state = self.draw_state_stack.pop() for prop, value in state.items(): setattr(self, prop, value) def __calc_round_direction(self, src, dst, radius): return [min(max((s - d) * 0.5, -radius), radius) for s, d in zip(src, dst)] def transform_part_params(params, kwargs, base=ReportlabImageBase): # Chceck each parameter for key, value in kwargs.items(): # If is unknown, raise exception if key not in base.PARAMS: raise ValueError("Unknown attribute '%s'" % key) # Get transform function like to int transform = base.PARAMS[key] try: params[key] = value if transform is None else transform(value) except Exception as e: raise ValueError("Wrong value '%s' for attribute %s: %s" % (value, key, e)) def reportlab_image_factory(base=ReportlabImageBase, **kwargs): """ Returns ReportlabImage class for qrcode image_factory """ # specific part settings draw_parts = kwargs.pop('draw_parts', []) # transform common parameters params = {} transform_part_params(params, kwargs, base) parts = [] # parse parameters specific for pparts for part in draw_parts: draw_command = part.pop('draw') part_params = {} transform_part_params(part_params, part, base) draw_operations = [] draw_command = ['+'] + re.split(r'([+-])', draw_command) for operator, element in zip(draw_command[::2], draw_command[1::2]): if element: draw_operations.append((operator, element)) part_params['draw'] = draw_operations parts.append(part_params) if parts: params['draw_parts'] = parts return type('ReportlabImage', (base,), params) def parse_color(params, color_name): color = params.get(color_name) if color is None: return alpha = 1.0 if re.match(r'^#[0-9a-f]{8}$', color.lower()): color = color.lower() alpha = int(color[-2:], base=16) / 255 color = color[:7] params[color_name] = color params[f'{color_name}_alpha'] = alpha def clean_params(params, clean_type=PARAMS_GLOBAL): """ Validate and clean parameters """ if clean_type == PARAMS_GLOBAL: if params['version'] is not None: try: params['version'] = int(params['version']) except ValueError: raise ValueError("Version '%s' is not a number" % params['version']) if params['error_correction'] in QR_ERROR_CORRECTIONS: params['error_correction'] = QR_ERROR_CORRECTIONS[params['error_correction']] else: raise ValueError("Unknown error correction '%s', expected one of %s" % (params['error_correction'], ', '.join(QR_ERROR_CORRECTIONS.keys()))) parse_color(params, 'fg') parse_color(params, 'bg') def parse_params_string(params): """ Parses params string in form: key=value,key2=value2;(text|base64);content For example: size=5cm,fg=#ff0000,bg=#ffffff,version=1,error_correction=M,padding=5%;text;text to encode """ try: parsed_params, fmt, text = params.split(';', 2) except ValueError: raise ValueError("Wrong format, expected parametrs;format;content") if fmt not in ('text', 'base64'): raise ValueError("Unknown format '%s', supprted are text or base64" % fmt) params = DEFAULT_PARAMS.copy() # allow draw specific parts with different settings params['draw_parts'] = [] curreent_draw = params if parsed_params: try: for item in parsed_params.split(','): key, value = item.split('=', 1) if key == 'draw': curreent_draw = {'draw': value} params['draw_parts'].append(curreent_draw) else: curreent_draw[key] = value except ValueError: raise ValueError("Wrong format of parameters '%s', expected key=value pairs delimited by ',' character" % parsed_params) clean_params(params) for part in params['draw_parts']: clean_params(part, PARAMS_PART) text = text.encode('utf-8') if fmt == 'base64': try: text = b64decode(text) except Exception as e: raise ValueError("Wrong base64 '%s': %s" % (text.decode('utf-8'), e)) return params, text def build_qrcode(params: dict, text: str) -> ReportlabImageBase: factory_kwargs = {key: value for key, value in params.items() if key not in QR_PARAMS} qr_kwargs = {key: value for key, value in params.items() if key in QR_PARAMS} qr = qrcode.QRCode(image_factory=reportlab_image_factory(**factory_kwargs), border=0, **qr_kwargs) qr.add_data(text) return qr.make_image() def qr_draw(canvas, text, **kwargs): params = DEFAULT_PARAMS.copy() params.update(**kwargs) clean_params(params) if isinstance(text, str): text = text.encode('utf-8') build_qrcode(params, text).save(canvas) def qr(canvas, params=None): """ Generate QR code using plugInGraphic or plugInFlowable Example RML code: <illustration height="5cm" width="5cm" align="center"> <plugInGraphic module="reportlab_qrcode" function="qr">size=5cm;text;Simple text</plugInGraphic> </illustration> """ build_qrcode(*parse_params_string(params)).save(canvas)
/reportlab_qr_code_generator-1.7.0.tar.gz/reportlab_qr_code_generator-1.7.0/reportlab_qr_code/__init__.py
0.532425
0.317069
__init__.py
pypi
__version__='3.3.0' __doc__=""" PDFPathObject is an efficient way to draw paths on a Canvas. Do not instantiate directly, obtain one from the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py """ from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: """Represents a graphic path. There are certain 'modes' to PDF drawing, and making a separate object to expose Path operations ensures they are completed with no run-time overhead. Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes; and then add it back into the canvas with one of the relevant operators. Path objects are probably not long, so we pack onto one line the code argument allows a canvas to get the operatiosn appended directly so avoiding the final getCode """ def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path must start with a moveto or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self): "pack onto one line; used internally" return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): """Contributed to piddlePDF by Robert Kern, 28/7/99. Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2. The algorithm is an elliptical generalization of the formulae in Jim Fitzsimmon's TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): """Like arc, but draws a line from the current point to the start if the start is not the current point.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width, height): """Adds a rectangle to the path""" self._code_append('%s re' % fp_str((x, y, width, height))) def ellipse(self, x, y, width, height): """adds an ellipse to the path""" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): """adds a circle to the path""" x1 = x_cen - r y1 = y_cen - r width = height = 2*r self.ellipse(x1, y1, width, height) def roundRect(self, x, y, width, height, radius): """Draws a rectangle with rounded corners. The corners are approximately quadrants of a circle, with the given radius.""" #use a precomputed set of factors for the bezier approximation #to a circle. There are six relevant points on the x axis and y axis. #sketch them and it should all make sense! t = 0.4472 * radius x0 = x x1 = x0 + t x2 = x0 + radius x3 = x0 + width - radius x4 = x0 + width - t x5 = x0 + width y0 = y y1 = y0 + t y2 = y0 + radius y3 = y0 + height - radius y4 = y0 + height - t y5 = y0 + height self.moveTo(x2, y0) self.lineTo(x3, y0) #bottom row self.curveTo(x4, y0, x5, y1, x5, y2) #bottom right self.lineTo(x5, y3) #right edge self.curveTo(x5, y4, x4, y5, x3, y5) #top right self.lineTo(x2, y5) #top row self.curveTo(x1, y5, x0, y4, x0, y3) #top left self.lineTo(x0, y2) #left edge self.curveTo(x0, y1, x1, y0, x2, y0) #bottom left self.close() def close(self): "draws a line back to where it started" self._code_append('h')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfgen/pathobject.py
0.817246
0.62661
pathobject.py
pypi
__version__='3.3.0' __doc__=""" This module includes any mathematical methods needed for PIDDLE. It should have no dependencies beyond the Python library. So far, just Robert Kern's bezierArc. """ from math import sin, cos, pi, ceil def bezierArc(x1,y1, x2,y2, startAng=0, extent=90): """bezierArc(x1,y1, x2,y2, startAng=0, extent=90) --> List of Bezier curve control points. (x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The coordinate system has coordinates that increase to the right and down. Angles, measured in degress, start with 0 to the right (the positive X axis) and increase counter-clockwise. The arc extends from startAng to startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down semi-circle. The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4) such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and (x3, y3) as their respective Bezier control points.""" x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2) if abs(extent) <= 90: arcList = [startAng] fragAngle = float(extent) Nfrag = 1 else: arcList = [] Nfrag = int(ceil(abs(extent)/90.)) fragAngle = float(extent) / Nfrag x_cen = (x1+x2)/2. y_cen = (y1+y2)/2. rx = (x2-x1)/2. ry = (y2-y1)/2. halfAng = fragAngle * pi / 360. kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng)) if fragAngle < 0: sign = -1 else: sign = 1 pointList = [] for i in range(Nfrag): theta0 = (startAng + i*fragAngle) * pi / 180. theta1 = (startAng + (i+1)*fragAngle) *pi / 180. if fragAngle > 0: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) - kappa * sin(theta0)), y_cen - ry * (sin(theta0) + kappa * cos(theta0)), x_cen + rx * (cos(theta1) + kappa * sin(theta1)), y_cen - ry * (sin(theta1) - kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) else: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) + kappa * sin(theta0)), y_cen - ry * (sin(theta0) - kappa * cos(theta0)), x_cen + rx * (cos(theta1) - kappa * sin(theta1)), y_cen - ry * (sin(theta1) + kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) return pointList
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfgen/pdfgeom.py
0.863765
0.635534
pdfgeom.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py
0.563858
0.221035
_fontdata_widths_helveticaboldoblique.py
pypi
SymbolEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent', 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus', 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi', 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex', 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho', 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', 'braceleft', 'bar', 'braceright', 'similar', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Euro', 'Upsilon1', 'minute', 'lessequal', 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree', 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional', 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence', 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn', 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply', 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset', 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element', 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif', 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot', 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup', 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp', 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex', 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex', None, 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', 'bracerightbt', None)
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_enc_symbol.py
0.621311
0.246998
_fontdata_enc_symbol.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_courieroblique.py
0.620277
0.171338
_fontdata_widths_courieroblique.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_courierbold.py
0.620277
0.171338
_fontdata_widths_courierbold.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_courier.py
0.620277
0.171338
_fontdata_widths_courier.py
pypi
import string from reportlab.pdfbase.pdfdoc import PDFString, PDFStream, PDFDictionary, PDFName, PDFObject from reportlab.lib.colors import obj_R_G_B #==========================public interfaces def textFieldAbsolute(canvas, title, x, y, width, height, value="", maxlen=1000000, multiline=0): """Place a text field on the current page with name title at ABSOLUTE position (x,y) with dimensions (width, height), using value as the default value and maxlen as the maximum permissible length. If multiline is set make it a multiline field. """ theform = getForm(canvas) return theform.textField(canvas, title, x, y, x+width, y+height, value, maxlen, multiline) def textFieldRelative(canvas, title, xR, yR, width, height, value="", maxlen=1000000, multiline=0): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return textFieldAbsolute(canvas, title, xA, yA, width, height, value, maxlen, multiline) def buttonFieldAbsolute(canvas, title, value, x, y, width=16.7704, height=14.907): """Place a check button field on the current page with name title and default value value (one of "Yes" or "Off") at ABSOLUTE position (x,y). """ theform = getForm(canvas) return theform.buttonField(canvas, title, value, x, y, width=width, height=height) def buttonFieldRelative(canvas, title, value, xR, yR, width=16.7704, height=14.907): "same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return buttonFieldAbsolute(canvas, title, value, xA, yA, width=width, height=height) def selectFieldAbsolute(canvas, title, value, options, x, y, width, height): """Place a select field (drop down list) on the current page with name title and with options listed in the sequence options default value value (must be one of options) at ABSOLUTE position (x,y) with dimensions (width, height).""" theform = getForm(canvas) theform.selectField(canvas, title, value, options, x, y, x+width, y+height) def selectFieldRelative(canvas, title, value, options, xR, yR, width, height): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return selectFieldAbsolute(canvas, title, value, options, xA, yA, width, height) #==========================end of public interfaces from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf def getForm(canvas): "get form from canvas, create the form if needed" try: return canvas.AcroForm except AttributeError: theform = canvas.AcroForm = AcroForm() # install the form in the document d = canvas._doc cat = d._catalog cat.AcroForm = theform return theform class AcroForm(PDFObject): def __init__(self): self.fields = [] def textField(self, canvas, title, xmin, ymin, xmax, ymax, value="", maxlen=1000000, multiline=0): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen, font, fontsize, R, G, B, multiline) self.fields.append(field) canvas._addAnnotation(field) def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font=font, fontsize=fontsize, R=R, G=G, B=B) self.fields.append(field) canvas._addAnnotation(field) def buttonField(self, canvas, title, value, xmin, ymin, width=16.7704, height=14.907): # determine the page ref doc = canvas._doc page = doc.thisPageRef() field = ButtonField(title, value, xmin, ymin, page, width=width, height=height) self.fields.append(field) canvas._addAnnotation(field) def format(self, document): from reportlab.pdfbase.pdfdoc import PDFArray proxy = PDFPattern(FormPattern, Resources=getattr(self,'resources',None) or FormResources(), NeedAppearances=getattr(self,'needAppearances','false'), fields=PDFArray(self.fields), SigFlags=getattr(self,'sigFlags',0)) return proxy.format(document) FormPattern = [ '<<\r\n', '/NeedAppearances ',['NeedAppearances'],'\r\n' '/DA ', PDFString('/Helv 0 Tf 0 g '), '\r\n', '/DR ',["Resources"],'\r\n', '/Fields ', ["fields"],'\r\n', PDFPatternIf('SigFlags',['\r\n/SigFlags ',['SigFlags']]), '>>' ] def FormFontsDictionary(): from reportlab.pdfbase.pdfdoc import PDFDictionary fontsdictionary = PDFDictionary() fontsdictionary.__RefOnly__ = 1 for fullname, shortname in FORMFONTNAMES.items(): fontsdictionary[shortname] = FormFont(fullname, shortname) fontsdictionary["ZaDb"] = PDFPattern(ZaDbPattern) return fontsdictionary def FormResources(): return PDFPattern(FormResourcesDictionaryPattern, Encoding=PDFPattern(EncodingPattern,PDFDocEncoding=PDFPattern(PDFDocEncodingPattern)), Font=FormFontsDictionary()) ZaDbPattern = [ ' <<' ' /BaseFont' ' /ZapfDingbats' ' /Name' ' /ZaDb' ' /Subtype' ' /Type1' ' /Type' ' /Font' '>>'] FormResourcesDictionaryPattern = [ '<<', ' /Encoding ', ["Encoding"], '\r\n', ' /Font ', ["Font"], '\r\n', '>>' ] FORMFONTNAMES = { "Helvetica": "Helv", "Helvetica-Bold": "HeBo", 'Courier': "Cour", 'Courier-Bold': "CoBo", 'Courier-Oblique': "CoOb", 'Courier-BoldOblique': "CoBO", 'Helvetica-Oblique': "HeOb", 'Helvetica-BoldOblique': "HeBO", 'Times-Roman': "Time", 'Times-Bold': "TiBo", 'Times-Italic': "TiIt", 'Times-BoldItalic': "TiBI", } EncodingPattern = [ '<<', ' /PDFDocEncoding ', ["PDFDocEncoding"], '\r\n', '>>', ] PDFDocEncodingPattern = [ '<<' ' /Differences' ' [' ' 24' ' /breve' ' /caron' ' /circumflex' ' /dotaccent' ' /hungarumlaut' ' /ogonek' ' /ring' ' /tilde' ' 39' ' /quotesingle' ' 96' ' /grave' ' 128' ' /bullet' ' /dagger' ' /daggerdbl' ' /ellipsis' ' /emdash' ' /endash' ' /florin' ' /fraction' ' /guilsinglleft' ' /guilsinglright' ' /minus' ' /perthousand' ' /quotedblbase' ' /quotedblleft' ' /quotedblright' ' /quoteleft' ' /quoteright' ' /quotesinglbase' ' /trademark' ' /fi' ' /fl' ' /Lslash' ' /OE' ' /Scaron' ' /Ydieresis' ' /Zcaron' ' /dotlessi' ' /lslash' ' /oe' ' /scaron' ' /zcaron' ' 160' ' /Euro' ' 164' ' /currency' ' 166' ' /brokenbar' ' 168' ' /dieresis' ' /copyright' ' /ordfeminine' ' 172' ' /logicalnot' ' /.notdef' ' /registered' ' /macron' ' /degree' ' /plusminus' ' /twosuperior' ' /threesuperior' ' /acute' ' /mu' ' 183' ' /periodcentered' ' /cedilla' ' /onesuperior' ' /ordmasculine' ' 188' ' /onequarter' ' /onehalf' ' /threequarters' ' 192' ' /Agrave' ' /Aacute' ' /Acircumflex' ' /Atilde' ' /Adieresis' ' /Aring' ' /AE' ' /Ccedilla' ' /Egrave' ' /Eacute' ' /Ecircumflex' ' /Edieresis' ' /Igrave' ' /Iacute' ' /Icircumflex' ' /Idieresis' ' /Eth' ' /Ntilde' ' /Ograve' ' /Oacute' ' /Ocircumflex' ' /Otilde' ' /Odieresis' ' /multiply' ' /Oslash' ' /Ugrave' ' /Uacute' ' /Ucircumflex' ' /Udieresis' ' /Yacute' ' /Thorn' ' /germandbls' ' /agrave' ' /aacute' ' /acircumflex' ' /atilde' ' /adieresis' ' /aring' ' /ae' ' /ccedilla' ' /egrave' ' /eacute' ' /ecircumflex' ' /edieresis' ' /igrave' ' /iacute' ' /icircumflex' ' /idieresis' ' /eth' ' /ntilde' ' /ograve' ' /oacute' ' /ocircumflex' ' /otilde' ' /odieresis' ' /divide' ' /oslash' ' /ugrave' ' /uacute' ' /ucircumflex' ' /udieresis' ' /yacute' ' /thorn' ' /ydieresis' ' ]' ' /Type' ' /Encoding' '>>'] def FormFont(BaseFont, Name): from reportlab.pdfbase.pdfdoc import PDFName return PDFPattern(FormFontPattern, BaseFont=PDFName(BaseFont), Name=PDFName(Name), Encoding=PDFPattern(PDFDocEncodingPattern)) FormFontPattern = [ '<<', ' /BaseFont ', ["BaseFont"], '\r\n', ' /Encoding ', ["Encoding"], '\r\n', ' /Name ', ["Name"], '\r\n', ' /Subtype ' ' /Type1 ' ' /Type ' ' /Font ' '>>' ] def resetPdfForm(): pass from reportlab.rl_config import register_reset register_reset(resetPdfForm) resetPdfForm() def TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen=1000000, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627, multiline=0): from reportlab.pdfbase.pdfdoc import PDFString, PDFName Flags = 0 if multiline: Flags = Flags | (1<<12) # bit 13 is at position 12 :) fontname = FORMFONTNAMES[font] return PDFPattern(TextFieldPattern, value=PDFString(value), maxlen=maxlen, page=page, title=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B, Flags=Flags) TextFieldPattern = [ '<<' ' /DA' ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)' ' /DV ', ["value"], '\r\n', ' /F 4 /FT /Tx' '/MK << /BC [ 0 0 0 ] >>' ' /MaxLen ', ["maxlen"], '\r\n', ' /P ', ["page"], '\r\n', ' /Rect ' ' [', ["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ]' '/Subtype /Widget' ' /T ', ["title"], '\r\n', ' /Type' ' /Annot' ' /V ', ["value"], '\r\n', ' /Ff ', ["Flags"],'\r\n', '>>'] def SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627): #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B) from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray if value not in options: raise ValueError("value %s must be one of options %s" % (repr(value), repr(options))) fontname = FORMFONTNAMES[font] optionstrings = list(map(PDFString, options)) optionarray = PDFArray(optionstrings) return PDFPattern(SelectFieldPattern, Options=optionarray, Selected=PDFString(value), Page=page, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B) SelectFieldPattern = [ '<< % a select list\r\n' ' /DA ', ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)\r\n', #' (/Helv 12 Tf 0 g)\r\n', ' /DV ', ["Selected"],'\r\n', ' /F ', ' 4\r\n', ' /FT ', ' /Ch\r\n', ' /MK ', ' <<', ' /BC', ' [', ' 0', ' 0', ' 0', ' ]', ' /BG', ' [', ' 1', ' 1', ' 1', ' ]', ' >>\r\n', ' /Opt ', ["Options"],'\r\n', ' /P ', ["Page"],'\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] \r\n', '/Subtype', ' /Widget\r\n', ' /T ', ["Name"],'\r\n', ' /Type ', ' /Annot', ' /V ', ["Selected"],'\r\n', '>>'] def ButtonField(title, value, xmin, ymin, page, width=16.7704, height=14.907): if value not in ("Yes", "Off"): raise ValueError("button value must be 'Yes' or 'Off': "+repr(value)) fontSize = (11.3086/14.907)*height dx = (3.6017/16.7704)*width dy = (3.3881/14.907)*height return PDFPattern(ButtonFieldPattern, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmin+width, ymax=ymin+width, Hide=PDFPattern(['<< /S /Hide >>']), APDOff=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f\r\n' % vars(), width=width, height=height), APDYes=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET\r\n' % vars(), width=width, height=height), APNYes=ButtonStream('q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET Q\r\n' % vars(), width=width, height=height), Value=PDFName(value), Page=page) ButtonFieldPattern = ['<< ', '/AA', ' <<', ' /D ', ["Hide"],'\r\n', #' %(imported.18.0)s', ' >> ', '/AP ', ' <<', ' /D', ' <<', ' /Off ', #' %(imported.40.0)s', ["APDOff"], '\r\n', ' /Yes ', #' %(imported.39.0)s', ["APDYes"], '\r\n', ' >>', '\r\n', ' /N', ' << ', ' /Yes ', #' %(imported.38.0)s', ["APNYes"], '\r\n', ' >>', ' >>\r\n', ' /AS ', ["Value"], '\r\n', ' /DA ', PDFString('/ZaDb 0 Tf 0 g'), '\r\n', '/DV ', ["Value"], '\r\n', '/F ', ' 4 ', '/FT ', ' /Btn ', '/H ', ' /T ', '/MK ', ' <<', ' /AC (\\376\\377)', #PDFString('\376\377'), ' /CA ', PDFString('4'), ' /RC ', PDFString('\376\377'), ' >> ','\r\n', '/P ', ["Page"], '\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] ','\r\n', '/Subtype', ' /Widget ', '/T ', ["Name"], '\r\n', '/Type', ' /Annot ', '/V ', ["Value"], '\r\n', ' >>'] def buttonStreamDictionary(width=16.7704, height=14.907): "everything except the length for the button appearance streams" result = PDFDictionary() result["SubType"] = "/Form" result["BBox"] = "[0 0 %(width)s %(height)s]" % vars() font = PDFDictionary() font["ZaDb"] = PDFPattern(ZaDbPattern) resources = PDFDictionary() resources["ProcSet"] = "[ /PDF /Text ]" resources["Font"] = font result["Resources"] = resources return result def ButtonStream(content, width=16.7704, height=14.907): result = PDFStream(buttonStreamDictionary(width=width,height=height), content) result.filters = [] return result
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/pdfform.py
0.567337
0.407923
pdfform.py
pypi
widths = {'A': 667, 'AE': 944, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 667, 'G': 722, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 667, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 889, 'X': 667, 'Y': 611, 'Yacute': 611, 'Ydieresis': 611, 'Z': 611, 'Zcaron': 611, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 570, 'asciitilde': 570, 'asterisk': 500, 'at': 832, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 220, 'braceleft': 348, 'braceright': 348, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 389, 'exclamdown': 389, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 570, 'logicalnot': 606, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 606, 'mu': 576, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 266, 'ordmasculine': 300, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 500, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 389, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 444, 'w': 667, 'x': 500, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py
0.560974
0.26389
_fontdata_widths_timesbolditalic.py
pypi
widths = {'A': 722, 'AE': 889, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 556, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 389, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 889, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 556, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 556, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 944, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 611, 'Zcaron': 611, 'a': 444, 'aacute': 444, 'acircumflex': 444, 'acute': 333, 'adieresis': 444, 'ae': 667, 'agrave': 444, 'ampersand': 778, 'aring': 444, 'asciicircum': 469, 'asciitilde': 541, 'asterisk': 500, 'at': 921, 'atilde': 444, 'b': 500, 'backslash': 278, 'bar': 200, 'braceleft': 480, 'braceright': 480, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 200, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 278, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 564, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 564, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 564, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 564, 'logicalnot': 564, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 564, 'mu': 500, 'multiply': 564, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 453, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 564, 'plusminus': 564, 'q': 500, 'question': 444, 'questiondown': 444, 'quotedbl': 408, 'quotedblbase': 444, 'quotedblleft': 444, 'quotedblright': 444, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 180, 'r': 333, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 278, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_timesroman.py
0.558568
0.184327
_fontdata_widths_timesroman.py
pypi
widths = {'Alpha': 722, 'Beta': 667, 'Chi': 722, 'Delta': 612, 'Epsilon': 611, 'Eta': 722, 'Euro': 750, 'Gamma': 603, 'Ifraktur': 686, 'Iota': 333, 'Kappa': 722, 'Lambda': 686, 'Mu': 889, 'Nu': 722, 'Omega': 768, 'Omicron': 722, 'Phi': 763, 'Pi': 768, 'Psi': 795, 'Rfraktur': 795, 'Rho': 556, 'Sigma': 592, 'Tau': 611, 'Theta': 741, 'Upsilon': 690, 'Upsilon1': 620, 'Xi': 645, 'Zeta': 611, 'aleph': 823, 'alpha': 631, 'ampersand': 778, 'angle': 768, 'angleleft': 329, 'angleright': 329, 'apple': 790, 'approxequal': 549, 'arrowboth': 1042, 'arrowdblboth': 1042, 'arrowdbldown': 603, 'arrowdblleft': 987, 'arrowdblright': 987, 'arrowdblup': 603, 'arrowdown': 603, 'arrowhorizex': 1000, 'arrowleft': 987, 'arrowright': 987, 'arrowup': 603, 'arrowvertex': 603, 'asteriskmath': 500, 'bar': 200, 'beta': 549, 'braceex': 494, 'braceleft': 480, 'braceleftbt': 494, 'braceleftmid': 494, 'bracelefttp': 494, 'braceright': 480, 'bracerightbt': 494, 'bracerightmid': 494, 'bracerighttp': 494, 'bracketleft': 333, 'bracketleftbt': 384, 'bracketleftex': 384, 'bracketlefttp': 384, 'bracketright': 333, 'bracketrightbt': 384, 'bracketrightex': 384, 'bracketrighttp': 384, 'bullet': 460, 'carriagereturn': 658, 'chi': 549, 'circlemultiply': 768, 'circleplus': 768, 'club': 753, 'colon': 278, 'comma': 250, 'congruent': 549, 'copyrightsans': 790, 'copyrightserif': 790, 'degree': 400, 'delta': 494, 'diamond': 753, 'divide': 549, 'dotmath': 250, 'eight': 500, 'element': 713, 'ellipsis': 1000, 'emptyset': 823, 'epsilon': 439, 'equal': 549, 'equivalence': 549, 'eta': 603, 'exclam': 333, 'existential': 549, 'five': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'gamma': 411, 'gradient': 713, 'greater': 549, 'greaterequal': 549, 'heart': 753, 'infinity': 713, 'integral': 274, 'integralbt': 686, 'integralex': 686, 'integraltp': 686, 'intersection': 768, 'iota': 329, 'kappa': 549, 'lambda': 549, 'less': 549, 'lessequal': 549, 'logicaland': 603, 'logicalnot': 713, 'logicalor': 603, 'lozenge': 494, 'minus': 549, 'minute': 247, 'mu': 576, 'multiply': 549, 'nine': 500, 'notelement': 713, 'notequal': 549, 'notsubset': 713, 'nu': 521, 'numbersign': 500, 'omega': 686, 'omega1': 713, 'omicron': 549, 'one': 500, 'parenleft': 333, 'parenleftbt': 384, 'parenleftex': 384, 'parenlefttp': 384, 'parenright': 333, 'parenrightbt': 384, 'parenrightex': 384, 'parenrighttp': 384, 'partialdiff': 494, 'percent': 833, 'period': 250, 'perpendicular': 658, 'phi': 521, 'phi1': 603, 'pi': 549, 'plus': 549, 'plusminus': 549, 'product': 823, 'propersubset': 713, 'propersuperset': 713, 'proportional': 713, 'psi': 686, 'question': 444, 'radical': 549, 'radicalex': 500, 'reflexsubset': 713, 'reflexsuperset': 713, 'registersans': 790, 'registerserif': 790, 'rho': 549, 'second': 411, 'semicolon': 278, 'seven': 500, 'sigma': 603, 'sigma1': 439, 'similar': 549, 'six': 500, 'slash': 278, 'space': 250, 'spade': 753, 'suchthat': 439, 'summation': 713, 'tau': 439, 'therefore': 863, 'theta': 521, 'theta1': 631, 'three': 500, 'trademarksans': 786, 'trademarkserif': 890, 'two': 500, 'underscore': 500, 'union': 768, 'universal': 713, 'upsilon': 576, 'weierstrass': 987, 'xi': 493, 'zero': 500, 'zeta': 494}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_symbol.py
0.650245
0.257549
_fontdata_widths_symbol.py
pypi
WinAnsiEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase', 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron', 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash', 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet', 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling', 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright', 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute', 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior', 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters', 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis', 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn', 'ydieresis')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_enc_winansi.py
0.540439
0.153644
_fontdata_enc_winansi.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py
0.620277
0.171338
_fontdata_widths_courierboldoblique.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_helvetica.py
0.572245
0.290893
_fontdata_widths_helvetica.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 778, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 778, 'L': 667, 'Lslash': 667, 'M': 944, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 611, 'Q': 778, 'R': 722, 'S': 556, 'Scaron': 556, 'T': 667, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 1000, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 667, 'Zcaron': 667, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 833, 'aring': 500, 'asciicircum': 581, 'asciitilde': 520, 'asterisk': 500, 'at': 930, 'atilde': 500, 'b': 556, 'backslash': 278, 'bar': 220, 'braceleft': 394, 'braceright': 394, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 556, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 556, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 333, 'k': 556, 'l': 278, 'less': 570, 'logicalnot': 570, 'lslash': 278, 'm': 833, 'macron': 333, 'minus': 570, 'mu': 556, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 300, 'ordmasculine': 330, 'oslash': 500, 'otilde': 500, 'p': 556, 'paragraph': 540, 'parenleft': 333, 'parenright': 333, 'percent': 1000, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 556, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 444, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 333, 'thorn': 556, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_timesbold.py
0.5564
0.181953
_fontdata_widths_timesbold.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_helveticabold.py
0.563858
0.221035
_fontdata_widths_helveticabold.py
pypi