def generate_pdf(splits, threshold, shared_key, txid):
    cnt = 1
    for i in range(splits):
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font('Arial', 'B', 16)
        pdf.image('Flo.png', 20, 20, 33)
        pdf.multi_cell(
            0, 10,
            'A secret has been encrypted and posted on the blockchain of the FLO cryptocurrency.',
            0, 'C', False)
        pdf.multi_cell(0, 10, '', 0, 'C', 'False')
        pdf.multi_cell(
            0, 10,
            'The key to decrypt this secret has been split in ' + str(splits) +
            ' shares like this one. By design, the secret can be decrypted with any '
            + str(threshold) + ' of these shares.', 0, 'C', False)
        pdf.multi_cell(0, 10, '', 0, 'C', 'False')
        pdf.multi_cell(
            0, 10, 'Below is the part of the key that belongs to this share',
            0, 'C', False)
        pdf.multi_cell(0, 10, '', 0, 'C', 'False')
        pdf.multi_cell(0, 10, str(shared_key[i]), 0, 'C', False)
        pdf.multi_cell(0, 10, '', 0, 'C', 'False')
        pdf.multi_cell(0, 10,
                       'Transaction Id For This Encryption Is Given Below', 0,
                       'C', False)
        pdf.multi_cell(0, 10, str(txid), 0, 'C', False)
        pdf.set_y(-35)
        pdf.set_font('Arial', 'B', 8)
        pdf.cell(0, 10, 'Page %s' % pdf.page_no(), 0, 0, 'C')
        pdf.output('sharedkey' + str(cnt) + '.pdf', 'F')
        cnt += 1
示例#2
0
    def download_jpg(self, url):
        base_eap = url.split('/')[0]
        eap_url_for_entry = url.replace('/', '_')
        combined_url = self.join_url(self.EAP_BASE_URL, base_eap, eap_url_for_entry)
        pg = 1
        can_go = True
        file_list = []
        if not os.path.exists(self.JPEG_PATH):
            os.makedirs(self.JPEG_PATH)
        while can_go:
            dl_url = self.join_url(combined_url, str(pg) + '.jp2', 'full', str(self.height) + ',' +
                                   str(self.DEFAULT_WIDTH), str(self.rotation),
                                   self.EAP_FILENAME + '?t=' + str(int(time.time() * 1000)))

            title = os.path.join(self.JPEG_PATH, eap_url_for_entry + '_' + str(pg) + '.jpg')
            pg = pg + 1
            print('Downloading ' + title)
            try:
                urllib.request.urlretrieve(dl_url, title)
                file_list.append(title)
            except HTTPError:
                can_go = False

        if self.type == 'p':
            pdf = FPDF(orientation=self.type, unit='pt', format=(self.DEFAULT_WIDTH + 50, self.height + 50))
            pdf.add_page(orientation=self.type)
        else:
            pdf = FPDF(orientation=self.type, unit='pt', format=(self.height + 50, self.DEFAULT_WIDTH + 50))
            pdf.add_page(orientation=self.type)

        for image in file_list:
            print('Adding ' + image + ' to PDF')
            if self.type == 'p':
                pdf.image(image, h=self.height, w=self.DEFAULT_WIDTH)
            else:
                pdf.image(image, h=self.height, w=self.DEFAULT_WIDTH)
        page_count = pdf.page_no()
        if not os.path.exists(self.PDF_PATH):
            os.makedirs(self.PDF_PATH)
        pdf.output(os.path.join(self.PDF_PATH, eap_url_for_entry + '.pdf'))
        if page_count > len(file_list):
            # delete pg 1
            infile = PyPDF2.PdfFileReader(os.path.join(self.PDF_PATH, eap_url_for_entry + '.pdf'))
            outfile = PyPDF2.PdfFileWriter()
            pg = 1
            print('Deleting blank page...')
            while pg < page_count:
                p = infile.getPage(pg)
                pg = pg + 1
                outfile.addPage(p)
            with open(os.path.join(self.PDF_PATH, eap_url_for_entry + '_nofirst.pdf'), 'wb') as f:
                outfile.write(f)
            try:
                os.remove(os.path.join(self.PDF_PATH, eap_url_for_entry + '.pdf'))
            except OSError:
                pass
    def save(self, ass_name, stu_list, _dir):
        pdf = FPDF()
        while pdf.page_no() == 0:
            print("0 pages add title page")
            pdf.add_page()
            pdf.set_font("times", "B", 45)
            pdf.write(10, f"Assignment: {ass_name}\nDate: {date.today()}")
        for student in stu_list:
            for sub in student.submissions:
                pdf.add_page()
                pdf.set_font("times")
                pdf.write(10, f"Student:\n{student.name}")
                pdf.image(f"{_dir}/{sub}", w=50, h=50, link=f"{_dir}/{sub}")
        pdf.output(f"{ass_name}.pdf")

        self.create_warning(f"PDF for {ass_name} has been created")
示例#4
0
def generatePDF(userid, maxportfolioid):
    sql_statement = "SELECT symbol, purchase_price, lot_size from portfolio where userid = %s and portfolioid = %s"
    data = (userid, maxportfolioid)
    connection = DBconnection(sql_statement, data)
    Symbol = [i[0] for i in connection]
    PurchasePrice = [i[1] for i in connection]
    Lot_Size = [i[2] for i in connection]

    pdf = FPDF()

    #header of the pdf file
    header = 'Specifically curated for ' + str(userid)
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    w = pdf.get_string_width(header) + 6
    pdf.set_x((210 - w) / 2)
    pdf.cell(w, 9, header, 0, 0, 'C')
    pdf.line(20, 18, 210 - 20, 18)

    pdf.ln(10)
    pdf.set_font('Times', '', 12)
    pdf.multi_cell(
        0, 5,
        'Here is a list of suggested financial instruments for your peruse.')

    for i in range(len(Symbol)):
        pdf.ln()
        pdf.set_font('Arial', '', 12)
        pdf.set_fill_color(200, 220, 255)
        pdf.cell(
            0, 6, 'Financial Instrument ' + str(i + 1) + ": " +
            str(Symbol[i]) + " Unit Price " + str(PurchasePrice[i]) +
            " Lot Size " + str(Lot_Size[i]), 0, 1, 'L', 1)

        pdf.ln()
        pdf.set_font('Courier', 'B', 12)
        pdf.multi_cell(
            0, 5, 'A detailed analysis on ' + Symbol[i] + '---------------')

    #pdf.set_y(0) #on top of the page
    pdf.set_y(-30)  #30 CM from the bottom of the page
    pdf.set_font('Arial', '', 8)
    pdf.set_text_color(0)
    pdf.cell(0, 5, 'Page ' + str(pdf.page_no()), 0, 0, 'C')

    pdf.output(str(userid) + '.pdf', 'F')
    return pdf
示例#5
0
#####################hw test_data################################

distances = []

print('Initializing distances...')
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 12.0)
num = 0
for comment in hw_comments:
    num+=1
    comments = list(filter(None, comment.lower().split('.')))
    no_of_comments = len(comments)
    heading = "Comment "+str(num)
    pg_no = pdf.page_no()
    # checking for page no. in advance based on future formatting(line break) that will be done 
    # to ensure all sentences of comment are in the same page for each heading.
    if(pdf.ln(2*(no_of_comments+1))):
        if(pdf.page_no()!=pg_no):
            pdf.add_page()
    pdf.cell(h=5.0, align='L', w=0, txt=heading,  border=0, fill=False,ln=2)
    #print(pdf.page_no())
    for single_comment in comments:
        if len(single_comment) == 1:
            continue
        print(single_comment)

        #can't apply stemming as google negative pretrained vectors are used.
        '''
        single_comment = single_comment.strip()
示例#6
0
class Kut2FPDF(object):
    """
    Convert kuts to pyFPDF.
    """

    _document: "FPDF"

    _xml: Element
    _xml_data: Element
    _page_orientation: str
    _page_size: List[int]
    _bottom_margin: int
    _left_margin: int
    _right_margin: int
    _top_margin: int
    _page_top: Dict[int, int]
    _data_row: Element
    _parser_tools: "kparsertools.KParserTools"
    _avalible_fonts: List[str]
    _unavalible_fonts: List[str]
    design_mode: bool
    _actual_data_line: Optional[Element]
    _no_print_footer: bool
    _actual_section_size: int
    increase_section_size: int
    last_detail: bool
    actual_data_level: int
    last_data_processed: Element
    prev_level: int
    draws_at_header: Dict[str, str]
    detailn: Dict[str, int]
    name_: str
    _actual_append_page_no: int
    reset_page_count: bool

    def __init__(self) -> None:
        """Constructor."""

        check_dependencies({"fpdf": "fpdf2"})

        self._parser_tools = kparsertools.KParserTools()
        self._avalible_fonts = []
        self._page_top: Dict[int, int] = {}
        self._unavalible_fonts = []
        self.design_mode = config.value("ebcomportamiento/kugar_debug_mode",
                                        False)
        self._actual_data_line = None
        self._no_print_footer = False
        self.increase_section_size = 0
        self.actual_data_level = 0
        self.prev_level = -1
        self.draws_at_header = {}
        self.detailn = {}
        self.name_ = ""
        self._actual_append_page_no = -1
        self.reset_page_count = False
        self.new_page = False

    def parse(self,
              name: str,
              kut: str,
              data: str,
              report: "FPDF" = None,
              flags: List[int] = []) -> Optional[str]:
        """
        Parse string containing ".kut" file into a pdf and return its file path.

        @param name. Filename path for ".kut".
        @param kut. String with ".kut" file contents.
        @param data. String with data to be used in the report.
        @return Path to PDF file.
        """
        try:
            self._xml = self._parser_tools.loadKut(kut).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar %s.kut", name)
            return None
        try:
            self._xml_data = load2xml(data).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar xml_data")
            return None

        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "create",
            ["Pineboo", len(self._xml_data), "kugar"])
        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "setLabelText",
            ["Creando informe ...", "kugar"])

        self.name_ = name
        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =
        if report is None:
            from fpdf import FPDF  # type: ignore

            self._actual_append_page_no = 0
            self._document = FPDF(self._page_orientation, "pt",
                                  self._page_size)
            for font in self._document.core_fonts:
                LOGGER.debug("KUT2FPDF :: Adding font %s", font)
                self._avalible_fonts.append(font)
        else:
            self._document = report
        # Seteamos rutas a carpetas con tipos de letra ...

        if not hasattr(self._document, "set_stretching"):
            raise Exception("incorrect pyfpdf versión , you need <= 1.7.3")

        # Cargamos las fuentes disponibles
        next_page_break = (flags[2] == 1) if len(flags) == 3 else True
        page_append = (flags[1] == 1) if len(flags) > 1 else False
        page_display = (flags[0] == 1) if len(flags) > 0 else False

        if page_append:
            self.prev_level = -1
            self.last_detail = False

        page_break = False
        if self.new_page:
            page_break = True
            self.new_page = False

        if self.reset_page_count:
            self.reset_page_no()
            self.reset_page_count = False

        if self.design_mode:
            print("Append", page_append)
            print("Display", page_display)
            print("Page break", next_page_break)

        if next_page_break:
            self.reset_page_count = True

        if page_display:
            self.new_page = True

        self.processDetails(not page_break)

        # FIXME:Alguno valores no se encuentran
        for pages in self._document.pages.keys():
            page_content = self._document.pages[pages]["content"]
            for header in self.draws_at_header.keys():
                page_content = page_content.replace(
                    header, str(self.draws_at_header[header]))

            self._document.pages[pages]["content"] = page_content

        # print(self.draws_at_header.keys())
        self._document.set_title(self.name_)
        self._document.set_author("Pineboo - kut2fpdf plugin")

        return self._document

    def get_file_name(self) -> Optional[str]:
        """Retrieve file name where PDF should be saved."""
        import os

        pdf_name = application.PROJECT.tmpdir
        pdf_name += "/%s_%s.pdf" % (
            self.name_, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        if self._document is not None:
            self._document.output(pdf_name, "F")
            return pdf_name
        else:
            return None

    def topSection(self) -> int:
        """
        Retrieve top section margin for current page to calculate object positions.

        @return Number with ceiling for current page.
        """
        return self._page_top[int(self._document.page_no())]

    def setTopSection(self, value: int) -> None:
        """
        Update top section for current page.

        Usually updated when processing a section.
        @param value. Number specifying new ceiling.
        """
        self._actual_section_size = value - self.topSection()
        self._page_top[int(self._document.page_no())] = value

    def newPage(self, data_level: int, add_on_header: bool = True) -> None:
        """
        Add a new page to the document.
        """
        self._document.add_page(self._page_orientation)
        self._page_top[int(self._document.page_no())] = self._top_margin
        self._document.set_margins(
            self._left_margin, self._top_margin,
            self._right_margin)  # Lo dejo pero no se nota nada
        self._no_print_footer = False
        if self.design_mode:
            self.draw_margins()

        self._actual_section_size = 0
        self._actual_append_page_no += 1
        if self.design_mode:
            print("Nueva página", self.number_pages())

        # l_ini = data_level
        # l_end = self.prev_level

        # if l_ini == l_end:
        #    l_end = l_end + 1

        # if l_ini <= l_end:
        #    for l in range(l_ini , l_end):
        #        print(l)
        #        self.processSection("AddOnHeader", str(l))
        pg_headers = self._xml.findall("PageHeader")

        for page_header in pg_headers:
            if self.number_pages() == 1 or page_header.get(
                    "PrintFrequency") == "1":
                ph_level = (page_header.get("Level")
                            if page_header.get("Level") is not None else None)
                self.processSection("PageHeader", int(ph_level or "0"))
                break

        if add_on_header and not self.number_pages() == 1:
            for level in range(data_level + 1):
                self.processSection("AddOnHeader", int(level))

        # Por ahora se omite detail header

    def processDetails(self, keep_page: Optional[bool] = None) -> None:
        """
        Process detail secions with their matching detailHeader and detailFooter.
        """
        # Procesamos la cabecera si procede ..

        top_level = 0
        level = 0
        first_page_created = (keep_page if keep_page is not None
                              and self._document.page_no() > 0 else False)

        rows_array = self._xml_data.findall("Row")
        i = 0

        for data in rows_array:
            self._actual_data_line = data
            level_str: Optional[str] = data.get("level")
            if level_str is None:
                level_str = "0"
            level = int(level_str)
            if level > top_level:
                top_level = level

            if not first_page_created:
                self.newPage(level)
                first_page_created = True

            if rows_array[len(rows_array) - 1] is data:
                self.last_detail = True

            if level < self.prev_level:
                for lev in range(level + 1, self.prev_level + 1):
                    self.processData("DetailFooter", self.last_data_processed,
                                     lev)

            if not str(level) in self.detailn.keys():
                self.detailn[str(level)] = 0
            else:
                self.detailn[str(level)] += 1

            if level > self.prev_level:
                self.processData("DetailHeader", data, level)

            self.processData("Detail", data, level)

            self.last_data_processed = data

            self.prev_level = level

            application.PROJECT.message_manager().send(
                "progress_dialog_manager", "setProgress", [i, "kugar"])
            i += 1

        if not self._no_print_footer and hasattr(self, "last_data_processed"):
            for lev in reversed(range(top_level + 1)):
                self.processData("DetailFooter", self.last_data_processed, lev)

        application.PROJECT.message_manager().send("progress_dialog_manager",
                                                   "destroy", ["kugar"])

    def processData(self, section_name: str, data: Element,
                    data_level: int) -> None:
        """
        Check if detailHeader + detail + detailFooter do fit in the remaining page and create a new page if not.

        @param section_name. Section name to check
        @param data. Data to check
        @param data_level. Section level
        """
        self.actual_data_level = data_level
        list_sections = self._xml.findall(section_name)
        # data_size = len(listDF)

        for section in list_sections:
            draw_if = section.get("DrawIf")
            show = True
            if draw_if:
                show = bool(data.get(draw_if))

            if section.get("Level") == str(data_level) and show not in (
                    "", "False", "None"):

                if section_name in ("DetailHeader", "Detail"):
                    height_calculated = (
                        self._parser_tools.getHeight(section) +
                        self.topSection() + self.increase_section_size)

                    if section_name == "DetailHeader":
                        for detail in self._xml.findall("Detail"):
                            if detail.get("Level") == str(data_level):
                                height_calculated += self._parser_tools.getHeight(
                                    detail)

                    for detail_footer in self._xml.findall("DetailFooter"):
                        if detail_footer.get("Level") == str(data_level):
                            height_calculated += self._parser_tools.getHeight(
                                detail_footer)

                    aof_size = 0
                    for add_footer in self._xml.findall("AddOnFooter"):
                        # if add_footer.get("Level") == str(data_level):
                        aof_size += self._parser_tools.getHeight(add_footer)
                        height_calculated += self._parser_tools.getHeight(
                            add_footer)

                    page_footer: Any = self._xml.get("PageFooter")
                    if isinstance(page_footer, Element):
                        if (self._document.page_no() == 1
                                or page_footer.get("PrintFrecuency") == "1"):
                            height_calculated += self._parser_tools.getHeight(
                                page_footer)

                    height_calculated += self._bottom_margin
                    if (height_calculated +
                            aof_size) > self._document.h:  # Si nos pasamos
                        self._no_print_footer = True
                        # Vemos el tope por abajo
                        limit_bottom = self._document.h - aof_size
                        actual_size = self._parser_tools.getHeight(
                            section) + self.topSection()

                        if (actual_size >= limit_bottom - 2
                            ) or self.last_detail:  # +2 se usa de margen extra
                            self.processSection("AddOnFooter", int(data_level))

                            self.newPage(data_level)

                self.processXML(section, data)

                if section.get("NewPage") == "true" and not self.last_detail:
                    self.newPage(data_level, False)

                break  # Se ejecuta una sola instancia

    def processSection(self, name: str, level: int = 0) -> None:
        """
        Process non-detail sections.

        @param name. Section name to process
        """
        sec_list = self._xml.findall(name)
        sec_ = None
        for section in sec_list:
            if section.get("Level") == str(
                    level) or section.get("Level") is None:
                sec_ = section
                break

        if sec_ is not None:
            if (sec_.get("PrintFrequency") == "1"
                    or self._document.page_no() == 1
                    or name in ("AddOnHeader", "AddOnFooter")):
                self.processXML(sec_)

    def processXML(self, xml: Element, data: Optional[Element] = None) -> None:
        """
        Process single XML element.

        @param xml: Element to process
        @param. data: Line affected
        """

        fix_height = True
        if data is None:
            data = self._actual_data_line

        if self.design_mode and data is not None:
            print("Procesando", xml.tag, data.get("level"))

        size_updated = False
        if xml.tag == "DetailFooter":
            if xml.get("PlaceAtBottom") == "true":
                height = self._parser_tools.getHeight(xml)
                self.setTopSection(self._document.h - height -
                                   self.increase_section_size)
                size_updated = True

        if xml.tag == "PageFooter":
            fix_height = False

        if not size_updated:
            self.fix_extra_size(
            )  # Sirve para actualizar la altura con lineas que se han partido porque son muy largas

        for label in xml.iter("Label"):
            self.processText(label, data, fix_height)

        for field in xml.iter("Field"):
            self.processText(field, data, fix_height)

        for special in xml.iter("Special"):
            self.processText(special, data, fix_height, xml.tag)

        for calculated in xml.iter("CalculatedField"):
            self.processText(calculated, data, fix_height, xml.tag)

        # Busco draw_at_header en DetailFooter y los meto también
        if xml.tag == "DetailHeader":
            detail_level = xml.get("Level")
            if detail_level is None:
                raise Exception("Level tag not found")
            for detail_footer in self._xml.iter("DetailFooter"):
                if detail_footer.get("Level") == detail_level:
                    for calculated_filed in detail_footer.iter(
                            "CalculatedField"):
                        if calculated_filed.get("DrawAtHeader") == "true":
                            header_name = "%s_header_%s_%s" % (
                                self.detailn[detail_level],
                                detail_level,
                                calculated_filed.get("Field"),
                            )
                            self.draws_at_header[header_name] = ""
                            self.processText(calculated_filed, data,
                                             fix_height, xml.tag)

        for line in xml.iter("Line"):
            self.processLine(line, fix_height)

        if not size_updated:
            self.setTopSection(self.topSection() +
                               self._parser_tools.getHeight(xml))

    def fix_extra_size(self) -> None:
        """Increase size of the section if needed."""
        if self.increase_section_size > 0:
            self.setTopSection(self.topSection() + self.increase_section_size)
            self.increase_section_size = 0

    def processLine(self, xml: Element, fix_height: bool = True) -> None:
        """
        Process single line.

        @param xml. Sección de xml a procesar.
        @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
        """

        color = xml.get("Color")
        red = 0 if not color else int(color.split(",")[0])
        green = 0 if not color else int(color.split(",")[1])
        blue = 0 if not color else int(color.split(",")[2])

        style = int(xml.get("Style") or "0")
        width = int(xml.get("Width") or "0")
        pos_x1 = self.calculateLeftStart(xml.get("X1") or "0")
        pos_x1 = self.calculateWidth(pos_x1, 0, False)
        pos_x2 = self.calculateLeftStart(xml.get("X2") or "0")
        pos_x2 = self.calculateWidth(pos_x2, 0, False)

        # Ajustar altura a secciones ya creadas
        pos_y1 = int(xml.get("Y1") or "0") + self.topSection()
        pos_y2 = int(xml.get("Y2") or "0") + self.topSection()
        if fix_height:
            pos_y1 = self._parser_tools.ratio_correction_h(pos_y1)
            pos_y2 = self._parser_tools.ratio_correction_h(pos_y2)

        self._document.set_line_width(
            self._parser_tools.ratio_correction_h(width))
        self._document.set_draw_color(red, green, blue)
        dash_length = 1
        space_length = 1
        if style == 2:
            dash_length = 20
            space_length = 20
        elif style == 3:
            dash_length = 10
            space_length = 10

        self._document.dashed_line(pos_x1, pos_y1, pos_x2, pos_y2, dash_length,
                                   space_length)
        # else:
        #    self._document.line(X1, Y1, X2, Y2)

    def calculateLeftStart(self, position: Union[str, int, float]) -> int:
        """
        Check if left margin is exceeded for current page.

        @param position. Position to check.
        @return Revised position.
        """
        return self._parser_tools.ratio_correction_w(
            int(position)) + self._left_margin

    def calculateWidth(self,
                       width: int,
                       pos_x: int,
                       fix_ratio: bool = True) -> int:
        """
        Check if right margin is exceeded for current page.

        @param x. Position to check.
        @return Revised position.
        """
        limit = self._document.w - self._right_margin
        ret_: int

        if fix_ratio:
            width = self._parser_tools.ratio_correction_w(width)
            pos_x = self._parser_tools.ratio_correction_w(pos_x)
            ret_ = width
            if pos_x + width > limit:
                ret_ = limit - pos_x
        else:
            ret_ = width

        return ret_

    def processText(
        self,
        xml: Element,
        data_row: Optional[Element] = None,
        fix_height: bool = True,
        section_name: Optional[str] = None,
    ) -> None:
        """
        Check tag (calculated, label, special or image).

        @param xml. XML section to process.
        @param fix_height. Revise height from original .kut file except pageFooter.
        """
        is_image = False
        is_barcode = False
        text: str = xml.get("Text") or ""
        # borderColor = xml.get("BorderColor")
        field_name = xml.get("Field") or ""

        # x,y,W,H se calcula y corrigen aquí para luego estar correctos en los diferentes destinos posibles
        width = int(xml.get("Width") or "0")

        height = self._parser_tools.getHeight(xml)

        pos_x = int(xml.get("X") or "0")

        pos_y = (int(xml.get("Y") or "0") + self.topSection()
                 )  # Añade la altura que hay ocupada por otras secciones
        if fix_height:
            pos_y = self._parser_tools.ratio_correction_h(
                pos_y)  # Corrige la posición con respecto al kut original

        data_type = xml.get("DataType")

        if xml.tag == "Field" and data_row is not None:
            text = data_row.get(field_name) or ""

        elif xml.tag == "Special":
            if text == "":
                if xml.get("Type") == "1":
                    text = "PageNo"
            text = self._parser_tools.getSpecial(text,
                                                 self._actual_append_page_no)

        calculation_type = xml.get("CalculationType")

        if calculation_type is not None and xml.tag != "Field":
            if calculation_type == "6":
                function_name = xml.get("FunctionName")
                if function_name and data_row is not None:
                    try:
                        nodo = self._parser_tools.convertToNode(data_row)

                        ret_ = application.PROJECT.call(
                            function_name, [nodo, field_name], None, False)
                        if ret_ is False:
                            return
                        else:
                            text = str(ret_)

                    except Exception:
                        LOGGER.exception(
                            "KUT2FPDF:: Error llamando a function %s",
                            function_name)
                        return
                else:
                    return
            elif calculation_type == "1":
                text = self._parser_tools.calculate_sum(
                    field_name, self.last_data_processed, self._xml_data,
                    self.actual_data_level)

            elif calculation_type in ("5"):
                if data_row is None:
                    data_row = self._xml_data[0]

                text = data_row.get(field_name) or ""

        if data_type is not None:
            text = self._parser_tools.calculated(text, int(data_type),
                                                 xml.get("Precision"),
                                                 data_row)

        if data_type == "5":
            is_image = True

        elif data_type == "6":
            is_barcode = True

        if xml.get("BlankZero") == "1" and text is not None:
            res_ = re.findall(r"\d+", text)
            if res_ == ["0"]:
                return

        if text is not None:
            from pineboolib.core.settings import config

            temporal = config.value("ebcomportamiento/temp_dir")
            if text.startswith(temporal):
                is_image = True

        # negValueColor = xml.get("NegValueColor")
        # Currency = xml.get("Currency")
        #
        # commaSeparator = xml.get("CommaSeparator")
        # dateFormat = xml.get("DateFormat")

        if is_image:
            self.draw_image(pos_x, pos_y, width, height, xml, text)
        elif is_barcode:
            self.draw_barcode(pos_x, pos_y, width, height, xml, text)
        elif data_row is not None:
            level = data_row.get("level") or "0"
            if level and str(level) in self.detailn.keys():
                val = "%s_header_%s_%s" % (self.detailn[str(level)], level,
                                           field_name)

            if xml.get("DrawAtHeader") == "true" and level:
                if section_name == "DetailHeader":
                    val = ""
                    self.drawText(pos_x, pos_y, width, height, xml, val)

                    # print(level, section_name, val, text)

            if section_name == "DetailFooter" and xml.get(
                    "DrawAtHeader") == "true":
                self.draws_at_header[val] = text
                # print("Añadiendo a", val, text, level)

            else:
                self.drawText(pos_x, pos_y, width, height, xml, text)

    def drawText(self, pos_x: int, pos_y: int, width: int, height: int,
                 xml: Element, txt: str) -> None:
        """
        Draw a text field onto the page.

        @param pos_x. Label X Pos.
        @param pos_y. Label Y Pos.
        @param width. Label Width.
        @param height. Label Height.
        @param xml. Related XML Section
        @param txt. Computed text of the label to be created.
        """

        if txt in ("None", None):
            # return
            txt = ""

        if width == 0 and height == 0:
            return

        txt = self._parser_tools.restore_text(txt)

        resizeable = False

        if xml.get("ChangeHeight") == "1":
            resizeable = True

        # height_resized = False
        orig_x = pos_x
        orig_y = pos_y
        orig_w = width
        orig_h = height
        # Corregimos margenes:
        pos_x = self.calculateLeftStart(pos_x)
        width = self.calculateWidth(width, pos_x)

        # bg_color = xml.get("BackgroundColor").split(",")
        fg_color = self.get_color(xml.get("ForegroundColor") or "")
        self._document.set_text_color(fg_color[0], fg_color[1], fg_color[2])

        # self._document.set_draw_color(255, 255, 255)

        # if xml.get("BorderStyle") == "1":
        # FIXME: Hay que ajustar los margenes

        # font_name, font_size, font_style
        font_style = ""
        font_size = int(xml.get("FontSize") or "0")
        font_name_orig = ((xml.get("FontFamily") or "").lower() if
                          xml.get("FontFamily") is not None else "helvetica")
        font_name = font_name_orig

        font_w = int(xml.get("FontWeight") or "50")

        if font_w == 50:  # Normal
            font_w = 100
        elif font_w >= 65:
            font_style += "B"
            font_w = 100

        font_italic = xml.get("FontItalic")
        font_underlined = xml.get(
            "FontUnderlined")  # FIXME: hay que ver si es así

        # background_color = self.get_color(xml.get("BackgroundColor"))
        # if background_color != [255,255,255]: #Los textos que llevan fondo no blanco van en negrita
        #    font_style += "B"

        if font_italic == "1":
            font_style += "I"

        if font_underlined == "1":
            font_style += "U"

        font_name = font_name.replace(" narrow", "")

        font_full_name = "%s%s" % (font_name, font_style)

        if font_full_name not in self._avalible_fonts:
            font_found: Optional[str] = None
            if font_full_name not in self._unavalible_fonts:
                font_found = self._parser_tools.find_font(
                    font_full_name, font_style)
            if font_found:
                if self.design_mode:
                    LOGGER.warning(
                        "KUT2FPDF::Añadiendo el tipo de letra %s %s (%s)",
                        font_name,
                        font_style,
                        font_found,
                    )
                self._document.add_font(font_name, font_style, font_found,
                                        True)
                self._avalible_fonts.append(font_full_name)

            else:
                if font_full_name not in self._unavalible_fonts:
                    if self.design_mode:
                        LOGGER.warning(
                            "KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica%s."
                            % (font_full_name, font_style))
                    self._unavalible_fonts.append(font_full_name)
                font_name = "helvetica"

        if font_name is not font_name_orig and font_name_orig.lower().find(
                "narrow") > -1:
            font_w = 85

        self._document.set_font(font_name, font_style, font_size)
        self._document.set_stretching(font_w)
        # Corregir alineación
        vertical_alignment = xml.get(
            "VAlignment")  # 0 izquierda, 1 centrado,2 derecha
        horizontal_alignment = xml.get("HAlignment")

        # layout_direction = xml.get("layoutDirection")

        start_section_size = self._actual_section_size
        result_section_size = 0
        # Miramos si el texto sobrepasa el ancho

        array_text: List[str] = []
        array_n = []
        text_lines = []
        if txt.find("\n") > -1:
            for line_text in txt.split("\n"):
                array_n.append(line_text)
        if array_n:  # Hay saltos de lineas ...
            for n in array_n:
                text_lines.append(n)
        else:  # No hay saltos de lineas
            text_lines.append(txt)

        for text_line in text_lines:
            if len(text_line) > 1:
                if text_line[0] == " " and text_line[1] != " ":
                    text_line = text_line[1:]
            str_width = self._document.get_string_width(text_line)
            if (
                    str_width > width - 10 and xml.tag != "Label"
                    and resizeable
            ):  # Una linea es mas larga que el ancho del campo(Le quito 10 al ancho maximo para que corte parecido a kugar original)
                # height_resized = True
                array_text = self.split_text(text_line, width - 10)
            else:

                array_text.append(text_line)

        # calculated_h = orig_h * len(array_text)
        self.drawRect(orig_x, orig_y, orig_w, orig_h, xml)

        processed_lines = 0
        extra_size = 0
        for actual_text in array_text:

            processed_lines += 1

            if processed_lines > 1:
                extra_size += font_size + 2

            if horizontal_alignment == "1":  # sobre X
                # Centrado
                pos_x = pos_x + (width / 2) - (
                    self._document.get_string_width(actual_text) / 2)
                # x = x + (width / 2) - (str_width if not height_resized else width / 2)
            elif horizontal_alignment == "2":

                # Derecha
                pos_x = (pos_x + width -
                         self._document.get_string_width(actual_text) - 2
                         )  # -2 de margen
                # x = x + width - str_width if not height_resized else width
            else:
                # Izquierda
                if processed_lines == 1:
                    pos_x = pos_x + 2

            if vertical_alignment == "1":  # sobre Y
                # Centrado
                # y = (y + ((H / 2) / processed_lines)) + (((self._document.font_size_pt / 2) / 2) * processed_lines)
                pos_y = int((orig_y + (orig_h / 2)) +
                            ((self._document.font_size_pt / 2) / 2))

                if len(array_text) > 1:
                    pos_y = pos_y - (font_size // 2)

            elif vertical_alignment == "2":
                # Abajo
                pos_y = orig_y + orig_h - font_size
            else:
                # Arriba
                pos_y = orig_y + font_size

            pos_y = pos_y + extra_size

            if self.design_mode:
                self.write_debug(
                    self.calculateLeftStart(orig_x),
                    pos_y,
                    "Hal:%s, Val:%s, T:%s st:%s" %
                    (horizontal_alignment, vertical_alignment, txt, font_w),
                    6,
                    "green",
                )
                if xml.tag == "CalculatedField":
                    self.write_debug(
                        self.calculateLeftStart(orig_x),
                        pos_y,
                        "CalculatedField:%s, Field:%s" %
                        (xml.get("FunctionName"), xml.get("Field")),
                        3,
                        "blue",
                    )

            self._document.text(pos_x, pos_y, actual_text)
            result_section_size += start_section_size

        result_section_size = result_section_size - start_section_size

        if (self.increase_section_size < extra_size
            ):  # Si algun incremento extra hay superior se respeta
            self.increase_section_size = extra_size

    def split_text(self, texto: str, limit_w: int) -> List[str]:
        """Split text into lines based on visual width."""
        list_ = []
        linea_: Optional[str] = None

        for parte in texto.split(" "):
            if linea_ is None and parte == "":
                continue

            if linea_ is not None:
                if self._document.get_string_width(linea_ + parte) > limit_w:
                    list_.append(linea_)
                    linea_ = ""
            else:
                linea_ = ""

            linea_ += "%s " % parte
        if linea_ is not None:
            list_.append(linea_)
        return list_

    def get_color(self, value: str) -> List[int]:
        """Convert color text into [r,g,b] array."""
        lvalue = value.split(",")
        red: int
        green: int
        blue: int
        if len(lvalue) == 3:
            red = int(lvalue[0])
            green = int(lvalue[1])
            blue = int(lvalue[2])
        else:
            red = int(value[0:2])
            green = int(value[3:5])
            blue = int(value[6:8])

        return [red, green, blue]

    def drawRect(self,
                 pos_x: int,
                 pos_y: int,
                 width: int,
                 height: int,
                 xml: Element = None) -> None:
        """
        Draw a rectangle in current page.

        @param pos_x. left side
        @param pos_y. top side
        @param width. width
        @param height. heigth
        """
        style_ = ""
        border_color = None
        bg_color = None
        line_width = self._document.line_width
        border_width = 0.2
        # Calculamos borde  y restamos del ancho
        orig_x = pos_x
        orig_y = pos_y
        orig_w = width

        pos_x = self.calculateLeftStart(orig_x)
        width = self.calculateWidth(width, pos_x)

        if xml is not None and not self.design_mode:
            if xml.get("BorderStyle") == "1":

                border_color = self.get_color(xml.get("BorderColor") or "")
                self._document.set_draw_color(border_color[0], border_color[1],
                                              border_color[2])
                style_ += "D"

            bg_color = self.get_color(xml.get("BackgroundColor") or "")
            self._document.set_fill_color(bg_color[0], bg_color[1],
                                          bg_color[2])
            style_ = "F" + style_

            border_width = int(
                xml.get("BorderWidth") or "0" if xml.get("BorderWidth"
                                                         ) else 0.2)
        else:
            self.write_cords_debug(pos_x, pos_y, width, height, orig_x, orig_w)
            style_ = "D"
            self._document.set_draw_color(0, 0, 0)

        if style_ != "":
            self._document.set_line_width(border_width)

            self._document.rect(pos_x, pos_y, width, height, style_)
            self._document.set_line_width(line_width)

            self._document.set_xy(orig_x, orig_y)
        # self._document.set_draw_color(255, 255, 255)
        # self._document.set_fill_color(0, 0, 0)

    def write_cords_debug(
        self,
        pos_x: Union[float, int],
        pos_y: Union[float, int],
        width: Union[float, int],
        height: Union[float, int],
        orig_x: Union[float, int],
        orig_w: Union[float, int],
    ) -> None:
        """Debug for Kut coordinated."""
        self.write_debug(
            int(pos_x),
            int(pos_y),
            "X:%s Y:%s W:%s H:%s orig_x:%s, orig_W:%s" % (
                round(pos_x, 2),
                round(pos_y, 2),
                round(width, 2),
                round(height, 2),
                round(orig_x, 2),
                round(orig_w, 2),
            ),
            2,
            "red",
        )

    def write_debug(self,
                    pos_x: int,
                    pos_y: int,
                    text: str,
                    height: int,
                    color: Optional[str] = None) -> None:
        """Write debug data into the report."""
        orig_color = self._document.text_color
        red = 0
        green = 0
        blue = 0
        current_font_family = self._document.font_family
        current_font_size = self._document.font_size_pt
        current_font_style = self._document.font_style
        if color == "red":
            red = 255
        elif color == "green":
            green = 255
        elif color == "blue":
            blue = 255

        self._document.set_text_color(red, green, blue)
        self._document.set_font_size(4)
        self._document.text(pos_x, pos_y + height, text)
        self._document.text_color = orig_color
        # self._document.set_xy(orig_x, orig_y)
        self._document.set_font(current_font_family, current_font_style,
                                current_font_size)

    def draw_image(self, pos_x: int, pos_y: int, width: int, height: int,
                   xml: Element, file_name: str) -> None:
        """
        Draw image onto current page.

        @param pos_x. left position
        @param pos_y. top position
        @param width. width
        @param height. heigth
        @param xml. Related XML section
        @param file_name. filename of temp data to use
        """
        import os

        if not file_name.lower().endswith(".png"):
            file_name_ = self._parser_tools.parseKey(file_name)
            if file_name_ is None:
                return
            file_name = file_name_

        if os.path.exists(file_name):
            pos_x = self.calculateLeftStart(pos_x)
            width = self.calculateWidth(width, pos_x)

            self._document.image(file_name, pos_x, pos_y, width, height, "PNG")

    def draw_barcode(self, pos_x: int, pos_y: int, width: int, height: int,
                     xml: Element, text: str) -> None:
        """
        Draw barcode onto currrent page.
        """
        if text == "None":
            return
        from pineboolib.fllegacy import flcodbar

        file_name = application.PROJECT.tmpdir
        file_name += "/%s.png" % (text)
        codbartype = xml.get("CodBarType")

        if not os.path.exists(file_name):

            bar_code = flcodbar.FLCodBar(text)  # Code128
            if codbartype is not None:
                type: int = bar_code.nameToType(codbartype.lower())
                bar_code.setType(type)

            bar_code.setText(text)

            pix = bar_code.pixmap()
            if not pix.isNull():
                pix.save(file_name, "PNG")

        self.draw_image(pos_x + 10, pos_y, width - 20, height, xml, file_name)

    def setPageFormat(self, xml: Element) -> None:
        """
        Define page parameters.

        @param xml: XML with KUT data
        """
        custom_size = None

        self._bottom_margin = int(xml.get("BottomMargin") or "0")
        self._left_margin = int(xml.get("LeftMargin") or "0")
        self._right_margin = int(xml.get("RightMargin") or "0")
        self._top_margin = int(xml.get("TopMargin") or "0")

        page_size = int(xml.get("PageSize") or "0")
        page_orientation = xml.get("PageOrientation") or "0"

        if page_size in [30, 31]:
            custom_size = [
                int(xml.get("CustomHeightMM") or "0"),
                int(xml.get("CustomWidthMM") or "0"),
            ]

        self._page_orientation = "P" if page_orientation == "0" else "L"
        self._page_size = self._parser_tools.convertPageSize(
            page_size, int(page_orientation), custom_size)  # devuelve un array

    def draw_margins(self) -> None:
        """Draw margins on the report."""
        self.draw_debug_line(0 + self._left_margin, 0, 0 + self._left_margin,
                             self._page_size[1])  # Vertical derecha
        self.draw_debug_line(
            self._page_size[0] - self._right_margin,
            0,
            self._page_size[0] - self._right_margin,
            self._page_size[1],
        )  # Vertical izquierda
        self.draw_debug_line(0, 0 + self._top_margin, self._page_size[0],
                             0 + self._top_margin)  # Horizontal superior
        self.draw_debug_line(
            0,
            self._page_size[1] - self._bottom_margin,
            self._page_size[0],
            self._page_size[1] - self._bottom_margin,
        )  # Horizontal inferior

    def draw_debug_line(
        self,
        pos_x1: int,
        pos_y1: int,
        pos_x2: int,
        pos_y2: int,
        title: Optional[str] = None,
        color: str = "GREY",
    ) -> None:
        """Draw a debug line on the report."""
        dash_length = 2
        space_length = 2

        red = 0
        green = 0
        blue = 0
        if color == "GREY":
            red = 220
            green = 220
            blue = 220
        self._document.set_line_width(1)
        self._document.set_draw_color(red, green, blue)
        self._document.dashed_line(pos_x1, pos_y1, pos_x2, pos_y1, dash_length,
                                   space_length)

    def number_pages(self) -> int:
        """Get number of pages on the report."""
        return self._actual_append_page_no if self._actual_append_page_no > 0 else 0

    def reset_page_no(self) -> None:
        """Reset page number."""
        self._actual_append_page_no = -1
示例#7
0
class kut2fpdf(object):

    _document = None  # Aquí se irán guardando los datos del documento
    logger = None
    _xml = None
    _xml_data = None
    _page_orientation = None
    _page_size = None
    _bottom_margin = None
    _left_margin = None
    _right_margin = None
    _top_margin = None
    _page_top = {}
    _data_row = None  # Apunta a la fila actual en data
    _parser_tools = None
    _avalible_fonts = []

    def __init__(self):

        self.logger = logging.getLogger("kut2rml")
        checkDependencies({"fpdf": "fpdf"})
        from pineboolib.plugins.kugar.parsertools import parsertools
        self._parser_tools = parsertools()

    """
    Convierte una cadena de texto que contiene el ".kut" en un pdf y retorna la ruta a este último.
    @param name. Nombre de ".kut".
    @param kut. Cadena de texto que contiene el ".kut".
    @param data. Cadena de texto que contiene los datos para ser rellenados en el informe.
    @return Ruta a fichero pdf.
    """

    def parse(self, name, kut, data):

        try:
            self._xml = self._parser_tools.loadKut(kut)
        except Exception:
            self.logger.exception(
                "KUT2FPDF: Problema al procesar %s.kut", name)
            return False

        try:
            self._xml_data = load2xml(data)
        except Exception:
            self.logger.exception("KUT2FPDF: Problema al procesar xml_data")
            return False

        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =

        from fpdf import FPDF
        self._document = FPDF(self._page_orientation, "pt", self._page_size)
        # Seteamos rutas a carpetas con tipos de letra ...

        # Cargamos las fuentes disponibles
        for f in self._document.core_fonts:
            self.logger.debug("KUT2FPDF :: Adding font %s", f)
            self._avalible_fonts.append(f)

        self.newPage()
        self.processDetails()

        pdfname = pineboolib.project.getTempDir()
        pdfname += "/%s_%s.pdf" % (name, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))

        # Datos del creador del documento
        self._document.set_title(name)
        self._document.set_author("Pineboo - kut2fpdf plugin")

        self._document.output(pdfname, 'F')

        return pdfname

    """
    Indica el techo para calcular la posición de los objetos de esa sección.
    @return Número con el techo de la página actual.
    """

    def topSection(self):
        return self._page_top[str(self._document.page_no())]

    """
    Actualiza el valor del techo de la página actual. Se suele actualizar al procesar una sección.
    @param value. Numero que elspecifica el nuevo techo.
    """

    def setTopSection(self, value):
        self._page_top[str(self._document.page_no())] = value

    """
    Añade una nueva página al documento.
    """

    def newPage(self):
        self._document.add_page(self._page_orientation)
        self._page_top[str(self._document.page_no())] = self._top_margin
        self._document.set_margins(self._left_margin, self._top_margin,
                                   self._right_margin)  # Lo dejo pero no se nota nada
        # Corta con el borde inferior ...
        # self._document.set_auto_page_break(
        #    True, self._document.h - self._bottom_margin)

        self.processSection("PageHeader")
    """
    Procesa las secciones details con sus correspondientes detailHeader y detailFooter.
    """

    def processDetails(self):
        # Procesamos la cabecera si procede ..
        prevLevel = 0
        level = None
        for data in self._xml_data.findall("Row"):
            level = int(data.get("level"))
            if prevLevel > level:
                self.processData("DetailFooter", data, prevLevel)
            elif prevLevel < level:
                self.processData("DetailHeader",  data, level)

            self.processData("Detail", data, level)

            prevLevel = level

        if level:
            for l in reversed(range(level + 1)):
                self.processData("DetailFooter", data, l)

        if self._xml.find("PageFooter"):
            self.processSection("PageFooter")
        elif self._xml.find("AddOnFooter"):
            self.processSection("AddOnFooter")

    """
    Paso intermedio que calcula si detailHeader + detail + detailFooter entran en el resto de la ṕagina. Si no es así crea nueva página.
    @param section_name. Nombre de la sección a procesar.
    @param data. Linea de datos a procesar.
    @param data_level. Nivel de seccion.
    """

    def processData(self, section_name, data, data_level):
        listDF = self._xml.findall(section_name)
        for dF in listDF:
            if dF.get("Level") == str(data_level):
                if section_name == "Detail" and (not dF.get("DrawIf") or data.get(dF.get("DrawIf"))):
                    heightCalculated = self._parser_tools.getHeight(dF) + self.topSection()
                    for dFooter in self._xml.findall("DetailFooter"):
                        if dFooter.get("Level") == str(data_level):
                            heightCalculated += self._parser_tools.getHeight(dFooter)
                    pageFooter = self._xml.get("PageFooter")
                    if pageFooter:
                        if self._document.page_no() == 1 or pageFooter.get("PrintFrecuency") == "1":
                            heightCalculated += self._parser_tools.getHeight(pageFooter)

                    heightCalculated += self._bottom_margin

                    if heightCalculated > self._document.h:  # Si nos pasamos
                        self.processSection("PageFooter")  # Pie de página
                        self.newPage()

                if not dF.get("DrawIf") or data.get(dF.get("DrawIf")):
                    self.processXML(dF, data)
                    #self.logger.debug("%s_BOTTON = %s" % (name.upper(), self.actualVSize[str(self.pagina)]))

    """
    Procesa las secciones fuera de detail, pageHeader, pageFooter, AddOnFooter.
    @param name. Nombre de la sección a procesar.
    """

    def processSection(self, name):
        sec_ = self._xml.find(name)
        if sec_:
            if sec_.get("PrintFrequency") == "1" or self._document.page_no() == 1:
                if sec_.tag == "PageFooter":
                    self.setTopSection(self._document.h - int(sec_.get("Height")))
                self.processXML(sec_)

    """
    Procesa un elemento de xml.
    @param xml: El elemento a procesar.
    @param. data: Linea de datos afectada.
    """

    def processXML(self, xml, data=None):
        fix_height = True
        if xml.tag == "DetailFooter":
            if xml.get("PlaceAtBottom") == "true":
                self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml))

        if xml.tag == "PageFooter":
            fix_height = False

        for child in xml.iter():
            if child.tag in ("Label", "Field", "Special", "CalculatedField"):
                self.processText(child, data, fix_height)
            elif child.tag == "Line":
                self.processLine(child, fix_height)

        if xml.get("PlaceAtBottom") != "true":
            self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml))

    """
    Procesa una linea.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processLine(self, xml, fix_height=True):

        color = xml.get("Color")
        r = 0 if not color else int(color.split(",")[0])
        g = 0 if not color else int(color.split(",")[1])
        b = 0 if not color else int(color.split(",")[2])

        #style = int(xml.get("Style"))
        width = int(xml.get("Width"))
        X1 = self.calculateLeftStart(xml.get("X1"))
        X2 = self.calculateRightEnd(xml.get("X2"))
        # Ajustar altura a secciones ya creadas
        Y1 = int(xml.get("Y1")) + self.topSection()
        Y2 = int(xml.get("Y2")) + self.topSection()
        if fix_height:
            Y1 = self._parser_tools.heightCorrection(Y1)
            Y2 = self._parser_tools.heightCorrection(Y2)
        self._document.set_line_width(width)
        self._document.set_draw_color(r, g, b)
        self._document.line(X1, Y1, X2, Y2)

    """
    Comprueba si excedemos el margen izquierdo de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateLeftStart(self, x):
        x = int(x)
        ret_ = x
        if x < self._left_margin:
            ret_ = self._left_margin

        return ret_

    """
    Comprueba si excedemos el margen derecho de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateRightEnd(self, x):
        x = int(x)
        ret_ = x
        if x > (self._document.w - self._right_margin):
            ret_ = self._document.w - self._right_margin

        return ret_

    """
    Procesa una etiqueta. Esta peude ser un campo calculado, una etiqueta, un campo especial o una imagen.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processText(self, xml, data_row=None, fix_height=True):
        isImage = False
        text = xml.get("Text")
        BorderWidth = int(xml.get("BorderWidth"))
        borderColor = xml.get("BorderColor")

        # x,y,W,H se calcula y corrigen aquí para luego estar correctos en los diferentes destinos posibles
        W = int(xml.get("Width"))
        H = self._parser_tools.getHeight(xml)

        x = int(xml.get("X"))
        y = int(xml.get("Y")) + self.topSection()  # Añade la altura que hay ocupada por otras secciones
        if fix_height:
            y = self._parser_tools.heightCorrection(y)  # Corrige la posición con respecto al kut original

        dataType = xml.get("Datatype")

        if xml.tag == "Field" and data_row is not None:
            text = data_row.get(xml.get("Field"))

        elif xml.tag == "Special":
            text = self._parser_tools.getSpecial(
                text[1:len(text) - 1], self._document.page_no())

        elif xml.tag == "CalculatedField":
            if xml.get("FunctionName"):
                function_name = xml.get("FunctionName")
                try:
                    nodo = self._parser_tools.convertToNode(data_row)
                    text = str(pineboolib.project.call(function_name, [nodo]))
                except Exception:
                    self.logger.exception(
                        "KUT2FPDF:: Error llamando a function %s", function_name)
                    return
            else:
                if data_row is None:
                    data_row = self._xml_data[0]
                if xml.get("Field"):
                    text = data_row.get(
                        xml.get("Field")) if not "None" else ""

            if text and dataType is not None:
                text = self._parser_tools.calculated(text, int(dataType), xml.get("Precision"), data_row)

            if dataType == "5":
                isImage = True

        if text and text.startswith(filedir("../tempdata")):
            isImage = True

        precision = xml.get("Precision")
        negValueColor = xml.get("NegValueColor")
        Currency = xml.get("Currency")

        commaSeparator = xml.get("CommaSeparator")
        dateFormat = xml.get("DateFormat")

        if not isImage:

            self.drawText(x, y, W, H, xml, text)
        else:
            self.drawImage(x, y, W, H, xml, text)

    """
    Dibuja un campo texto en la página.
    @param x. Pos x de la etiqueta.
    @param y. Pos y de la etiqueta.
    @param W. Anchura de la etiqueta.
    @param H. Altura de la etiqueta.
    @param xml. Sección del xml afectada.
    @param txt. Texto calculado de la etiqueta a crear.
    """

    def drawText(self, x, y, W, H, xml, txt):

        if txt in ("None", None):
            return

        # Corregimos margenes:
        x = self.calculateLeftStart(x)
        W = self.calculateRightEnd(x + W) - x

        bg_color = xml.get("BackgroundColor").split(",")
        fg_color = xml.get("ForegroundColor").split(",")

        self._document.set_text_color(int(fg_color[0]), int(fg_color[1]), int(fg_color[2]))
        self._document.set_fill_color(int(bg_color[0]), int(bg_color[1]), int(bg_color[2]))

        if xml.get("BorderStyle") == "1":
            # FIXME: Hay que ajustar los margenes
            self.drawRect(x, y, W, H)

        #font_name, font_size, font_style
        font_style = ""
        font_size = int(xml.get("FontSize"))
        font_name = xml.get("FontFamily").lower()

        fontW = int(xml.get("FontWeight"))
        fontI = xml.get("FontItalic")
        fontU = xml.get("FontUnderlined")  # FIXME: hay que ver si es así

        if fontW > 60 and font_size > 10:
            font_style += "B"

        if fontI == "1":
            font_style += "I"

        if fontU == "1":
            font_style += "U"

        while font_name not in self._avalible_fonts:
            font_found = self._parser_tools.find_font(font_name)
            if font_found:
                self.logger.info("KUT2FPDF::Añadiendo el tipo de letra %s (%s)", font_name, font_found)
                self._document.add_font(font_name, "", font_found, True)
                self._avalible_fonts.append(font_name)

            else:
                self.logger.warning("KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica.", font_name)
                font_name = "helvetica"

        self._document.set_font(font_name, font_style, font_size)

        # Corregir alineación
        VAlignment = xml.get("VAlignment")  # 0 izquierda, 1 centrado,2 derecha
        HAlignment = xml.get("HAlignment")

        if HAlignment == "1":  # sobre X
            # Centrado
            x = x + (W / 2) - (self._document.get_string_width(txt) / 2)
        elif HAlignment == "2":
            # Derecha
            x = x + W - self._document.get_string_width(txt)
        else:
            # Izquierda
            x = x

        if VAlignment == "1":  # sobre Y
            # Centrado
            y = (y + H / 2) + (self._document.font_size_pt / 2)
        elif VAlignment == "2":
            # Abajo
            y = y + W - font_size
        else:
            # Arriba
            y = y

        self._document.text(x, y, txt)

    """
    Dibuja un cuadrado en la página actual.
    @param x. Pos x del cuadrado.
    @param y. Pos y del cuadrado.
    @param W. Anchura del cuadrado.
    @param H. Altura del cuadrado.
    """

    def drawRect(self, x, y, W, H):
        self._document.rect(x, y, W, H, "DF")

    """
    Inserta una imagen en la página actual.
    @param x. Pos x de la imagen.
    @param y. Pos y de la imagen.
    @param W. Anchura de la imagen.
    @param H. Altura de la imagen.
    @param xml. Sección del xml afectada.
    @param file_name. Nombr del fichero de tempdata a usar
    """

    def drawImage(self, x, y, W, H, xml, file_name):

        self._document.image(file_name, x, y, W, H, "PNG")
    """
    Define los parámetros de la página
    @param xml: Elemento xml con los datos del fichero .kut a procesar
    """

    def setPageFormat(self, xml):
        custom_size = None

        self._bottom_margin = int(xml.get("BottomMargin"))
        self._left_margin = int(xml.get("LeftMargin"))
        self._right_margin = int(xml.get("RightMargin"))
        self._top_margin = int(xml.get("TopMargin"))

        page_size = int(xml.get("PageSize"))
        page_orientation = xml.get("PageOrientation")

        if page_size in [30, 31]:
            custom_size = [int(xml.get("CustomHeightMM")), int(xml.get("CustomWidthMM"))]

        self._page_orientation = "P" if page_orientation == "0" else "L"
        self._page_size = self._parser_tools.converPageSize(
            page_size, int(page_orientation), custom_size)  # devuelve un array
示例#8
0
def menu():
    month, year = util.valid_month_year()

    if year == 0:
        return

    regcard: Card = Card.validcard(0)  # SEARCH
    regsynd, regcomp = Company.validcompany(0)

    conn = Database.conn
    cursor = Database.cursor

    filepdf = FPDF('P', 'mm', 'A4')  # Portrait

    dtini, dtfinal = util.first_last_day(month, year)

    data: cursor = Pouch.finddate(dtini, dtfinal, regcard.codeCard,
                                  regsynd.codeSynd, regcomp.codeComp)

    if len(data) == 0:
        print("\33[1;31mDon't have register\33[m")
    else:
        filepdf.add_page()
        filepdf.set_font('Arial', '', 10)
        filepdf.cell(190, 4, 'Página ' + str(filepdf.page_no()), 0, 1, 'R')
        filepdf.set_font('Arial', 'B', 16)
        filepdf.cell(
            190, 4,
            'Monthly Report - ' + str(month) + '/' + str(year) + '          ' +
            datetime.strftime(datetime.today().now(), '%m/%d/%Y %H:%M'), 0, 1,
            'C')
        filepdf.set_font('Courier', '', 10)
        filepdf.cell(190, 4, ' ', 0, 1, 'R')
        # 60 = weight 20 = height by cell 0 = border 1 = break line L = align
        subtitle = '   Date    Pouch      Card       Syndicate       Company        Quant  Value'
        filepdf.set_font('Courier', '', 10)
        filepdf.cell(190, 4, subtitle, 0, 1, 'L')
        contline = 2
        for reg in data:
            dtarrived = reg[0]
            codepouch = reg[1]
            namecard = reg[2]
            namesynd = reg[3]
            namecomp = reg[4]
            quant = reg[5]
            value = reg[6]

            if contline > 59:
                filepdf.add_page()
                filepdf.set_font('Arial', '', 10)
                filepdf.cell(190, 4, 'Página ' + str(filepdf.page_no()), 0, 1,
                             'R')
                subtitle = 'Arrived    Pouch      Card       Syndicate       Company        Quant  Value'
                filepdf.set_font('Courier', '', 10)
                filepdf.cell(190, 4, subtitle, 0, 1, 'L')
                contline = 2

            contline += 1

            filepdf.cell(
                210, 4, f'{dtarrived} {codepouch:<10} {namecard:<10} '
                f'{namesynd:<15} {namecomp:<15} {quant:>4} {value:>6.2f}', 0,
                1, 'L')
        try:
            filepdf.output(f'ReportMonthly_{year}{month:0>2}.pdf',
                           'F')  # D - Web   F- Local
            print('Generated Report')
        except Exception:
            print('\33[1;31mThe file pdf is open\33[m')

    return
示例#9
0
def setava_01(self, stock_taking):
    comp = list(self.mdb.stock.find().sort([("category", 1), ("_id", 1)]))
    autori = stock_taking['author'].strip().split(',')
    datum = str(stock_taking['closed'].date())
    filename = "{}_{}.pdf".format(stock_taking['_id'],
                                  ''.join(stock_taking['name'].split()))

    print("Generovani prehledu inventury")
    print("Od:", autori)
    print("Kdy:", datum)
    print("Soubor,", filename)

    page = 1
    money_sum = 0
    Err = []

    pdf = FPDF('P', 'mm', format='A4')
    pdf.set_auto_page_break(False)

    pdf.add_font('pt_sans',
                 '',
                 'static/pt_sans/PT_Sans-Web-Regular.ttf',
                 uni=True)
    pdf.add_font('pt_sans-bold',
                 '',
                 'static/pt_sans/PT_Sans-Web-Bold.ttf',
                 uni=True)
    pdf.set_font('pt_sans', '', 12)
    pdf.add_page()

    pdf.set_xy(0, 40)
    pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
    pdf.set_xy(0, 46)
    pdf.cell(pdf.w,
             0,
             'Universal Scientific Technologies s.r.o.',
             align='C',
             ln=2)

    pdf.set_xy(20, 200)
    pdf.cell(1, 0, 'Inventuru provedli:', ln=2)
    for x in autori:
        pdf.cell(1, 20, x, ln=2)

    pdf.set_font('pt_sans', '', 8)
    pdf.set_xy(120, 288)
    pdf.cell(
        10, 0, "Vytvořeno %s, strana %s z %s" %
        (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"), page,
         pdf.alias_nb_pages()))

    pdf.add_page()

    data = self.mdb.stock.aggregate([{
        '$addFields': {
            'count': {
                '$sum': '$history.bilance'
            }
        }
    }])

    query = [
        {
            "$group": {
                '_id': '$pid',
                'operations': {
                    "$push": "$$ROOT"
                }
            }
        },
        {
            "$addFields": {
                "packet_count": {
                    "$sum": "$operations.count"
                },
                "packet_reserv": {
                    "$sum": "$operations.reserv"
                },
                "packet_ordered": {
                    "$sum": "$operations.ordered"
                },
                "packet_price": {
                    "$function": {
                        "body": '''function(prices, counts) {
                         let total_counts = Array.sum(counts);
                         var tmp_count = total_counts;
                         var total_price = 0;

                         var c = counts.reverse();
                         var p = prices.reverse();

                         for(i in c){
                             if(c[i] > 0){
                                 if(c[i] < tmp_count){
                                     total_price += (c[i]*p[i]);
                                     tmp_count -= c[i]
                                  }
                                  else{
                                     total_price += (tmp_count*p[i]);
                                     tmp_count = 0;
                                  }
                            }

                         }
                         return total_price;
                        }''',
                        "args":
                        ["$operations.unit_price", "$operations.count"],
                        "lang": "js"
                    }
                }
            }
        },
        #{"$addFields": {"comp": "$pid"}},
        {
            "$lookup": {
                "from":
                "stock",
                "let": {
                    "pid": "$_id"
                },
                "pipeline": [
                    {
                        "$match": {
                            "$expr": {
                                "$in": ["$$pid", "$packets._id"]
                            }
                        }
                    },
                    {
                        "$unwind": "$packets"
                    },
                    {
                        "$match": {
                            "$expr": {
                                "$eq": ["$packets._id", "$$pid"]
                            }
                        }
                    },
                ],
                "as":
                "component"
            }
        },
        {
            "$set": {
                "component": {
                    "$first": "$component"
                }
            }
        },
        {
            "$lookup": {
                "from": "store_positions_complete",
                "localField": "component.packets.position",
                "foreignField": "_id",
                "as": "position_info",
            }
        },
        {
            "$set": {
                "position_info": {
                    "$first": "$position_info"
                }
            }
        },
        {
            "$group": {
                '_id': '$component._id',
                'packets': {
                    "$push": "$$ROOT"
                },
                #'component': { "$push": "$component" }
            }
        },
        {
            "$sort": {
                "_id": 1
            }
        }

        #{ "$sort": {"position_info.warehouse.code": 1, "position_info.path_string": 1, "position_info.name": 1, "component.name":1}},

        #{ "$project": { "packet_count": 1, "packet_reserv": 1, "packet_price": 1, "packet_ordered": 1, "_id": 0} },
        # { "$group": {
        #     '_id': 'null',
        #     'count': {"$sum": '$packet_count'},
        #     'price': {"$sum": '$packet_price'},
        #     'reserv': {"$sum": '$packet_reserv'},
        #     'ordered': {"$sum": '$packet_ordered'},
        #     }
        # }
    ]
    data = self.mdb.stock_operation.aggregate(query)

    gen_time = datetime.datetime(2018, 10, 1)
    lastOid = ObjectId.from_datetime(gen_time)

    number_components = 0
    number_packets = 0

    for i, component in enumerate(data):
        print(" ")
        number_components += 1
        # print(component['_id'], component)
        component['packets_count'] = []
        component['packets_prices'] = []
        try:
            ## Pokud je konec stránky
            if pdf.get_y() > pdf.h - 20:
                pdf.line(10, pdf.get_y() + 0.5, pdf.w - 10, pdf.get_y() + 0.5)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(150, pdf.get_y() + 1)
                pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                pdf.add_page()

            ## Pokud je nová strana
            if page != pdf.page_no():
                pdf.set_font('pt_sans', '', 8)
                page = pdf.page_no()
                pdf.set_xy(120, 288)
                pdf.cell(
                    10, 0, "Vytvořeno %s, strana %s z %s" %
                    (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"),
                     page, pdf.alias_nb_pages()))

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(10, 10)
                pdf.cell(100, 5, 'Skladová položka')
                pdf.set_x(105)
                pdf.cell(10, 5, "Počet kusů", align='R')
                #pdf.set_x(120)
                #pdf.cell(10, 5, "Cena za 1ks", align='R')
                pdf.set_x(180)
                pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                pdf.line(10, 15, pdf.w - 10, 15)
                pdf.set_y(18)
                page_sum = 0

            pdf.set_font('pt_sans', '', 10)

            count = 0
            price = 0
            packets = ""
            for j, packet in enumerate(component['packets']):
                number_packets += 1
                pcount = packet['packet_count']
                pprice = round(packet['packet_price'], 2)

                component['packets_count'].append(pcount)
                component['packets_prices'].append(pprice)

                count += pcount
                price += pprice
                packets += " {},".format(pprice)

                #pac_info = get_packet_count(self.mdb, packet['_id'])
                #print("C: {}, {}, ".format(pcount-pac_info['packet_count'], pprice-pac_info['packet_price']))
            price_ks = 0
            first_price = 0

            inventura = False

            if count > 0:

                money_sum += price
                page_sum += price

                if price == 0.0:  # and x.get('count', 0) > 0:
                    Err.append(
                        'Polozka >%s< nulová cena, nenulový počet (%s)' %
                        (component['_id'], component.get('name', '---')))

                pdf.set_x(10)
                pdf.cell(
                    100, 5,
                    "{:5.0f}  {} ({})".format(i, packet['component']['name'],
                                              len(component['packets'])))

                pdf.set_font('pt_sans', '', 10)
                pdf.set_x(105)
                pdf.cell(10, 5, "{} j".format(count), align='R')

                # pdf.set_x(107)
                # pdf.cell(10, 5, repr(component['packets_count']) + " " +repr(component['packets_prices']), align='L')

                pdf.set_font('pt_sans-bold', '', 10)
                pdf.set_x(180)
                pdf.cell(10, 5, "%6.2f Kč" % (price), align='R')

        except Exception as e:
            Err.append('Err' + repr(e) + repr(component['_id']))
            print(e)

        if count > 0:
            pdf.set_y(pdf.get_y() + 4)

    pdf.line(10, pdf.get_y(), pdf.w - 10, pdf.get_y())
    pdf.set_font('pt_sans', '', 8)
    pdf.set_x(180)
    pdf.cell(10, 5, "Konec souhrnu", align='R')

    print("Celková cena", money_sum)
    print("Probematicke", len(Err))
    print("Polozek:", number_components)
    print("Pocet sacku:", number_packets)

    pdf.page = 1
    pdf.set_xy(20, 175)
    pdf.set_font('pt_sans', '', 12)
    pdf.cell(
        20, 20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %
        (datum, money_sum))
    if len(Err) > 0:
        pdf.set_xy(30, 80)
        pdf.cell(1, 6, "Pozor, chyby ve skladu:", ln=2)
        pdf.set_x(32)
        for ch in Err:
            pdf.cell(1, 5, ch, ln=2)
    pdf.page = page

    pdf.output("static/tmp/sestava.pdf")
    year = datum[:4]

    filename = "{}.pdf".format(''.join(stock_taking['name'].split(' ')))
    foldername = os.path.join(tornado.options.options.owncloud_root,
                              'accounting', year, 'stocktaking', filename)
    foldername = save_file(self.mdb, foldername)
    return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
示例#10
0
    def get(self, data = None):
        out_type = self.get_argument('type', 'html')
        components = []
        components = self.get_query_arguments('action[]', [])
        multiply = int(self.get_argument('multiply', 5))
        layout = self.get_argument('template', '70x40_simple')
        skip = int(self.get_argument('skip', 0))
        #print("Soucastky..",components)
        if len(components) > 0:
            comp = list(self.mdb.stock.find({'_id' : {'$in' : components}}))
        else:
            comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)]))
        page = 0
        #print("Budeme tisknout:", comp)

        if layout == 'souhrn_01':
            autori = self.get_query_argument('autor', None)
            if not autori: autori = ['autory vlozite pridanim autoru do adresy s parametrem "autor"', 'autoru muze byt vice, pouzijte vice parametru', 'Například pridanim tohoto na konec adresy: &autor=Tester První']
            datum = self.get_argument('datum', ">>pro specifikovani pridejte parametr 'datum' do GET parametru<<")
            page = 1
            money_sum = 0
            Err = []

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')
            pdf.set_auto_page_break(False)

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans', '', 12)
            pdf.add_page()

            pdf.set_xy(0, 40)
            pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
            pdf.set_xy(0, 46)
            pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2)

            pdf.set_xy(20, 200)
            pdf.cell(1,0, 'Inventuru provedli:', ln=2)
            for x in autori:
                pdf.cell(1,20, x, ln=2)

            pdf.set_font('pt_sans', '', 8)
            pdf.set_xy(120, 288)
            pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

            pdf.add_page()


            data = self.mdb.stock.aggregate([
                    {'$addFields': {'count': {'$sum': '$history.bilance'}}}
                ])


            gen_time = datetime.datetime(2018, 10, 1)
            lastOid = ObjectId.from_datetime(gen_time)


            for i, component in enumerate(data):
            #for i, component in enumerate(list(data)[:30]):
                print(i, "=============================")
                print(component['_id'])
                try:
                    ## Pokud je konec stránky
                    if pdf.get_y() > pdf.h-20:
                        pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5)

                        pdf.set_font('pt_sans', '', 10)
                        pdf.set_xy(150, pdf.get_y()+1)
                        pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                        pdf.add_page()

                    ## Pokud je nová strana
                    if page != pdf.page_no():
                        pdf.set_font('pt_sans', '', 8)
                        page = pdf.page_no()
                        pdf.set_xy(120, 288)
                        pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

                        pdf.set_font('pt_sans', '', 11)
                        pdf.set_xy(10, 10)
                        pdf.cell(100, 5, 'Skladová položka')
                        pdf.set_x(95)
                        pdf.cell(10, 5, "Počet kusů", align='R')
                        pdf.set_x(120)
                        pdf.cell(10, 5, "Cena za 1ks", align='R')
                        pdf.set_x(180)
                        pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                        pdf.line(10, 15, pdf.w-10, 15)
                        pdf.set_y(18)
                        page_sum = 0

                    pdf.set_font('pt_sans', '', 10)

                    count = component['count']

                    if count >0:
                        price = 0
                        price_ks = 0
                        first_price = 0


                        pdf.set_x(10)
                        pdf.cell(100, 5, component['_id'])

                        pdf.set_x(95)
                        pdf.cell(10, 5, "%5.d" %(count), align='R')

                    pdf.set_x(10)
                    pdf.cell(100, 5, "{:5.0f}  {}".format(i, component['_id']))


                    inventura = False
                    for x in reversed(component.get('history', [])):
                        if x.get('operation', None) == 'inventory':
                            print("inventura", x)
                            if x['_id'].generation_time > lastOid.generation_time:
                                print("#############")
                                inventura = True
                                count = x['absolute']

                                pdf.set_x(110)
                                pdf.cell(1, 5, "i")
                                break;

                    pdf.set_font('pt_sans', '', 10)
                    pdf.set_x(95)
                    pdf.cell(10, 5, "{} j".format(count), align='R')

                    rest = count

                    for x in reversed(component.get('history', [])):

                        if x.get('price', 0) > 0:
                            if first_price == 0:
                                first_price = x['price']
                            if x['bilance'] > 0:
                                if x['bilance'] <= rest:
                                    price += x['price']*x['bilance']
                                    rest -= x['bilance']
                                else:
                                    price += x['price']*rest
                                    rest = 0

                    print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price)
                    if(count-rest): price += rest*first_price
                    money_sum += price
                    page_sum +=price

                    if price == 0.0 and x.get('count', 0) > 0:
                        Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id']))

                    pdf.set_x(120)
                    if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R')
                    else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R')

                    pdf.set_font('pt_sans-bold', '', 10)
                    pdf.set_x(180)
                    pdf.cell(10, 5, "%6.2f Kč" %(price), align='R')


                except Exception as e:
                    Err.append('Err' + repr(e) + component['_id'])
                    print(e)

                pdf.set_y(pdf.get_y()+4)

            pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y())
            pdf.set_font('pt_sans', '', 8)
            pdf.set_x(180)
            pdf.cell(10, 5, "Konec souhrnu", align='R')

            pdf.set_font('pt_sans', '', 10)
            pdf.set_xy(150, pdf.get_y()+3)
            pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

            pdf.page = 1
            pdf.set_xy(20,175)
            pdf.set_font('pt_sans', '', 12)
            pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum))
            if len(Err) > 0:
                pdf.set_xy(30,80)
                pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2)
                pdf.set_x(32)
                for ch in Err:
                    pdf.cell(1,5,ch,ln=2)
            pdf.page = page

            print(autori)



        if layout == '105x74_simple':
            page = 0
            page_cols = 2
            page_rows = 4
            page_cells = page_cols * page_rows
            cell_w = 105
            cell_h = 75

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+5, cell_y+23)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        if layout == '70x42-3_simple':
            page = 0
            page_cols = 3
            page_rows = 7
            page_cells = page_cols * page_rows
            cell_w = 210/page_cols
            cell_h = 297/page_rows


            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['name'].strip().replace('/', '_')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                pdf.set_xy(cell_x+5, cell_y+6.75)
                if len(component['name'])<23:
                    pdf.set_font('pt_sans-bold', '', 14)
                else:
                    pdf.set_font('pt_sans-bold', '', 10)
                pdf.cell(cell_w-10, 0, component['name'][:35])
                pdf.set_xy(cell_x+2.5, cell_y+9)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w-5, h=7)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+4, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-8, 4, component['description'][:185])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-7)
                pdf.set_xy(cell_x+5, cell_y+13)
                pdf.set_font('pt_sans', '', 7.5)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " |" + str(datetime.date.today()) + "| " + component['_id'])



        if layout == '105x48_simple':
            page = 0
            page_cols = 2
            page_rows = 6
            page_cells = page_cols * page_rows
            #cell_w = 105
            #cell_h = 48
            cell_w = 210/page_cols
            cell_h = 297/page_rows

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(cell_x+5, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 4, component['description'][:275])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 4, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-10)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        elif layout == '105x48_panorama':
            page = 0
            page_cols = 6
            page_rows = 2
            page_cells = page_cols * page_rows
            cell_w = 48
            cell_h = 105

            print ("pozadovany format je:", layout)
            pdf = FPDF('L', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+cell_h)
                pdf.rotate(90)
                pdf.image('static/barcode/%s.png'%(id), w = cell_h-5, h=10)
                pdf.rotate(0)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+8, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")



        pdf.output("static/tmp/sestava.pdf")
        with open('static/tmp/sestava.pdf', 'rb') as f:
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "inline; filename=UST_tiskova_sestava.pdf")
            self.write(f.read())
        f.close()
示例#11
0
    def download_jpg(self, url):
        base_eap = url.split('/')[0]
        eap_url_for_entry = url.replace('/', '_')
        combined_url = self.join_url(self.EAP_BASE_URL, base_eap,
                                     eap_url_for_entry)
        pg = 1
        can_go = True
        file_list = []
        if not os.path.exists(self.JPEG_PATH):
            os.makedirs(self.JPEG_PATH)
        while can_go:
            if self.type == 'p':
                dl_url = self.join_url(
                    combined_url,
                    str(pg) + '.jp2', 'full',
                    str(self.height) + ',' + str(self.DEFAULT_WIDTH),
                    str(self.rotation),
                    self.EAP_FILENAME + '?t=' + str(int(time.time() * 1000)))
            else:
                dl_url = self.join_url(
                    combined_url,
                    str(pg) + '.jp2', 'full',
                    str(self.DEFAULT_WIDTH) + ',' + str(self.height),
                    str(self.rotation),
                    self.EAP_FILENAME + '?t=' + str(int(time.time() * 1000)))
            print(dl_url)
            title = os.path.join(self.JPEG_PATH,
                                 eap_url_for_entry + '_' + str(pg) + '.jpg')
            if os.path.isfile(title):
                # if file exists, don't download iff next file also exists
                # note that this effectively means that we can't parallelize at a page level
                download_this = True
                while True:
                    new_title = os.path.join(
                        self.JPEG_PATH,
                        eap_url_for_entry + '_' + str(pg + 1) + '.jpg')
                    old_title = os.path.join(
                        self.JPEG_PATH,
                        eap_url_for_entry + '_' + str(pg) + '.jpg')
                    if os.path.isfile(new_title):
                        print('Skipping ' + old_title)
                        file_list.append(old_title)
                        pg = pg + 1
                        download_this = False
                    else:
                        break
                if not download_this:
                    continue
            pg = pg + 1
            print('Downloading ' + title)
            try:
                urllib.request.urlretrieve(dl_url, title)
                file_list.append(title)
            except HTTPError:
                can_go = False

        pdf = FPDF(orientation=self.type,
                   unit='pt',
                   format=(self.height + 50, self.DEFAULT_WIDTH + 50))
        pdf.add_page(orientation=self.type)

        for image in file_list:
            print('Adding ' + image + ' to PDF')
            if self.type == 'p':
                pdf.image(image, h=self.DEFAULT_WIDTH, w=self.height)
            else:
                pdf.image(image, h=self.height, w=self.DEFAULT_WIDTH)
        page_count = pdf.page_no()
        if not os.path.exists(self.PDF_PATH):
            os.makedirs(self.PDF_PATH)
        pdf.output(os.path.join(self.PDF_PATH, eap_url_for_entry + '.pdf'))

        if page_count > len(file_list):
            # delete pg 1
            infile = PyPDF2.PdfFileReader(
                os.path.join(self.PDF_PATH, eap_url_for_entry + '.pdf'))
            outfile = PyPDF2.PdfFileWriter()
            pg = 1
            print('Deleting blank page...')
            while pg < page_count:
                p = infile.getPage(pg)
                pg = pg + 1
                outfile.addPage(p)
            exists, eap_file = _helpers.page_exists(self.EAP_ARCHIVE_URL +
                                                    url.replace('/', '-'))
            if not exists:
                eap_filename = eap_url_for_entry
            else:
                eap_filename = eap_file.title.text.split('|')[0].strip()
                eap_filename = re.sub(r'[^\w]', '', eap_filename)
            with open(os.path.join(self.PDF_PATH, eap_filename + '.pdf'),
                      'wb') as f:
                outfile.write(f)
                print('Writing to ' + eap_filename + '.pdf')
                with open(self.EAP_DONE_FILENAME, 'a') as f:
                    f.write(url + '\n')
            if self.DELETE_ORIG_PDF:
                try:
                    os.remove(
                        os.path.join(self.PDF_PATH,
                                     eap_url_for_entry + '.pdf'))
                except OSError:
                    pass
示例#12
0
class kut2fpdf(object):

    _document = None  # Aquí se irán guardando los datos del documento
    logger = None
    _xml = None
    _xml_data = None
    _page_orientation = None
    _page_size = None
    _bottom_margin = None
    _left_margin = None
    _right_margin = None
    _top_margin = None
    _page_top = {}
    _data_row = None  # Apunta a la fila actual en data
    _parser_tools = None
    _avalible_fonts = None
    _unavalible_fonts = None
    design_mode = None
    _actual_data_line = None
    _no_print_footer = False
    _actual_section_size = None
    increase_section_size = None
    last_detail = False
    actual_data_level = None
    last_data_processed = None
    prev_level = None
    draws_at_header = None
    detailn = None
    name_ = None
    _actual_append_page_no = None
    reset_page_count = None

    def __init__(self):

        self.logger = logging.getLogger("kut2fpdf")
        checkDependencies({"fpdf": "pyfpdf"})
        from pineboolib.plugins.kugar.parsertools import parsertools
        self._parser_tools = parsertools()
        self._avalible_fonts = []
        self._unavalible_fonts = []
        self.design_mode = FLSettings().readBoolEntry("ebcomportamiento/kugar_debug_mode")
        self._actual_data_line = None
        self._no_print_footer = False
        self.increase_section_size = 0
        self.actual_data_level = 0
        self.prev_level = -1
        self.draws_at_header = {}
        self.detailn = {}
        self.name_ = None
        self._actual_append_page_no = 0
        self.reset_page_count = False
        self.new_page = False
    """
    Convierte una cadena de texto que contiene el ".kut" en un pdf y retorna la ruta a este último.
    @param name. Nombre de ".kut".
    @param kut. Cadena de texto que contiene el ".kut".
    @param data. Cadena de texto que contiene los datos para ser rellenados en el informe.
    @return Ruta a fichero pdf.
    """

    def parse(self, name, kut, data, report = None, flags = []):

        try:
            self._xml = self._parser_tools.loadKut(kut)
        except Exception:
            self.logger.exception(
                "KUT2FPDF: Problema al procesar %s.kut", name)
            return False
        try:
            self._xml_data = load2xml(data)
        except Exception:
            self.logger.exception("KUT2FPDF: Problema al procesar xml_data")
            return False

        self.name_ = name
        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =
        if report is None:
            from fpdf import FPDF
            self._actual_append_page_no = -1
            self._document = FPDF(self._page_orientation, "pt", self._page_size)
            for f in self._document.core_fonts:
                self.logger.debug("KUT2FPDF :: Adding font %s", f)
                self._avalible_fonts.append(f)
        else:
            self._document = report
        # Seteamos rutas a carpetas con tipos de letra ...
        
        # Cargamos las fuentes disponibles
        next_page_break = (flags[2] == 1) if len(flags) == 3 else True
        page_append = (flags[1] == 1) if len(flags) > 1 else False
        page_display = (flags[0] == 1) if len(flags) > 0 else False
        

        
        if page_append:
            self.prev_level = -1
            self.last_detail = False
        
        page_break = False
        if self.new_page:
            page_break = True
            self.new_page = False
                   
        
        if self.reset_page_count:
            self.reset_page_no()
            self.reset_page_count = False
        
        if self.design_mode:
            print("Append", page_append)
            print("Display", page_display)
            print("Page break", next_page_break)
        
        if next_page_break:
            self.reset_page_count = True
        
        if page_display:
            self.new_page = True
            
            
        
            

        self.processDetails(not page_break)
        
        #FIXME:Alguno valores no se encuentran
        for p in self._document.pages.keys():
            page_content = self._document.pages[p]["content"]
            for h in self.draws_at_header.keys():
                page_content = page_content.replace(h, str(self.draws_at_header[h]))
            
            
            self._document.pages[p]["content"] = page_content
                    
        #print(self.draws_at_header.keys())   
        self._document.set_title(self.name_)
        self._document.set_author("Pineboo - kut2fpdf plugin")
        
        
        return self._document    
        

        
    
    def get_file_name(self):
        import os
        
        pdf_name = aqApp.tmp_dir()
        pdf_name += "/%s_%s.pdf" % (self.name_, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        if self._document is not None:
            self._document.output(pdf_name, 'F')        
            return pdf_name
        else:
            return None
    

    """
    Indica el techo para calcular la posición de los objetos de esa sección.
    @return Número con el techo de la página actual.
    """

    def topSection(self):
        return self._page_top[str(self._document.page_no())]

    """
    Actualiza el valor del techo de la página actual. Se suele actualizar al procesar una sección.
    @param value. Numero que elspecifica el nuevo techo.
    """

    def setTopSection(self, value):
        self._actual_section_size = value - self.topSection()
        self._page_top[str(self._document.page_no())] = value

    """
    Añade una nueva página al documento.
    """

    def newPage(self, data_level, add_on_header = True):
        self._document.add_page(self._page_orientation)
        self._page_top[str(self._document.page_no())] = self._top_margin
        self._document.set_margins(self._left_margin, self._top_margin, self._right_margin)  # Lo dejo pero no se nota nada
        self._no_print_footer = False
        if self.design_mode:
            self.draw_margins()
            
        self._actual_section_size = 0
        self._actual_append_page_no += 1
        if self.design_mode:
            print("Nueva página", self.number_pages())
        
        #l_ini = data_level
        #l_end = self.prev_level
        
        #if l_ini == l_end:
        #    l_end = l_end + 1
        
        #if l_ini <= l_end:
        #    for l in range(l_ini , l_end):
        #        print(l)
        #        self.processSection("AddOnHeader", str(l))
        pg_headers = self._xml.findall("PageHeader")
        
        for ph in pg_headers:
            if self.number_pages() == 0 or ph.get("PrintFrequency") == "1":
                ph_level = ph.get("Level") if ph.get("Level") is not None else None
                self.processSection("PageHeader", ph_level)
                break
        
        
        if add_on_header and not self.number_pages() == 0:
            for l in range(data_level + 1):
                self.processSection("AddOnHeader", str(l))
            
        
        #Por ahora se omite detail header

        
    """
    Procesa las secciones details con sus correspondientes detailHeader y detailFooter.
    """

    def processDetails(self, keep_page = None):
        # Procesamos la cabecera si procede ..
        top_level = 0
        level = 0
        first_page_created = keep_page if keep_page is not None and self._document.page_no() > 0 else False
        
        rows_array = self._xml_data.findall("Row")
        for data in rows_array:
            self._actual_data_line = data
            level = int(data.get("level"))
            if level > top_level:
                top_level = level
                
            if not first_page_created:
                self.newPage(level)
                first_page_created = True
            
            if rows_array[len(rows_array) - 1] is data:
                self.last_detail = True
            
            if level < self.prev_level:
                for l in range(level + 1, self.prev_level + 1):
                    self.processData("DetailFooter", self.last_data_processed, l)    
            
            
            
            
               
            if not str(level) in self.detailn.keys():
                self.detailn[str(level)] = 0
            else:    
                self.detailn[str(level)] += 1
            
            if level > self.prev_level:         
                self.processData("DetailHeader",  data, level)    
                      
                        
            self.processData("Detail", data, level)
            
            self.last_data_processed = data
            
                
            self.prev_level = level
        if not self._no_print_footer:
           for l in reversed(range(top_level + 1)):
               self.processData("DetailFooter", data, l)

    """
    Paso intermedio que calcula si detailHeader + detail + detailFooter entran en el resto de la ṕagina. Si no es así crea nueva página.
    @param section_name. Nombre de la sección a procesar.
    @param data. Linea de datos a procesar.
    @param data_level. Nivel de seccion.
    """

    def processData(self, section_name, data, data_level):
        self.actual_data_level = data_level
        listDF = self._xml.findall(section_name)
        data_size = len(listDF)      
        
        for dF in listDF:
            draw_if = dF.get("DrawIf")
            show = True
            if draw_if:
                show = data.get(draw_if)
            
            
            if dF.get("Level") == str(data_level) and show not in ("None", "False"):
                    
                if section_name in ("DetailHeader","Detail"):
                    heightCalculated = self._parser_tools.getHeight(dF) + self.topSection()
                    
                    if section_name is "DetailHeader":
                        for detail in self._xml.findall("Detail"):
                            if detail.get("Level") == str(data_level):
                                heightCalculated += self._parser_tools.getHeight(detail)
                            
                    for dFooter in self._xml.findall("DetailFooter"):
                        if dFooter.get("Level") == str(data_level):
                            heightCalculated += self._parser_tools.getHeight(dFooter)
                    
                    #for addFooter in self._xml.findall("AddOnFooter"):
                    #    if addFooter.get("Level") == str(data_level):
                    #        heightCalculated += self._parser_tools.getHeight(addFooter)
                    
                    pageFooter = self._xml.get("PageFooter")
                    if pageFooter:
                        if self._document.page_no() == 1 or pageFooter.get("PrintFrecuency") == "1":
                            heightCalculated += self._parser_tools.getHeight(pageFooter)

                    heightCalculated += self._bottom_margin
                    if heightCalculated > self._document.h:  # Si nos pasamos
                        self._no_print_footer = True
                        #Vemos el tope por abajo 
                        limit_bottom = self._document.h - self._parser_tools.getHeight(self._xml.get("AddOnFooter"))
                        actual_size = self._parser_tools.getHeight(dF) + self.topSection()
                        
                        
                        

                        if (actual_size > limit_bottom + 2) or self.last_detail: # +2 se usa de margen extra
                            self.processSection("AddOnFooter", str(data_level))
                            self.newPage(data_level)

                    
                self.processXML(dF, data)
                                    
                if dF.get("NewPage") == "true" and not self.last_detail:
                    self.newPage(data_level, False)
                
                
                break #Se ejecuta una sola instancia

    """
    Procesa las secciones fuera de detail
    @param name. Nombre de la sección a procesar.
    """

    def processSection(self, name, level=0):
        sec_list = self._xml.findall(name)
        sec_ = None
        for s in sec_list:
            if s.get("Level") == str(level) or s.get("Level") is None:
                sec_ = s
        
        if sec_ is not None:
            if sec_.get("PrintFrequency") == "1" or self._document.page_no() == 1 or name in ("AddOnHeader","AddOnFooter"):   
                self.processXML(sec_)

    """
    Procesa un elemento de xml.
    @param xml: El elemento a procesar.
    @param. data: Linea de datos afectada.
    """

    def processXML(self, xml, data=None):
        
        fix_height = True
        if data is None:
            data = self._actual_data_line
        
        if self.design_mode:
            print("Procesando", xml.tag, data.get("level"))
        
        size_updated = False
        if xml.tag == "DetailFooter":
            if xml.get("PlaceAtBottom") == "true":
                self.setTopSection(self._document.h - self._parser_tools.getHeight(xml))
                size_updated = True
        
               
        if xml.tag == "PageFooter":
            fix_height = False

        self.fix_extra_size() #Sirve para actualizar la altura con lineas que se han partido porque son muy largas
        
        
            
        for label in xml.iter("Label"):
            self.processText(label, data, fix_height)
        
        for field in xml.iter("Field"):
            self.processText(field, data, fix_height)
        
        for special in xml.iter("Special"):
            self.processText(special, data, fix_height, xml.tag)
        
        for calculated in xml.iter("CalculatedField"):
            self.processText(calculated, data, fix_height, xml.tag)
        
        
        #Busco draw_at_header en DetailFooter y los meto también
        if xml.tag == "DetailHeader":
            detail_level = xml.get("Level")
            for df in self._xml.iter("DetailFooter"):
                if df.get("Level") == detail_level:
                    for cf in df.iter("CalculatedField"):
                        if cf.get("DrawAtHeader") == "true":
                            header_name = "%s_header_%s_%s" % (self.detailn[detail_level], detail_level, cf.get("Field"))
                            self.draws_at_header[header_name] = ""
                            self.processText(cf, data, fix_height, xml.tag)
            
        
        
        for line in xml.iter("Line"):
            self.processLine(line, fix_height)

        if not size_updated:
            self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml))
        
        
                    

    
    def fix_extra_size(self):
        if self.increase_section_size > 0:
            self.setTopSection(self.topSection() + self.increase_section_size)
            self.increase_section_size = 0    
    """
    Procesa una linea.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processLine(self, xml, fix_height=True):

        color = xml.get("Color")
        r = 0 if not color else int(color.split(",")[0])
        g = 0 if not color else int(color.split(",")[1])
        b = 0 if not color else int(color.split(",")[2])

        style = int(xml.get("Style"))
        width = int(xml.get("Width"))
        X1 = self.calculateLeftStart(xml.get("X1"))
        X1 = self.calculateWidth(X1, 0, False)
        X2 = self.calculateLeftStart(xml.get("X2"))
        X2 = self.calculateWidth(X2, 0, False)
        # Ajustar altura a secciones ya creadas
        Y1 = int(xml.get("Y1")) + self.topSection()
        Y2 = int(xml.get("Y2")) + self.topSection()
        if fix_height:
            Y1 = self._parser_tools.ratio_correction(Y1)
            Y2 = self._parser_tools.ratio_correction(Y2)
        
          
            
        
        self._document.set_line_width(width)
        self._document.set_draw_color(r, g, b)
        dash_length = 1
        space_length = 1
        if style == 2:
            dash_length = 20
            space_length = 20
        elif style == 3:
            dash_length = 10
            space_length = 10
        
        self._document.dashed_line(X1, Y1, X2, Y2, dash_length, space_length)  
        #else:
        #    self._document.line(X1, Y1, X2, Y2)

    """
    Comprueba si excedemos el margen izquierdo de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateLeftStart(self, x):
        return self._parser_tools.ratio_correction(int(x)) + self._left_margin

    """
    Comprueba si excedemos el margen derecho de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateWidth(self, width, pos_x, fix_ratio = True):
        width = int(width)
        if fix_ratio:
            width = self._parser_tools.ratio_correction(int(width))
        ret_ = width
        limit = self._document.w - self._right_margin
        if pos_x + width > limit:
            ret_ = limit - pos_x
        return ret_

    """
    Procesa una etiqueta. Esta puede ser un campo calculado, una etiqueta, un campo especial o una imagen.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processText(self, xml, data_row=None, fix_height=True, section_name = None):
        is_image = False
        is_barcode = False
        text = xml.get("Text")
        borderColor = xml.get("BorderColor")
        field_name = xml.get("Field")
        
        # x,y,W,H se calcula y corrigen aquí para luego estar correctos en los diferentes destinos posibles
        W = int(xml.get("Width"))
        
        H = self._parser_tools.getHeight(xml)
        
        x = int(xml.get("X"))
        
        
        y = int(xml.get("Y")) + self.topSection() # Añade la altura que hay ocupada por otras secciones
        if fix_height:
            y = self._parser_tools.ratio_correction(y)  # Corrige la posición con respecto al kut original
        
        
        
        



        data_type = xml.get("DataType")
        
        if xml.tag == "Field" and data_row is not None:
            text = data_row.get(field_name)

        elif xml.tag == "Special":
            if text == "":
                if xml.get("Type") == "1":
                    text = "PageNo"
            text = self._parser_tools.getSpecial( text, self._actual_append_page_no)

        calculation_type = xml.get("CalculationType")
        
        if calculation_type is not None and xml.tag != "Field":
            if calculation_type == "6":
                function_name = xml.get("FunctionName")
                try:
                    nodo = self._parser_tools.convertToNode(data_row)
                    from pineboolib.pncontrolsfactory import aqApp
                    ret_ = aqApp.call(function_name, [nodo, field_name])
                    if ret_ is False:
                        return
                    else:
                        text = str(ret_)                       
                        
                except Exception:
                    self.logger.exception(
                        "KUT2FPDF:: Error llamando a function %s", function_name)
                    return
            elif calculation_type == "1":
                text = self._parser_tools.calculate_sum(field_name, self.last_data_processed, self._xml_data, self.actual_data_level)
            
            elif calculation_type in ("5"):
                if data_row is None:
                    data_row = self._xml_data[0]
                
                text = data_row.get(field_name)
            
        if data_type is not None:
            text = self._parser_tools.calculated(text, int(data_type), xml.get("Precision"), data_row)
            
        if data_type == "5":
            is_image = True
        
        elif data_type == "6":
            is_barcode = True
            
        
        if xml.get("BlankZero") == "1" and text is not None:
            res_ = re.findall(r'\d+', text)
            res_ = "".join(res_)
            if int(res_) == 0:
                return
            
            

        if text is not None and text.startswith(filedir("../tempdata")):
            is_image = True

        negValueColor = xml.get("NegValueColor")
        Currency = xml.get("Currency")

        commaSeparator = xml.get("CommaSeparator")
        dateFormat = xml.get("DateFormat")

        if is_image:
            self.draw_image(x, y, W, H, xml, text)
        elif is_barcode:
            self.draw_barcode(x, y, W, H, xml, text)
        else:
            level = data_row.get("level")
            if level and str(level) in self.detailn.keys():
                val = "%s_header_%s_%s" % ( self.detailn[str(level)], level,field_name)
            
            if xml.get("DrawAtHeader") == "true" and level:
                if section_name == "DetailHeader":
                    val = ""
                    self.drawText(x, y, W, H, xml, val)
            
                    print(level, section_name, val, text)
            
            if section_name == "DetailFooter" and xml.get("DrawAtHeader") == "true":
                self.draws_at_header[val] = text
                print("Añadiendo a", val, text, level)
            
            else:
                self.drawText(x, y, W, H, xml, text)


    """
    Dibuja un campo texto en la página.
    @param x. Pos x de la etiqueta.
    @param y. Pos y de la etiqueta.
    @param W. Anchura de la etiqueta.
    @param H. Altura de la etiqueta.
    @param xml. Sección del xml afectada.
    @param txt. Texto calculado de la etiqueta a crear.
    """

    def drawText(self, x, y, W, H, xml, txt):


        if txt in ("None", None):
            return
        
        
        txt = self._parser_tools.restore_text(txt)
        
        resizeable = False
        
        if xml.get("ChangeHeight") == "1":
            resizeable = True
        
        
        
        height_resized = False
        orig_x = x
        orig_y = y
        orig_W = W
        orig_H = H
        # Corregimos margenes:
        x = self.calculateLeftStart(x)
        W = self.calculateWidth(W, x)
        
        #bg_color = xml.get("BackgroundColor").split(",")
        fg_color = self.get_color(xml.get("ForegroundColor"))
        self._document.set_text_color(fg_color[0], fg_color[1], fg_color[2])
        
        
        
        #self._document.set_draw_color(255, 255, 255)

        #if xml.get("BorderStyle") == "1":
            # FIXME: Hay que ajustar los margenes
        
        #font_name, font_size, font_style
        font_style = ""
        font_size = int(xml.get("FontSize"))
        font_name_orig = xml.get("FontFamily").lower() if xml.get("FontFamily") is not None else "helvetica"
        font_name = font_name_orig
        
        font_w = xml.get("FontWeight")
        
        if font_w in (None, "50"): #Normal
            font_w = 100
        elif int(font_w) >= 65:
            font_style += "B"
            font_w = 100

        
        
        
        fontI = xml.get("FontItalic")
        fontU = xml.get("FontUnderlined")  # FIXME: hay que ver si es así

        background_color = self.get_color(xml.get("BackgroundColor"))
        #if background_color != [255,255,255]: #Los textos que llevan fondo no blanco van en negrita
        #    font_style += "B"

        if fontI == "1":
            font_style += "I"

        if fontU == "1":
            font_style += "U"
        
        
        

        font_full_name = "%s%s" % (font_name, font_style)

        if font_full_name not in self._avalible_fonts:
            font_found = self._parser_tools.find_font(font_full_name)            
            if font_found:
                self.logger.warning("KUT2FPDF::Añadiendo el tipo de letra %s (%s)", font_full_name, font_found)
                self._document.add_font(font_full_name, "", font_found, True)
                self._avalible_fonts.append(font_full_name)

            else:
                if font_full_name not in self._unavalible_fonts:
                    self.logger.warning("KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica%s." %(font_full_name, font_style))
                    self._unavalible_fonts.append(font_full_name)
                font_name = "helvetica"
        
        if font_name is not font_name_orig and font_name_orig.lower().find("narrow") > -1:
            font_w = 85
                    
        
        self._document.set_font(font_name, font_style, font_size)
        self._document.set_stretching(font_w)
        # Corregir alineación
        VAlignment = xml.get("VAlignment")  # 0 izquierda, 1 centrado,2 derecha
        HAlignment = xml.get("HAlignment")
        
        layout_direction = xml.get("layoutDirection")
        
        start_section_size = self._actual_section_size
        result_section_size = 0
        #Miramos si el texto sobrepasa el ancho
        
        array_text = []
        array_n = []
        text_lines = []
        if txt.find("\n") > -1:
            for t in txt.split("\n"):
                array_n.append(t)
        if array_n: #Hay saltos de lineas ...
            for n in array_n:
                text_lines.append(n)
        else: #No hay saltos de lineas
            text_lines.append(txt)
            
        for tl in text_lines:
            str_width = self._document.get_string_width(tl)
            if str_width > W + 2 and xml.tag !="Label" and resizeable: #Una linea es mas larga que el ancho del campo(Dejando 2 de juego)
                height_resized = True
                array_text = self.split_text(tl, W)
            else:
            
                array_text.append(tl)
        
        #calculated_h = orig_H * len(array_text)
        self.drawRect(orig_x, orig_y, orig_W, orig_H, xml)
        
        processed_lines = 0
        extra_size = 0
        for actual_text in array_text:
            
            if actual_text is None:
                continue
            
            processed_lines += 1
            
            if processed_lines > 1:
                extra_size += font_size + 2
            
            if HAlignment == "1":  # sobre X
                # Centrado
                x = x + (W / 2) - (self._document.get_string_width(actual_text) / 2)
                #x = x + (W / 2) - (str_width if not height_resized else W / 2)
            elif HAlignment == "2":
                # Derecha
                x = x + W - self._document.get_string_width(actual_text) - 2 # -2 de margen
                #x = x + W - str_width if not height_resized else W
            else:
                # Izquierda
                x = x + 2

                
            if VAlignment == "1":  # sobre Y
                # Centrado
                #y = (y + ((H / 2) / processed_lines)) + (((self._document.font_size_pt / 2) / 2) * processed_lines) 
                y = ( orig_y  + ( orig_H / 2))+ ((self._document.font_size_pt / 2) /2)
            elif VAlignment == "2":
                # Abajo
                y = orig_y + orig_H - font_size
            else:
                # Arriba
                y = orig_y + font_size
        
            y = y + extra_size
            
            if self.design_mode:
                self.write_debug(self.calculateLeftStart(orig_x), y, "Hal:%s, Val:%s, T:%s st:%s" % (HAlignment, VAlignment, txt, font_w), 6, "green")
                if xml.tag == "CalculatedField":
                    self.write_debug(self.calculateLeftStart(orig_x), y, "CalculatedField:%s, Field:%s" % (xml.get("FunctionName"), xml.get("Field")), 3, "blue")
            
            
            
            
            self._document.text(x, y, actual_text)
            result_section_size += start_section_size
        
        result_section_size = result_section_size - start_section_size
        
        if self.increase_section_size < extra_size: #Si algun incremento extra hay superior se respeta
            self.increase_section_size = extra_size

    
    def split_text(self, texto, limit_w):
        list_ = []
        linea_ = None   
        
        for t in texto.split(" "):
            if linea_  is None and t == "":
                continue
            
            if linea_ is not None:
                if self._document.get_string_width(linea_ + t) > limit_w:
                    list_.append(linea_)
                    linea_ = ""
            else:
                linea_ = ""
            
            linea_ += "%s " % t
        
        list_.append(linea_)
        
        return list_
                
            
                   
        
    """
    Dibuja un cuadrado en la página actual.
    @param x. Pos x del cuadrado.
    @param y. Pos y del cuadrado.
    @param W. Anchura del cuadrado.
    @param H. Altura del cuadrado.
    """
    def get_color(self, value):
        value = value.split(",")
        r = None
        g = None
        b = None
        if len(value) == 3:
            r = int(value[0])
            g = int(value[1])
            b = int(value[2])
        else:
            r = int(value[0:2])
            g = int(value[3:5])
            b = int(value[6:8])
        
        return [r,g,b]

    def drawRect(self, x, y, W, H, xml = None):
        style_ = ""
        border_color = None
        bg_color = None
        line_width = self._document.line_width
        border_width = 0.2
        #Calculamos borde  y restamos del ancho
        orig_x = x
        orig_y = y
        orig_w = W
        
        x = self.calculateLeftStart(orig_x) 
        W = self.calculateWidth(W, x)
          
        
        if xml is not None and not self.design_mode:
            if xml.get("BorderStyle") == "1":
                
                border_color = self.get_color(xml.get("BorderColor"))
                self._document.set_draw_color(border_color[0], border_color[1], border_color[2])
                style_ += "D"
                    
            
            bg_color = self.get_color(xml.get("BackgroundColor"))
            self._document.set_fill_color(bg_color[0], bg_color[1], bg_color[2])
            style_ =  "F" + style_
            
            border_width = int(xml.get("BorderWidth") if xml.get("BorderWidth") else 0.2)
        else:
            self.write_cords_debug(x,y,W,H, orig_x, orig_w)
            style_ = "D"
            self._document.set_draw_color(0, 0, 0)
            
        if style_ is not "":
            self._document.set_line_width(border_width)

            self._document.rect(x, y, W, H, style_)
            self._document.set_line_width(line_width)
            
            self._document.set_xy(orig_x, orig_y)
        #self._document.set_draw_color(255, 255, 255)
        #self._document.set_fill_color(0, 0, 0)
    
    def write_cords_debug(self, x, y, w, h, ox, ow):
        self.write_debug(x,y,"X:%s Y:%s W:%s H:%s orig_x:%s, orig_W:%s" % (round(x, 2),round(y, 2),round(w, 2),round(h, 2), round(ox, 2), round(ow, 2)), 2, "red")
        
    
    def write_debug(self, x,y,text, h, color = None):
        orig_color = self._document.text_color
        r = None
        g = None
        b = None
        current_font_family = self._document.font_family
        current_font_size = self._document.font_size_pt
        current_font_style = self._document.font_style
        if color is "red":
            r = 255
            g = 0
            b = 0
        elif color is "green":
            r = 0
            g = 255
            b = 0
        elif color is "blue":
            r = 0
            g = 0
            b = 255
        
        self._document.set_text_color(r,g,b)
        self._document.set_font_size(4)
        self._document.text(x, y + h, text) 
        self._document.text_color = orig_color
        #self._document.set_xy(orig_x, orig_y)
        self._document.set_font(current_font_family, current_font_style, current_font_size)
        
    """
    Inserta una imagen en la página actual.
    @param x. Pos x de la imagen.
    @param y. Pos y de la imagen.
    @param W. Anchura de la imagen.
    @param H. Altura de la imagen.
    @param xml. Sección del xml afectada.
    @param file_name. Nombr del fichero de tempdata a usar
    """

    def draw_image(self, x, y, W, H, xml, file_name):
        import os
        if not file_name.lower().endswith(".png"):
            file_name = self._parser_tools.parseKey(file_name)
        
        
        if file_name is not None and os.path.exists(file_name):            
            x = self.calculateLeftStart(x)
            W = self.calculateWidth(W, x)
            
            self._document.image(file_name, x, y, W, H, "PNG")
    
    def draw_barcode(self, x, y, W, H, xml, text):
        if text == "None":
            return
        from pineboolib.fllegacy.flcodbar import FLCodBar
        file_name = aqApp.tmp_dir()
        file_name += "/%s.png" % (text)
        type = xml.get("CodBarType")
        
        if not os.path.exists(file_name):   
            
            bar_code = FLCodBar(text) #Code128
            if type is not None:
                type = bar_code.nameToType(type.lower())
                bar_code.setType(type)
                
            pix = bar_code.pixmap()
            if not pix.isNull():
                pix.save(file_name, "PNG")
            
        self.draw_image(x , y, W, H, xml, file_name)
            
            
            
 
        
    """
    Define los parámetros de la página
    @param xml: Elemento xml con los datos del fichero .kut a procesar
    """

    def setPageFormat(self, xml):
        custom_size = None

        self._bottom_margin = int(xml.get("BottomMargin"))
        self._left_margin = int(xml.get("LeftMargin"))
        self._right_margin = int(xml.get("RightMargin"))
        self._top_margin = int(xml.get("TopMargin"))
        
        page_size = int(xml.get("PageSize"))
        page_orientation = xml.get("PageOrientation")
        
        if page_size in [30, 31]:
            custom_size = [int(xml.get("CustomHeightMM")), int(xml.get("CustomWidthMM"))]

        self._page_orientation = "P" if page_orientation == "0" else "L"
        self._page_size = self._parser_tools.converPageSize(
            page_size, int(page_orientation), custom_size)  # devuelve un array
        
        
    
    def draw_margins(self):
        self.draw_debug_line(0 + self._left_margin , 0, 0+ self._left_margin  , self._page_size[1]) #Vertical derecha
        self.draw_debug_line(self._page_size[0] - self._right_margin , 0, self._page_size[0] - self._right_margin  , self._page_size[1])#Vertical izquierda
        self.draw_debug_line(0, 0 + self._top_margin, self._page_size[0], 0 + self._top_margin) #Horizontal superior
        self.draw_debug_line(0, self._page_size[1] - self._bottom_margin, self._page_size[0], self._page_size[1] - self._bottom_margin) #Horizontal inferior
    def draw_debug_line(self, X1, Y1, X2, Y2, title= None, color="GREY"):
        dash_length = 2
        space_length = 2
        
        r = 0
        g = 0
        b = 0
        if color == "GREY":
            r = 220
            g = 220
            b = 220
        self._document.set_line_width(1)
        self._document.set_draw_color(r, g, b)
        self._document.dashed_line(X1, Y1, X2, Y2, dash_length, space_length)
    
    def number_pages(self):
        return self._actual_append_page_no if self._actual_append_page_no > 0 else 0
    
    def reset_page_no(self):
        self._actual_append_page_no = -1
示例#13
0
def generarpdf(datos, result):

    pdf = FPDF()

    #header of the pdf file
    header = 'Reporte Simulación'
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    w = pdf.get_string_width(header) + 6
    pdf.set_x((210 - w) / 2)
    pdf.cell(w, 9, header, 0, 0, 'C')
    pdf.line(20, 18, 210 - 20, 18)

    pdf.ln(10)
    pdf.set_font('Times', '', 12)
    pdf.multi_cell(0, 5, ' Datos de configuración: ')
    pdf.multi_cell(0, 5, ' Descripción: ' + datos['identificacion'])
    pdf.multi_cell(0, 5, ' Horas de atención: ' + str(datos['horas_atencion']))
    pdf.multi_cell(
        0, 5, ' Cantidad de intervalos: ' + str(datos['cantidad_intervalos']))
    pdf.multi_cell(0, 5, ' Total declientes: ' + str(datos['total_clientes']))
    pdf.multi_cell(0, 5, ' Distribuciones: ' + str(datos['distribuciones']))
    pdf.multi_cell(
        0, 5, ' Cantidad de cajas_abiertas: ' +
        str(datos['cantidad_cajas_abiertas_cada_intervalo']))
    pdf.multi_cell(0, 5,
                   ' Minimo de_productos: ' + str(datos['minimo_productos']))
    pdf.multi_cell(0, 5,
                   ' Maximo_de productos: ' + str(datos['maximo_productos']))
    pdf.multi_cell(0, 5,
                   ' Promedio_seleccion: ' + str(datos['promedio_seleccion']))
    pdf.multi_cell(0, 5,
                   ' promedio_marcado: ' + str(datos['promedio_marcado']))
    pdf.multi_cell(0, 5, ' Promedio_pago: ' + str(datos['promedio_pago']))
    pdf.multi_cell(0, 5, ' -------------------------------------------------')

    for i in range(10):

        pdf.ln()
        pdf.set_font('Arial', '', 12)
        pdf.set_fill_color(200, 220, 255)
        pdf.cell(0, 6, 'Resultados intervalo: ' + str(result[i][0]), 0, 1, 'L',
                 1)

        pdf.ln(10)
        pdf.set_font('Times', '', 12)
        pdf.multi_cell(
            0, 5,
            ' La cantidad de clientes ingresados es: ' + str(result[i][1]))
        pdf.multi_cell(
            0, 5,
            ' La cantidad de clientes despachados es: ' + str(result[i][2]))
        pdf.multi_cell(
            0, 5, ' El promedio de productos por cliente despachado es: ' +
            str(result[i][3]))
        pdf.multi_cell(
            0, 5, ' El promedio de clientes en espera en colas de caja es: ' +
            str(result[i][4]))
        pdf.multi_cell(
            0, 5, ' La longitud maxima de cola de espera en caja fue de: ' +
            str(result[i][5]))
    pdf.ln()
    pdf.set_font('Arial', '', 12)
    pdf.set_fill_color(200, 220, 255)
    pdf.cell(0, 6, 'Tiempo total simulado: ' + str(result[1][6]) + ' minutos.',
             0, 1, 'L', 1)

    #pdf.set_y(0) #on top of the page
    pdf.set_y(-30)  #30 CM from the bottom of the page
    pdf.set_font('Arial', '', 8)
    pdf.set_text_color(0)
    pdf.cell(0, 5, 'Page ' + str(pdf.page_no()), 0, 0, 'C')

    dir = os.getcwd() + "/*.pdf"
    Numero = len(glob.glob(str(dir)))
    Numero += 1
    pdf.output('resultados' + str(Numero) + '.pdf', 'F')
示例#14
0
#!/usr/bin/env python3
#Refer from this site- https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
#Header
pdf.set_font('Arial', 'B', 16)
#width,height,msg,border,align,background
pdf.image('Flo.png', 20, 20, 33)
pdf.multi_cell(
    0, 10,
    'A secret has been encrypted and posted on the blockchain of the FLO cryptocurrency.',
    0, 'C', False)
pdf.multi_cell(
    0, 10,
    'The key to decrypt this secret has been split in 3 shares like this one. By design, the secret can be decrypted with any 2 of these shares.',
    0, 'C', False)
pdf.multi_cell(0, 10,
               'Bellow is the part of the key that belongs to this share', 0,
               'C', False)
#add shared key using multi_cell
#footer
pdf.set_y(-35)
pdf.set_font('Arial', 'B', 8)
pdf.cell(0, 10, 'Page %s' % pdf.page_no(), 0, 0, 'C')
pdf.output('sharedkey.pdf', 'F')
示例#15
0
def report():
    if request.method == 'POST':
        field = request.form['searchfield']
        dtarrived = field[6:] + '-' + field[3:5] + '-' + field[:2]

        message = utils.date_valid(dtarrived)

        if message == None:
            message, pouchs = PouchController.search(
                request.form['searchfield'])
            data = pouchs

            if message == None:
                searchfield = request.form['searchfield']

                filepdf = FPDF('P', 'mm', 'A4')  # Portrait

                filepdf.add_page()
                filepdf.set_font('Arial', '', 10)
                filepdf.cell(190, 4, 'Página ' + str(filepdf.page_no()), 0, 1,
                             'R')
                filepdf.set_font('Arial', 'B', 16)
                filepdf.cell(
                    190, 4, 'Date Arrived Report - ' +
                    searchfield + '          ' + datetime.strftime(
                        datetime.today().now(), '%d/%m/%Y %H:%M'), 0, 1, 'C')
                filepdf.set_font('Courier', '', 10)
                filepdf.cell(190, 4, ' ', 0, 1, 'R')
                # 60 = weight 20 = height by cell 0 = border 1 = break line L = align
                subtitle = '   Date    Pouch      Card       Syndicate       ' \
                           'Company        Quant  Value'
                filepdf.set_font('Courier', '', 10)
                filepdf.cell(190, 4, subtitle, 0, 1, 'L')
                contline = 2
                for reg in data:
                    dtarrive = reg.dtarrived[:2] + '/' + reg.dtarrived[5:7] + '/' \
                               + reg.dtarrived[0:4]
                    codepouch = reg.codepouch
                    codecard = reg.codecard
                    codesynd = reg.codesynd
                    codecomp = reg.codecomp
                    quant = reg.quant
                    value = reg.value

                    if contline > 59:
                        filepdf.add_page()
                        filepdf.set_font('Arial', '', 10)
                        filepdf.cell(190, 4, 'Page ' + str(filepdf.page_no()),
                                     0, 1, 'R')
                        subtitle = '   Date    Pouch      Card       Syndicate       Company        ' \
                                   'Quant  Value'
                        filepdf.set_font('Courier', '', 10)
                        filepdf.cell(190, 4, subtitle, 0, 1, 'L')
                        contline = 2

                    contline += 1

                    filepdf.cell(
                        210, 4, f'{dtarrive:} {codepouch:<10} {codecard:<10} '
                        f'{codesynd:<15} {codecomp:<15} {quant:>4} '
                        f'{value:>6.2f}', 0, 1, 'L')
                try:
                    dtarrived = searchfield[6:] + '-' + searchfield[
                        3:5] + '-' + searchfield[:2]
                    filepdf.output(f'ReportPouch_{dtarrived}.pdf',
                                   'F')  # D - Web   F- Local
                    message = 'Generated Report'
                except Exception:
                    message = 'The file pdf is open'
        flash(message)
    return render_template('Report/search.html')
示例#16
0
		def footer(this):
				this.set_y(-15)
				this.set_font('Helvetica','',10)
				this.cell(0,10,str(FPDF.page_no(this)),0,0,'C')	
示例#17
0
def setava_01(self, stock_taking):
    comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)]))
    autori = stock_taking['author'].strip().split(',')
    datum = str(stock_taking['closed'].date())
    filename = "{}_{}.pdf".format(stock_taking['_id'], ''.join(stock_taking['name'].split()))

    page = 1
    money_sum = 0
    Err = []

    pdf = FPDF('P', 'mm', format='A4')
    pdf.set_auto_page_break(False)

    pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
    pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
    pdf.set_font('pt_sans', '', 12)
    pdf.add_page()

    pdf.set_xy(0, 40)
    pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
    pdf.set_xy(0, 46)
    pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2)

    pdf.set_xy(20, 200)
    pdf.cell(1,0, 'Inventuru provedli:', ln=2)
    for x in autori:
        pdf.cell(1,20, x, ln=2)

    pdf.set_font('pt_sans', '', 8)
    pdf.set_xy(120, 288)
    pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

    pdf.add_page()

    ref = self.get_argument('ref')
    value = self.get_argument('value')
    c_name = self.get_argument('name')
    package = self.get_argument('package')
    ust_id = self.get_argument('ust_id')
    price_predicted = self.get_argument('price_predicted', 0.0)
    price_store = self.get_argument('price_store', 0.0)
    price_final = self.get_argument('price_final', 0.0)
    description = self.get_argument('description', '')
    print(ref.split(','))

    data = self.mdb.stock.aggregate([
            {'$addFields': {'count': {'$sum': '$history.bilance'}}}
        ])

    if exist.count() > 0:
        update = self.mdb.production.update(
            {
                '_id': bson.ObjectId(name),
                "components.Ref": c
            },{
                "$set": {
                "components.$.Ref": c,
                "components.$.Value": value,
                "components.$.Package": package,
                "components.$.UST_ID": ust_id,
                "components.$.price_predicted": price_predicted,
                "components.$.price_store": price_store,
                "components.$.price_final": price_final,
                "components.$.Note": description,
            }
        }, upsert = True)
    else:
        print("NOVA POLOZKA")
        update = self.mdb.production.update(
            {
                '_id': bson.ObjectId(name)
            },{
                "$push": {'components': {
                    "Ref": c,
                    "Package": package,
                    "Value": value,
                    "UST_ID": ust_id,
                    "price_predicted": price_predicted,
                    "price_store": price_store,
                    "price_final": price_final,
                    "Note": description
                    }
                }
            })

    gen_time = datetime.datetime(2018, 10, 1)
    lastOid = ObjectId.from_datetime(gen_time)


    for i, component in enumerate(data):
    #for i, component in enumerate(list(data)[:30]):
        #print(i, "=============================")
        print(component['_id'])
        try:
            ## Pokud je konec stránky
            if pdf.get_y() > pdf.h-20:
                pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(150, pdf.get_y()+1)
                pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                pdf.add_page()

            ## Pokud je nová strana
            if page != pdf.page_no():
                pdf.set_font('pt_sans', '', 8)
                page = pdf.page_no()
                pdf.set_xy(120, 288)
                pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(10, 10)
                pdf.cell(100, 5, 'Skladová položka')
                pdf.set_x(95)
                pdf.cell(10, 5, "Počet kusů", align='R')
                #pdf.set_x(120)
                #pdf.cell(10, 5, "Cena za 1ks", align='R')
                pdf.set_x(180)
                pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                pdf.line(10, 15, pdf.w-10, 15)
                pdf.set_y(18)
                page_sum = 0

            pdf.set_font('pt_sans', '', 10)

            count = component['count']
            price = 0
            price_ks = 0
            first_price = 0

            ref = self.get_argument('Ref')
            val = self.get_argument('Val')
            package = self.get_argument('Package')
            posx = self.get_argument('PosX')
            posy = self.get_argument('PosY')
            rot = self.get_argument('Rot')
            side = self.get_argument('Side')
            tstep = self.get_argument('Tstep')

            inventura = False
            for x in reversed(component.get('history', [])):
                if x.get('operation', None) == 'inventory':
                    #TODO: tady porovnávat, jesti to patri do stejne kampane. Ne na zaklade casu ale ID
                    if x['_id'].generation_time > lastOid.generation_time:
                        inventura = True
                        count = x['absolute']
                        #pdf.set_x(110)
                        #pdf.cell(1, 5, "i")
                        break;

            if count > 0:
                rest = count

                for x in reversed(component.get('history', [])):

                    if x.get('price', 0) > 0:
                        if first_price == 0: 
                            first_price = x['price']
                        if x['bilance'] > 0:
                            if x['bilance'] <= rest:
                                price += x['price']*x['bilance']
                                rest -= x['bilance']
                            else:
                                price += x['price']*rest
                                rest = 0
                
                print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price)
                if(count-rest): price += rest*first_price
                money_sum += price
                page_sum +=price

                if price == 0.0 and x.get('count', 0) > 0:
                    Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id']))


                #pdf.set_x(120)
                #if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R')
                #else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R')

                pdf.set_font('pt_sans', '', 10)
                pdf.set_x(95)
                pdf.cell(10, 5, "{} j".format(count), align='R')

                pdf.set_x(10)
                pdf.cell(100, 5, "{:5.0f}  {}".format(i, component['_id']))

                pdf.set_font('pt_sans-bold', '', 10)
                pdf.set_x(180)
                pdf.cell(10, 5, "%6.2f Kč" %(price), align='R')


        except Exception as e:
            Err.append('Err' + repr(e) + component['_id'])
            print(e)

        if count > 0:
            pdf.set_y(pdf.get_y()+4)

    pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y())
    pdf.set_font('pt_sans', '', 8)
    pdf.set_x(180)
    pdf.cell(10, 5, "Konec souhrnu", align='R')

    #pdf.set_font('pt_sans', '', 10)
    #pdf.set_xy(150, pdf.get_y()+3)
    #pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

    pdf.page = 1
    pdf.set_xy(20,175)
    pdf.set_font('pt_sans', '', 12)
    pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum))
    if len(Err) > 0:
        pdf.set_xy(30,80)
        pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2)
        pdf.set_x(32)
        for ch in Err:
            pdf.cell(1,5,ch,ln=2)
    pdf.page = page

    pdf.output("static/tmp/sestava.pdf")
    year = datum[:4]

    filename = "{}.pdf".format(''.join(stock_taking['name'].split(' ')))
    foldername = os.path.join(tornado.options.options.owncloud_root, 'accounting', year, 'stocktaking', filename)
    foldername = save_file(self.mdb, foldername)
    return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
示例#18
0
pdf.ln()
pdf.set_font('Arial', '', 12)
pdf.set_fill_color(200, 220, 255)
pdf.cell(0, 6, 'Chapter %d : %s' % (1, 'Sample Label'), 0, 1, 'L', 1)

pdf.ln()
pdf.set_font('Courier', 'B', 12)
pdf.multi_cell(
    0, 5,
    'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'
)

pdf.ln()
pdf.set_font('', 'U', 11)
pdf.multi_cell(
    0, 6,
    'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose.'
)

pdf.ln()
pdf.set_font('', 'I')
pdf.cell(0, 5, 'This is italic text')

#pdf.set_y(0)
pdf.set_y(-30)
pdf.set_font('Arial', '', 8)
pdf.set_text_color(0)
pdf.cell(0, 5, 'Page ' + str(pdf.page_no()), 0, 0, 'C')

pdf.output('simple.pdf', 'F')
示例#19
0
    def get(self, name):
        info = list(self.mdb.production.aggregate([
            {'$match': {'_id': bson.ObjectId(name)}},
        #     {'$sort': {'components.Ref': 1}},
        #     # {"$lookup":{
        #     #     "from": 'stock',
        #     #     "localField": 'UST_ID',
        #     #     "foreignField": '_id',
        #     #     "as": 'stock'
        #     # }}
        ]))[0]

        print(info)


        out = list(self.mdb.production.aggregate([
                {'$match': {'_id': bson.ObjectId(name)}},
                {'$unwind': '$components'},
                {'$project': {'components': 1}},
                {'$sort': {'components.Ref': 1}},
                {'$group':{
                    '_id': {'UST_ID': '$components.UST_ID',
                            'Value': '$components.Value',
                            'Footprint': '$components.Footprint',
                            'Distributor': '$components.Distributor',
                            'Datasheet': '$components.Datasheet',
                            'stock_count': '$components.stock_count',
                            'note': '$components.note'},
                    'Ref': {'$push': '$components.Ref'},
                    'category': {'$push': '$components.category'},
                    'count': {'$sum': 1},
                }},
                {"$addFields":{"cUST_ID": {"$convert":{
                         "input": '$_id.UST_ID',
                         "to": 'objectId',
                         "onError": "Err",
                         "onNull": "null"
                }}}},
                {"$lookup":{
                    "from": 'stock',
                    "localField": 'cUST_ID',
                    "foreignField": '_id',
                    "as": 'stock'
                }}
            ]))

        pdf = FPDF('P', 'mm', format='A4')
        pdf.set_auto_page_break(False)
        pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
        pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
        pdf.add_page()

        pdf.set_font('pt_sans', '', 12)
        pdf.set_xy(10, 9)
        pdf.cell(0,5, info.get('name', name))

        pdf.set_font('pt_sans', '', 8)
        pdf.set_y(20)
        pdf.cell(0,5, info.get('description', name))

        pdf.set_font('pt_sans', '', 8)
        pdf.set_xy(170, 3)
        pdf.cell(0, 5, "Strana "+str(pdf.page_no())+"/{nb}", border=0)
        pdf.set_xy(170, 6)
        pdf.cell(0, 5, str(datetime.datetime.now())[:16], border=0)
        if pdf.page_no() == 1:
            pdf.set_xy(170, 9)
            pdf.cell(0, 5, str("Sklad: {}".format('nazev')), border=0)
            pdf.set_xy(10, 13)
            pdf.cell(0, 5, str(name), border=0)

            pdf.set_xy(10, 3)
            pdf.cell(0, 5, "Universal Scientific Technologies s.r.o.")


        row = []
        used = []

        rowh = 9+8
        first_row = 28
        pdf.set_xy(10, 28)

        out = [{
                '_id': {
                    'UST_ID': 'UST_ID',
                    'Value': 'Value',
                    'Footprint': 'FootPrint',
                    'Distributor': 'Distributor',
                    'Datasheet': 'Datasheet',
                    'note': "Poznámka"
                },
                'Ref': ['Ref'],
                'count': '',
                'cUST_ID': "UST_ID",
                'stock': [{'name': 'Název', 'category': ['Kategorie']}]}
            ]+out

        j = 0

        last = 10
        for i, component in enumerate(out):
            print("Component", i, component)
            item_places = self.component_get_positions(component['cUST_ID'], stock = bson.ObjectId(self.get_cookie('warehouse', False)))
            #print("Places:", item_places)

            try:
                name = component.get('stock')[0]['name']
                category = component.get('stock')[0]['category']
            except Exception as e:
                name = ''
                category = []

            j += 1
            if j > 28-14:
                j = 0
                first_row = 10
                print("New page...")
                pdf.add_page()
                pdf.set_font('pt_sans', '', 8)
                pdf.set_xy(170, 3)
                pdf.cell(0, 5, "Strana "+str(pdf.page_no())+"/{nb}", border=0)
                pdf.set_xy(170, 6)
                pdf.cell(0, 5, str(datetime.datetime.now())[:16], border=0)
                pdf.line(10,first_row, 200, first_row )

                pdf.set_xy(10, 3)
                pdf.cell(0, 5, info.get('name', name), border=0)

            if type(component['count']) == 'String' and ['count'] > 5.0:
                last += 15
            else:
                last += 10

            pdf.set_font('pt_sans', '', 8)

            pdf.set_xy(10, first_row+j*rowh)
            pdf.cell(0, 5, str(i)+'.', border=0)


            pdf.set_xy(15, first_row+j*rowh + 11)
            pdf.cell(0, 5, str(', '.join(component['Ref'])), border=0)

            pdf.set_xy(163, first_row+j*rowh)
            pdf.cell(0, 5, str(component['_id'].get('UST_ID', '--')))

            pdf.set_xy(90, first_row+j*rowh + 3.5)
            pdf.cell(0, 5, component['_id'].get('Footprint', '--')[:30])

            pdf.set_xy(90, first_row+j*rowh + 7.5)
            pdf.cell(0, 5, str(component['_id'].get('note', '--')))

            pdf.set_font('pt_sans-bold', '', 7.5)

            pdf.set_xy(90, first_row+j*rowh)
            pdf.cell(0, 5, component['_id'].get('Value', '--')[:30])

            pdf.set_font('pt_sans-bold', '', 9)

            pdf.set_xy(15, first_row+j*rowh)
            pdf.cell(0, 5, name)

            pdf.set_xy(10, first_row+j*rowh + 3.5)
            pdf.cell(0, 5, str(component['count'])+'x', border=0)

            pdf.set_font('pt_sans', '', 8)


            pdf.set_xy(15, first_row+j*rowh + 7)
            pdf.cell(0, 5, str(', '.join(category)), border=0)

            for k, place in enumerate(item_places):
                pdf.set_xy(15, first_row+j*rowh + 3.5)
                pdf.cell(0, 5, place['info'][0]['name'])


            pdf.line(10,first_row+j*rowh + 16, 200, first_row+j*rowh + 16)
            print("===================Value==========================================")

        pdf.alias_nb_pages()
        pdf.output("static/production.pdf")
        with open('static/production.pdf', 'rb') as f:
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "inline; filename=UST_osazovaci_list.pdf")
            self.write(f.read())
        f.close()